Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use special characters in recipients name when using PHP's mail function

How can I send an email formatted as "Name <[email protected]>" to:

ŠŒŽœžŸ¥µÀÁÃÄÅÆÇÉÊËÍÎÏÐÒÓÕÖØÙÜÝßàáâåæçèéëìíîïðñóôõöøùûýÿ <[email protected]>

Obviously, many of these characters will never show up in a name, but in case they do, I would prefer that they do not prevent an email from being successfully sent.

Currently, this fails as noted in Apache's error.log with

Ignoring invalid 'To:' recipient address '¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ ' Transaction aborted: no recipients specified

If possible, I would like to keep the special characters 'as they are.' Otherwise, can I use some sort of transliteration function to clean-up the name?

Example of usage:

 <?php
 $to = "ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ <[email protected]>";
 $subject = "Test Subject";
 $body = "Test Body";
 if (mail($to, $subject, $body)) {
   echo("<p>Message successfully sent!</p>");
  } else {
   echo("<p>Message delivery failed...</p>");
  }
 ?>
like image 687
Citricguy Avatar asked Oct 06 '11 02:10

Citricguy


People also ask

How do I get special characters in an email?

On the Insert menu, click Advanced Symbol, and then click the Special Characters tab. Click the character that you want.

What is the correct syntax of mail () function in PHP?

"\r\n"; mail($to,$subject,$message,$headers);

How do I set the name of an email sender via PHP?

$to = "[email protected]"; $message = "Your message here."; $subject = "Your subject"; mail($to,$subject,$message,$header, '-f [email protected] -F "Jack Sparrow"') or die(); Just add the -f parameter to provide the sender's email and -F parameter to provide the sender's name to the mail(), all as a string.


1 Answers

mb_encode_mimeheader should do it, just as shown in the example:

mb_internal_encoding('UTF-8');

$name  = '山本';
$email = '[email protected]';
$addr  = mb_encode_mimeheader($name, 'UTF-8', 'Q') . " <$email>";

For better compatibility you should set the header Mime-Version: 1.0 so all mail clients understand you're using MIME encoding.

The final email headers should look like this:

To: =?UTF-8?Q?=E5=B0=81=E3=83=90=E3=83=BC?= <[email protected]>
Subject: =?UTF-8?Q?=E3=81=93=E3=82=93=E3=81=AB=E3=81=A1=E3=81=AF?=
Mime-Version: 1.0

Renders as:

To: 山本 <[email protected]>
Subject: こんにちは

Related: https://stackoverflow.com/a/13569317/476

like image 104
deceze Avatar answered Oct 26 '22 07:10

deceze