Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

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

How can I send an email formatted as "Name <user@example.com>" to:

??????¥μàá?????éê?í??Dòó???ùüY?àáa???èé?ìí??e?ó????ù?y? <user@example.com>

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 '¥μàá??????èéê?ìí??D?òó????ùú?üY?àáa?????èéê?ìí??e?òó????ùú?üy? ' 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 = "???????¥μàá??????èéê?ìí??D?òó????ùú?üY?àáa?????èéê?ìí??e?òó????ùú?üy? <CHANGED@gmail.com>";
 $subject = "Test Subject";
 $body = "Test Body";
 if (mail($to, $subject, $body)) {
   echo("<p>Message successfully sent!</p>");
  } else {
   echo("<p>Message delivery failed...</p>");
  }
 ?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

mb_internal_encoding('UTF-8');

$name  = '山本';
$email = 'yamamoto@example.com';
$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?= <yamamoto@example.com>
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: 山本 <yamamoto@example.com>
Subject: こんにちは

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...