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 'firstname.lastname@example.org'. You can also use a name before the e-mail address with the format 'John Vaze !email@example.com!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".
$headers.='CC: firstname.lastname@example.org, email@example.com'."\\r\\n";
$headers.='BCC: Baze Vaze !firstname.lastname@example.org!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.='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.='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.
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)