Home » Php » email – php mail with utf-8 encoding displays incorrectly in Microsoft mail clients

email – php mail with utf-8 encoding displays incorrectly in Microsoft mail clients

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’ve searched and searched for a solution to this but to no avail.

I’m using the php mailer to send out a mixed text / html email, encoded in utf8. Here’s the relevant code:

$headers = "From: $fromPerson\r\n" .
"Content-Transfer-Encoding: 8bit\r\n".
"Reply-To: $fromPerson\r\n" .
"Content-Type: multipart/alternative; boundary=". $mime_boundary_header. "\r\n" .
"X-Mailer: PHP/" . phpversion();

$message = "$notice_text

--$mime_boundary
Content-Type: text/plain; charset='UTF-8'
Content-Transfer-Encoding: 8bit

$textEmail

--$mime_boundary
Content-Type: text/html; charset='UTF-8'
Content-Transfer-Encoding: 8bit

$htmlEmail

--$mime_boundary--";

//mb_detect_encoding($message) returns UTF-8
$mail_sent = @mail( $to, $subject, $message, $headers);

The messages contain Spanish along with those tricky characters. The emails display fine in gmail, hotmail (online outlook), mac mail, phones etc. but not in Windows live mail or Microsoft outlook.

If I manually set the default font in Windows live Mail to utf8 the message displays correctly, but otherwise it does not. If I forward the email from another client to outlook or windows live it displays fine as well.

I could find work arounds I’m sure, but am I missing something? I don’t want to rely on the receivers knowing how to change the encoding of the message, so is there something I need to add to the email to prompt these clients to recognise the encoding?

I apologise if this has been dealt with elsewhere, and I’ll appreciate any advice. It looks like I should just go ahead and use PHPMailer to see if that fixes the problem, but out of personal curiosity it would be interesting to learn why this is happening…

How to&Answers:

I’m not sure that the ' wrapping the charset are necessary, or even correct. Try removing them:

Content-Type: text/plain; charset=UTF-8

Answer:

$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";

Answer:

A modification to Riko’s answer makes for a little cleaner code.

$header_array = [
    "MIME-Version: 1.0",
    "Content-type: text/html; charset=UTF-8",
    "From: [email protected]",
    "Reply-To: [email protected]"
];

$headers = implode("\r\n", $header_array);