显示名称而非电子邮件地址的电子邮件头格式是什么?

60

我正在尝试使用MySQL数据库创建一个处理邮件列表的PHP脚本,大部分内容已经完成。不幸的是,我似乎无法正确地获取邮件头信息,而且不确定问题在哪里。

$headers='From: noreply@rilburskryler.net \r\n';
$headers.='Reply-To: noreply@rilburskryler.net\r\n';
$headers.='X-Mailer: PHP/' . phpversion().'\r\n';
$headers.= 'MIME-Version: 1.0' . "\r\n";
$headers.= 'Content-type: text/html; charset=iso-8859-1 \r\n';
$headers.= "BCC: $emailList";

我在接收端得到的结果是:

"noreply"@rilburskryler.net rnReply-To: noreply@rilburskryler.netrnX-Mailer: PHP/5.2.13rnMIME-Version: 1.0

3个回答

136

要显示名称而不是电子邮件地址,请使用以下代码:

"John Smith" <johnsemail@hisserver.com>

简单。

关于断开的换行符,那是因为你用了撇号而非引号来包裹文本:

$headers = array(
  'From: "The Sending Name" <noreply@rilburskryler.net>' ,
  'Reply-To: "The Reply To Name" <noreply@rilburskryler.net>' ,
  'X-Mailer: PHP/' . phpversion() ,
  'MIME-Version: 1.0' ,
  'Content-type: text/html; charset=iso-8859-1' ,
  'BCC: ' . $emailList
);
$headers = implode( "\r\n" , $headers );

9
当显示名称包含空格字符时,需要使用引号将其括起来。 - Gumbo
3
刚刚测试了一下,没有用引号也可以。不确定这是否是标准格式,或者只是一种非常灵活宽容的结构... - Luke Stevenson
我认为一般情况下使用引号是个好主意。感谢您提供详细的答案。 - RonLugge
这个答案是一个误导,因为From: noreply@rilburskryler.net是RFC 5322中BNF规则允许的有效头部。请参考第3.4节。我怀疑Gumbo关于转义的回答才是真正的问题所在。 - james.garriss
我发现说双引号可以使用引用,单引号对我来说不起作用。我在Gmail中收到了这封电子邮件。 - Benjamin Jesuiter
显示剩余5条评论

11

单引号字符串中,只有转义序列\'\\ 被分别替换为'\。你需要使用双引号来让转义序列\r\n被替换为相应的字符:

$headers = "From: noreply@rilburskryler.net \r\n";
$headers.= "Reply-To: noreply@rilburskryler.net\r\n";
$headers.= "X-Mailer: PHP/" . phpversion()."\r\n";
$headers.= "MIME-Version: 1.0" . "\r\n";
$headers.= "Content-type: text/html; charset=iso-8859-1 \r\n";
$headers.= "BCC: $emailList";

你也可以使用数组来收集标题字段,然后将它们组合在一起:
$headers = array(
    'From: noreply@rilburskryler.net',
    'Reply-To: noreply@rilburskryler.net',
    'X-Mailer: PHP/' . phpversion(),
    'MIME-Version: 1.0',
    'Content-type: text/html; charset=iso-8859-1',
    "BCC: $emailList"
);
$headers = implode("\r\n", $headers);

-1
    $to = 'SendersName@domain.com';
    $to .=', ' . $_POST['Femail'];
    $subject = 'Contact Us Form';

// message
$message ="<html>
<head>
<title>Email title</title>
</head>
<body>
<h3>important message follows</h3>
<div>
     you are being brought this email to be safe.
</div>
</body>
</html>";


    // To send HTML mail, the Content-type header must be set
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    // Additional headers
    $headers .= 'To: SendersEmailName <SendersEmailName@domain.com>' . "\r\n";
    $headers .= 'From: YourName <YourName@domain.com>' . "\r\n";
    $headers.='X-Mailer: PHP/' . phpversion()."\r\n";
    $headers.= "BCC: $emailList";


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接