Asked  9 Months ago    Answers:  5   Viewed   58 times

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' . "rn";
$headers .= 'Content-type: text/html; charset=utf-8' . "rn";
$headers .= 'From: Me <me@example.com>' . "rn";

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

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

 Answers

87

Try for subject:

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

And then:

mail($to, $sub, $message, $headers);
Wednesday, March 31, 2021
 
akohout
answered 9 Months ago
79

Did you try iconv_set_encoding ?

This should work :

<?php
 iconv_set_encoding("internal_encoding", "UTF-8");

$subject = "Testmail — Special Characters";
$msg = "Hi there,nnthis isn’t something easy.nnI haven’t thought that it’s that complicated!";

mail(utf8_decode($to), utf8_decode($subject), utf8_decode($msg), utf8_decode($from)."nContent-Type: text/plain; charset=UTF-8nContent-Transfer-Encoding: 8bitn");?>
Wednesday, March 31, 2021
 
nasty
answered 9 Months ago
50

You have to set the third parameter of htmlentities() which tells the charset to use. Because of you don't set it, the default is used and the default is ISO-8859-1, not UTF-8.

Like htmlspecialchars(), it takes an optional third argument charset which defines character set used in conversion. Presently, the ISO-8859-1 character set is used as the default.

Just to clarify, this is the function signature:

string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $charset [, bool $double_encode = true ]]] )

and here you'll find the official doc: http://php.net/manual/en/function.htmlentities.php

Wednesday, March 31, 2021
 
Noob_Programmer
answered 9 Months ago
15

If you use utf-8 try this:

<?php $subject = "=?UTF-8?B?" . base64_encode($subject) . "?="; ?>
Wednesday, March 31, 2021
 
brombeer
answered 9 Months ago
78

I found the answer! It's inspired by this answer

$title = "Hunting, Tactical & Outdoor Optics eCommerce Store ?Çô $595,000 ?Çö SOLD";
$title = str_replace(html_entity_decode('&ndash;', ENT_COMPAT, 'UTF-8'), '-', $title);
$title = str_replace(html_entity_decode('&mdash;', ENT_COMPAT, 'UTF-8'), '-', $title);

Replacing the character right away won't work. html_entity_decode is definitely needed.

Friday, May 28, 2021
 
mgraph
answered 7 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share