Dealing with UTF-8 text using the PHP mail()-function

On one of my PHP-based websites, users can send mails via a simple text form. I had a problem with special characters in the subject or message body. The webpage has a <meta charset=”utf-8″ />-tag, which causes problems when people enter special characters, like é or € or “smart quotes”. They get sent via the mail()-function and show up like Ã³ or Ã© or â€™.

Deep down in the user comments in the documentation on the mail()-function, I found a small function that solved this easily:

function mail_utf8($to, $subject = '(No subject)', $message = '', $header = '') {
 $header_ = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=UTF-8' . "\r\n";
 $result = mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $header_ . $header);
 return $result;
}

Just use mail_utf8() instead of mail() on a UTF-8 page and a proper UTF-8 mail will be sent out.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.