views:

434

answers:

4

I tried to send a text email with non-English characters using PHPs mail function. But instead my message went with funny looking garbage characters. How do I fix it?

I use this piece of code:

function _mail($to, $subject, $content)
{

 $headers = 'From: [email protected]' . "\r\n" .
    'Reply-To: [email protected]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

 mail($to, $subject, $content, $headers);
}

Some of the characters came out as question marks...

+5  A: 

This is definitely a case for Joel's article The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).

You must understand the role of character encodings before you can successfully solve this problem.

Greg Hewgill
True, but not really an answer to the question IMHO; more like a pointer in the right direction.
Mathias Bynens
@Mathias, this was more than I could have come up with given the original question... ;-)
Arjan
+3  A: 

A mail wrapper such as Swiftmailer might help you.

Blair McMillan
+1  A: 

You might want to check out PEAR's MAIL_MIME

Martin Hohenberg
+2  A: 

The key is to use the UTF-8 character set.

Add Content-Type: text/html; charset=UTF-8, MIME-Version 1.0 and Content-Transfer-Encoding: quoted-printable to the mail headers, like this:

$headers = 'From: [email protected]' . "\r\n" .
           'Reply-To: [email protected]' . "\r\n" .
           'Content-Type: text/html; charset=UTF-8' . "\r\n" .
           'MIME-Version: 1.0' . "\r\n" .
           'Content-Transfer-Encoding: quoted-printable' . "\r\n" .
           'X-Mailer: PHP/' . phpversion(); // Why would you want to send this header?

If you would be using HTML instead of text, you’d also need to add a META tag to the HEAD of your (X)HTML mail:

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
Mathias Bynens
You will also need `MIME-Version: 1.0` and to `Content-Transfer-Encoding: quoted-printable` the body, as UTF-8 characters typically won't make it through the mail system intact otherwise.
bobince
Thanks, bobince! I updated my post.
Mathias Bynens
But obviously, when using quoted-printable, then the message should be encoded as such as well.
Arjan