PHP mail special characters in subject field

强颜欢笑 提交于 2019-12-18 13:09:44

问题


I would like to insert special characters in the subject of HTML e-mails sent with the PHP mail() function.

I want my subject to look like this:

★ Your new account

I have tried with an HTML entity like ★ (★) or by pasting the symbol directly in my code but that doesn't work either, except on a few e-mail clients.

$to = 'me@example.com';
$subject = '★ Your new account or ★ Your new account';
$message = 'HTML message...';

$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: Me <me@example.com>' . "\r\n";

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

Any advice on how to get this to work properly? Thank you.


回答1:


Try for subject:

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

And then:

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



回答2:


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?=



回答3:


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


来源:https://stackoverflow.com/questions/20806154/php-mail-special-characters-in-subject-field

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