Sending UTF-8, HTML, etc. mails with PHP mail()
Sometimes you just have to send an e-mail with PHP. Contact forms, notifications, forgotten passwords, registration confirmations, whatever. PHP's mail() is an easy solution and with a little tweaking it is capable to do a lot.
The basic format for mail() is like this (well for our purposes... but you can check the complete reference):
mail ($to, $subject, $message, $headers);
Returns boolean true if sending the mail was successful.
Defining the recipient address(es):
Basicly, you just write a simple e-mail like 'vaze@retek.hu'. You can also use a name before the e-mail address with the format 'John Vaze !lt!vaze@retek.hu!gt!'. Sometimes you want several recipients, in this case you must separate them with commas.
Defining From:, CC:, BCC:, Reply-To headers:
Do these in $headers. You should separate header definitions with a "\\r\\n".
For example:
$headers='From: mocsk@retek.hu'."\\r\\n";
$headers.='Reply-To: mocsk@retek.hu'."\\r\\n";
$headers.='CC: mocsk@retek.hu, gihi@retek.hu'."\\r\\n";
$headers.='BCC: Baze Vaze !lt!bv@retek.hu!gt!'."\\r\\n";
Sending HTML e-mail:
To be able to send nice-looking e-mails, you need this. All you have to do is include these headers:
$headers.='MIME-version: 1.0'."\\r\\n";
$headers.='Content-type: text/html; charset=iso-8859-1'."\\r\\n";
Sending UTF-8 headers:
When dealing with customers from different nations, it is a must to use a character set which supports a wide range of characters. For example, Hungarian language uses ő and ű. The best answer is to use UTF-8.
$headers.='MIME-version: 1.0'."\\r\\n";
$headers.='Content-type: text/html; charset=utf-8'."\\r\\n";
If you don't need HTML, you can use text/plain. Remember that this applies only to $message, but not $subject and the names before the e-mail addresses. You have to convert these.
$subject='=?UTF-8?B?'.base64_encode($subject).'?=';
Remember that in $to, From:, etc. you should not convert the e-mail addresses, only the names! So don't convert the whole string, only the names.
(of course for UTF-8 to work normally the strings you use should be UTF-8, so either use UTF-8 in the database or utf8_encode(), or if you are using constant string in the code, the PHP file itself should be UTF-8)