我正在尝试使用以下代码发送邮件,但出现以下错误
没有mail()
接受标题的数组?
Warning: mail() expects parameter 4 to be string, array given in ../email.php on line 16
代码 :
<?php
$name = @trim(stripslashes($_POST['name']));
$from = @trim(stripslashes($_POST['email']));
$subject = @trim(stripslashes($_POST['subject']));
$message = @trim(stripslashes($_POST['message']));
$to = 'example@gmail.com';
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();
mail($to, $subject, $message, $headers);
最佳答案
PHP mail()需要string $to
, string $subject
, string $message
, string $headers
如果你想使用一个数组作为标题
mail($to, $subject, $message, implode("\r\n", $headers));
否则更改您的代码
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: {$name} <{$from}>\r\n";
$headers .= "Reply-To: <{$from}>\r\n";
$headers .= "Subject: {$subject}\r\n";
$headers .= "X-Mailer: PHP/".phpversion()."\r\n";
为什么
\r\n
(来自 mail() 文档)?Multiple extra headers should be separated with a CRLF (\r\n) [...] If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.
边注用途
"\r\n"
而不是 '\r\n'
关于php - 警告 : mail() expects parameter 4 to be string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28138636/