如何在utf8中发送电子邮件

时间:2012-12-05 20:55:32

标签: php email utf-8 sendmail

我想以utf8编码发送此电子邮件的消息..

我能为此做些什么

include 'functions.php';
    $name = stripslashes($_POST['name']);
    $email = trim($_POST['email']);
    $subject = stripslashes($_POST['subject']);
    $message = stripslashes($_POST['message']);
    $cap=strtoupper($_POST['cap']);

    $error = '';


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

我能用utf8发送什么内容?

3 个答案:

答案 0 :(得分:2)

您可以在电子邮件标头中指定编码,如下所示:

$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());

答案 1 :(得分:1)

你可以使用php的utf8_encode函数。像这样:

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

这将在$ message变量或其他任何其他内容中存储字符串utf8。

修改

如果使用swiftmailer库,则默认为utf8编码。

答案 2 :(得分:0)

您需要在标头中设置utf-8编码并对主题进行编码,因为它很容易被破坏。我个人创建了自己的功能,还增加了设置发件人地址的功能:

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));
}