Categories
Code Snippets

Remove PHP Mail Special Characters in Subject Field

Let’s say you’d like to insert special characters in the subject of HTML e-mails sent with the PHP mail() function.

You have an email subject which when extracted from my database looks like this..

Coffee & Laptop

Sample code..

$to = 'me@example.com';
$subject = 'Coffee & Laptop';
$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);

Ofcourse, you won’t want the &amp; symbol showing when the email is sent to your client.

Add this line to change the html entities to the proper values:

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

Your code becomes:

$to = 'me@example.com';
$subject = 'Coffee &amp; Laptop';
$subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
$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);

Here’s what the end user sees as the subject when they receive the email:

Coffee & Laptop

Leave a Reply