How to send UTF-8 email?

PhpEmailUtf 8

Php Problem Overview


When I send out the email, the email does not show characters other than english. It does show like below:

> 余生ä»ä»

May know actually what cause this? Even I tried to added Content-type and charset in the script, it still show the same.

I used Mail::Factory("mail");

Php Solutions


Solution 1 - Php

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

Solution 2 - Php

I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:

function utf8_to_latin2($str)
{
	return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
	{
		mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
		"From: $form\r\n".
		"Reply-To: $reply\r\n".
		"X-Mailer: PHP/" . phpversion());
	}

I have made another mailer function, because apple device could not read well the previous version.

function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
	$s= "=?utf-8?b?".base64_encode($s)."?=";
	$headers = "MIME-Version: 1.0\r\n";
	$headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
	$headers.= "Content-Type: text/plain;charset=utf-8\r\n";
	$headers.= "Reply-To: $reply\r\n";	
	$headers.= "X-Mailer: PHP/" . phpversion();
	mail($to, $s, $body, $headers);
}

Solution 3 - Php

If not HTML, then UTF-8 is not recommended. koi8-r and windows-1251 only without problems. So use html mail.

$headers['Content-Type']='text/html; charset=UTF-8';
$body='<html><head><meta charset="UTF-8"><title>ESP Notufy - ESP Сообщения</title></head><body>'.$text.'</body></html>';


$mail_object=& Mail::factory('smtp',
    array ('host' => $host,
        'auth' => true,
        'username' => $username,
        'password' => $password));
$mail_object->send($recipents, $headers, $body);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondeepWebMieView Question on Stackoverflow
Solution 1 - Phps.webbanditView Answer on Stackoverflow
Solution 2 - Phpuser669677View Answer on Stackoverflow
Solution 3 - Phpvml vmlView Answer on Stackoverflow