Skip to content
Advertisement

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>n";
$headers .= "Reply-To: $sender_name<$from>n";
$headers .= "X-Sender: $sender_name<$from>n";
$headers .= "X-Mailer: PHP4n"; //mailer
$headers .= "X-Priority: 3n"; //1 UrgentMessage, 3 Normal
$headers .= "MIME-Version: 1.0n";
$headers .= "X-MSMail-Priority: Highn";
$headers .= "Importance: 3n";
$headers .= "Date: $daten";
$headers .= "Delivered-to: $ton";
$headers .= "Return-Path: $sender_name<$from>n";
$headers .= "Envelope-from: $sender_name<$from>n";
$headers .= "Content-Transfer-Encoding: 8bitn";
$headers .= "Content-Type: text/plain; charset=UTF-8n";

Advertisement

Answer

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)."?="
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement