Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

Email from PHP has broken Subject header encoding

My PHP script sends email to users and when the email arrives to their mailboxes, the subject line ($subject) has characters like a^£ added to the end of my subject text. This is obviously and encoding problem. The email message content itself is fine, just the subject line is broken.

I have searched all over but can’t find how to encode my subject properly.

This is my header. Notice that I’m using Content-Type with charset=utf-8 and Content-Transfer-Encoding: 8bit.

//set all necessary headers
$headers = "From: $sender_name<$from>
";
$headers .= "Reply-To: $sender_name<$from>
";
$headers .= "X-Sender: $sender_name<$from>
";
$headers .= "X-Mailer: PHP4
"; //mailer
$headers .= "X-Priority: 3
"; //1 UrgentMessage, 3 Normal
$headers .= "MIME-Version: 1.0
";
$headers .= "X-MSMail-Priority: High
";
$headers .= "Importance: 3
";
$headers .= "Date: $date
";
$headers .= "Delivered-to: $to
";
$headers .= "Return-Path: $sender_name<$from>
";
$headers .= "Envelope-from: $sender_name<$from>
";
$headers .= "Content-Transfer-Encoding: 8bit
";
$headers .= "Content-Type: text/plain; charset=UTF-8
";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update???For a more practical and up-to-date answer, have a look at Palec’s answer.


The specified character encoding in Content-Type does only describe the character encoding of the message body but not the header. You need to use the encoded-word syntax with either the quoted-printable encoding or the Base64 encoding:

encoded-word = "=?" charset "?" encoding "?" encoded-text "?="

You can use imap_8bit for the quoted-printable encoding and base64_encode for the Base64 encoding:

"Subject: =?UTF-8?B?".base64_encode($subject)."?="
"Subject: =?UTF-8?Q?".imap_8bit($subject)."?="

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...