在PHP邮件函数中设置$ headers数组时出现问题

6

当我将一个 $headers 数组指定为参数时,我无法通过 PHP mail 函数发送电子邮件。

$headers = array (
               'From' => "info@mysite.com",
               'Content-type' => "text/html;charset=UTF-8"
               );

或者

$headers=array(
    'From: "info@mysite.com',
    'Content-Type:text/html;charset=UTF-8',
    'Reply-To: "info@mysite.com'
);

以下是代码:

 <?php
   $email = 'test@test.com';
   $headers=array(
    'From: "info@mysite.com',
    'Content-Type:text/html;charset=UTF-8',
    'Reply-To: info@mysite.com'
);

$msg= 'This is a Test';

 mail($email, "Call Back Requert Confirmation", $msg, $headers);
?>

请问您能告诉我为什么会出现这种情况吗?并且我应该如何解决这个问题呢?


发送标题应该是字符串而不是数组。 - Rakesh Sharma
嗨,老实说我没有尝试过。 - Suffii
使用 join("\r\n", $headers) - Ja͢ck
2
没试过什么?阅读文档? - Barmar
4个回答

5
如果你想通过数组发送 $headers,那么你需要在每个头部值的末尾添加 \r\n 并将数组转换为一个 string
你的代码应该是:
$headers = array(
    'From: <info@mysite.com>',
    'Content-Type:text/html;charset=UTF-8',
    'Reply-To: <info@mysite.com>'
);
$headers = implode("\r\n", $headers);

1
谢谢Hardik,但是这段代码在电子邮件前面添加了“”。 - Suffii
地址不应该在引号内,应该是 <info@mysite.com> - Barmar
但是我得到的是 "info@mysite.com"。 - Suffii
我仍然收到“info@mysite.com at email address!”的回复邮件!在接收邮件时不会显示引号,但在回复邮件时会显示! - Suffii
1
根据文档,自 PHP 7.2 起,mail 函数应该能够接受 $headers 参数的数组形式。 - eballeste

2

$headers 需要是一个字符串,而不是一个数组:

http://php.net/manual/en/function.mail.php

$headers = 
    'From: info@mysite.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'MIME-Version: 1.0' . "\r\n" .
    'Content-type: text/html; charset=iso-8859-1' . "\r\n"
;

mail($email, "Call Back Requert Confirmation", $msg, $headers);

如果你想将$headers保留为数组,也可以这样做

mail($email, "Call Back Requert Confirmation", $msg, implode("\r\n", $headers));

2
尝试将标题作为字符串而不是数组发送。
$headers = "From: info@mysite.com\r\n"; 
$headers.= "MIME-Version: 1.0\r\n"; 
$headers.= "Content-Type:text/html;charset=UTF-8\r\n"; 

或者使用数组将数组转换为字符串,使用implode()并将其发送到mail()
$headers = implode("\r\n", $headers);
mail($email, "Call Back Requert Confirmation", $msg, $headers);

1
自 PHP 7.2.0 版本(发布于2017年11月30日)起,php的mail函数接受一个关联数组作为$additional_headers参数 -> Example

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