PHP mail special characters in subject field

ⅰ亾dé卋堺 提交于 2019-11-30 09:04:14

Try for subject:

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

And then:

mail($to, $sub, $message, $headers);

While the accepted answer works fine, it makes it impossible to read the subject when looking at the raw headers. Here's an alternative that keeps the line readable and also shorter if it consists of mostly ascii characters.

$subject = '=?UTF-8?q?' . quoted_printable_encode($subject) . '?=';

Here's the encoded subject line of the accepted answer:

=?UTF-8?B?4piFIFlvdXIgbmV3IGFjY291bnQ=?=

Here's the encoded subject line of my answer:

=?UTF-8?q?=E2=98=85 Your new account?=
 $headers="";    
 $message = utf8_encode($message);
 $message = wordwrap($message, 70, "\r\n");
 $subject = '=?UTF-8?B?'.base64_encode(utf8_encode($subject)).'?=';
 $to_name = '=?UTF-8?B?'.base64_encode(utf8_encode($to_name)).'?=';
 $from_name = '=?UTF-8?B?'.base64_encode(utf8_encode($from_name)).'?=';

 $headers .= "MIME-Version: 1.0" . "\r\n"; 
 $headers .= "Content-type: text/plain; charset=utf-8" . "\r\n"; 
 //$headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n"; 
 $headers .= "From: $from_name <$from_email>" . "\r\n"; 
 $headers .= "To: $to_name <$to_email>" . "\r\n";
 $headers .= "Subject: $subject" . "\r\n";
 $headers .= "X-Mailer: PHP/" . phpversion();  

 mail("", $subject, $message, $headers); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!