虽然接受的答案工作正常,但在查看原始标题时无法阅读主题。这是一个替代方案,可以保持行的可读性,如果它主要由ascii字符组成,则也更短。
$subject = '=?UTF-8?q?' . quoted_printable_encode($subject) . '?=';
以下是已接受答案的编码主题行:
=?UTF-8?B?4piFIFlvdXIgbmV3IGFjY291bnQ=?=
这是我的答案的编码主题行:
=?UTF-8?q?=E2=98=85 Your new account?=
编辑:
事实证明,根据RFC 2045的要求,它将长字符串拆分为最多75个字符的多行。结果是一个不能与 的参数一起使用的字符串。下面是解决此问题的更新版本。它还将避免对纯 ascii 主体进行编码。quoted_printable_encode()
mail()
$subject
/**
* Make sure the subject is ASCII-clean
*
* @param string $subject Subject to encode
*
* @return string Encoded subject
*/
function getEncodedSubject(string $subject): string {
if (!preg_match('/[^\x20-\x7e]/', $subject)) {
// ascii-only subject, return as-is
return $subject;
}
// Subject is non-ascii, needs encoding
$encoded = quoted_printable_encode($subject);
$prefix = '=?UTF-8?q?';
$suffix = '?=';
return $prefix . str_replace("=\r\n", $suffix . "\r\n " . $prefix, $encoded) . $suffix;
}
解释:
$subj = "Lorem ipsuöm dolor sit amet, consectetur adipiscing elit. Praesent mattis molestie purus, non semper lectus dictum eget.";
后quoted_printable_encode
Lorem ipsu=C3=B6m dolor sit amet, consectetur adipiscing elit. Praesent mat=
tis molestie purus, non semper lectus dictum eget.
后str_replace
=?UTF-8?q?Lorem ipsu=C3=B6m dolor sit amet, consectetur adipiscing elit. Praesent mat?=
=?UTF-8?q?tis molestie purus, non semper lectus dictum eget.?=