WordPress邮件在Gmail中邮件头乱码的问题及解决

第一次安装WordPress目的是为了测试及熟悉特性,按惯例起名为“测试沙盒”,哪知收到的竟然是来自“æµè¯æ²ç”的邮件;进一步使用时发现通知邮件的主题也有乱码现象;另外,这个问题也在我使用的插件“Contact Form ][”发送的联系邮件中出现。

几乎所有第一次使用php的mail()发送中文邮件头的开发者都遇到过这个问题,下面我要说的原因及解决方案包括但不限于在WordPress上使用。

原因:

看一看“测试沙盒”这四个字的编码:

测[E6 B5 8B]UTF-8
试[E8 AF 95]UTF-8
沙[E6 B2 99]UTF-8
盒[E7 9B 92]UTF-8

对比一下“æµè¯æ²ç”的编码:

æ [E6]URL-encode
µ [B5]URL-encode
è [E8]URL-encode
¯ [AF]URL-encode
æ [E6]URL-encode
² [B2]URL-encode
ç [E7]URL-encode

看出来了吧?16位的8和9开头的字节会被过滤掉!
因为根据RFC文档中的
RFC4021 Registration of Mail and MIME Header Fields
2.1.11. Header Field: Subject

RFC2822 Internet Message Format
3.6.5. Informational fields

header只传送8位字节的低7位,最高位是1的字节会被过滤。

怎么办?

解决方案:

用base64重新编码是最简单的办法。

格式

$subject = "=?UTF-8?B?".base64_encode($subject)."?=";

具体应用:

要修改的文件一共有三个:
wp-admin\install.php
wp-includes\pluggable-functions.php
wp-content\plugins\wp-contact-form\wp-contactform.php

wp-admin\install.php中的184行

$message_headers = 'From: "' . $weblog_title . '" ';

替换为

$message_headers = 'From: "' . "=?UTF-8?B?".base64_encode($weblog_title)."?=" . '" ';

wp-includes\pluggable-functions.php中的165行

return @mail($to, $subject, $message, $headers);

替换为

return @mail($to, "=?" . get_settings('blog_charset') . "?B?" . base64_encode($subject) . "?=", $message, $headers);

372行

$from = "From: \"$blogname\" <$wp_email>";

替换为

$from = "From: =?" . get_settings('blog_charset') . "?B?" . base64_encode("\"$blogname\"") . "?= <$wp_email>";

376行

$from = "From: \"$comment->comment_author\" <$wp_email>";

替换为

$from = "From: =?" . get_settings('blog_charset') . "?B?" . base64_encode("\"$comment->comment_author\"") . "?= <$wp_email>";

wp-content\plugins\wp-contact-form\wp-contactform.php中的187行和199行

$headers .= "From: $name <$email>\n";

都替换为

$headers .= "From: =?" . get_settings('blog_charset') . "?B?" . base64_encode($name) . "?= <$email>\n";

196行

mail($email, $subject ." ". $subj_suffix, $fullmsg, $headers);

替换为

mail($email, "=?" . get_settings('blog_charset') . "?B?" . base64_encode($subject ." ". $subj_suffix) . "?=", $fullmsg, $headers);

207行

mail($recipient, $subject ." ". $subj_suffix, $fullmsg, $headers);

替换为

mail($recipient, "=?" . get_settings('blog_charset') . "?B?" . base64_encode($subject ." ". $subj_suffix) . "?=", $fullmsg, $headers);

另外,附已经修改好的文件供下载:
wp-admininstall.php
wp-includes\pluggable-functions.php
wp-content\plugins\wp-contact-form\wp-contactform.php

当前日志信息

没有响应