Oscar Galo
Oscar Galo

Reputation: 358

Can't send emojis in subject when sending mail with PHPMailer

My PHPMailer relevant options are configured like this:

$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->SMTPAuth = true;
$mailer->CharSet = "UTF-8";
$mailer->isHTML(true);

Then, if i try to send an email to my hotmail.com account, with some emojis in the subject field like this:

$foo = "\xF0\x9F\x94\xA5 text \xF0\x9F\x94\xA5";
$mail->Subject = $foo;
$mail->Body = "<p style='font-size:100px'>Mail body: $foo</p>";

The mail is sent ok and the word "text" surrounded by two little fire emojis appears correctly in the email subject. The mail body appears correctly also:

enter image description here

. If i try this:

$foo = "\xF0\x9F\x94\xA5 text text \xF0\x9F\x94\xA5";
$mail->Subject = $foo;
$mail->Body = "<p style='font-size:100px'>Mail body: $foo</p>";

again subject and body appears correctly:

enter image description here

but if i add another "text" word:

$foo = "\xF0\x9F\x94\xA5 text text text \xF0\x9F\x94\xA5";
$mail->Subject = $foo;
$mail->Body = "<p style='font-size:100px'>Mail body: $foo</p>";

then this happens:

enter image description here

so the subject emojis are replaced with 4 question marks each (the 4 bytes comprising the emoji unicode character maybe?)

What is happening?

Upvotes: 3

Views: 2248

Answers (1)

Sammitch
Sammitch

Reputation: 32272

If it was just one provider or the other I'd say it was them, but both feels unlikely. I would wager that it's something on the sending end like an outbound filter that's improperly mangling the header. While you can specify the charset and encoding for the body of an email, the headers must be 7-bit safe, so if you want to use a fancier charset it has to follow the format specified in RFC1342.

I would wager that there's something in the outbound mail infrastructure that's decoding, and then incorrectly re-encoding the subject header. I would suggest contacting the administrators of your outbound mailing service and/or testing through another provider.

In the meantime, you can manually encode the subject line yourself, as the PHPMailer code shouldn't kick in unless it detects a non-7bit-safe character. eg:

function encode_subject($subject, $charset, $force=false) {
    if( !$force && $subject === quoted_printable_encode($subject) ) {
        return $subject;
    }
    return sprintf('=?%s?Q?%s?=', $charset, quoted_printable_encode($subject));
}

Upvotes: 2

Related Questions