Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 536
Michael Beeson Avatar asked May 23 '13 13:05

Michael Beeson


3 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
like image 193
Arnaud Le Blanc Avatar answered Oct 16 '22 22:10

Arnaud Le Blanc


$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";
like image 41
Rashad Avatar answered Oct 16 '22 23:10

Rashad


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);
like image 27
CodingInTheUK Avatar answered Oct 16 '22 21:10

CodingInTheUK