How to send an email in utf8

老子叫甜甜 提交于 2019-12-02 07:56:00

You can specify the encoding in the email headers, like so:

$mail = mail(WEBMASTER_EMAIL,$subject,$message,
        "From: ".$name." <".$email.">\r\n"
        ."Reply-To: ".$email."\r\n"
        ."Content-type: text/html; charset=UTF-8\r\n"
        ."X-Mailer: PHP/" . phpversion());

You can use php's utf8_encode function. Like so:

$message = utf8_encode(stripslashes($_POST['message']));

This will store the string utf8 encoded in your $message variable or any other for that matter.

Edit:

If you use the swiftmailer library, it will default to utf8 encoding.

You need to set the utf-8 encoding in the headers and also encode the subject, because it easily gets corrupted. I personally create my own function which also adds the ability to set the sender's adress:

function mail_utf8 ($to, $subject='', $message='', $from='', $header='') {
  if (preg_match("/\<html.*\>/i", $message))
    $content_type = "html";
  else
    $content_type = "plain";

  $header .= "\nMIME-Version: 1.0";
  $header .= "\nContent-type: text/$content_type; charset=UTF-8";
  if ($from)
    $header .= "\nFrom: ".$from;
  mail($to, "=?UTF-8?B?".base64_encode($subject)."?=", $message, trim($header));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!