Php 邮件不适用于多个收件人

Php mail not working with more than one recipient

为什么 this piece of php code 不适用于多个收件人?

只有当 $to 只有一个地址时才有效,例如:

$to = 'aa@bb.com';

编辑

如果电子邮件地址在同一个域中,它会起作用。例如,如果网站是 www.example.comxxx@example.com 之类的电子邮件会起作用,但 yyy@other.com 不会.

解决方案

PHPMailer。它提供了一种简单的方法来配置 SMTP.

这里是初始代码

<?php

//define the receiver of the email
$to = 'aa@bb.com, cc@dd.com, ee@ff.com';

// array with filenames to be sent as attachment
$files = array("a.zip","b.c","a.html");

// email fields: to, from, subject, and so on
$from = "mail@mail.com"; 
$subject ="My subject"; 
$message = "My message";

// boundary 
$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

// headers for attachment 
$headers = "From: $from";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

// multipart boundary 
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
$message .= "--{$mime_boundary}\n";

// preparing attachments
for($x=0;$x<count($files);$x++){
    $file = fopen($files[$x],"rb");
    $data = fread($file,filesize($files[$x]));
    fclose($file);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
    "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    $message .= "--{$mime_boundary}\n";
}

// send

$ok = @mail($to, $subject, $message, $headers); 
if ($ok) { 
    echo "<p>mail sent to $to!</p>"; 
} else { 
    echo "<p>mail could not be sent!</p>"; 
} 

?>

这是最终代码

// PHPMailer
$mail = new PHPMailer;

// setting up PHPMailer
$mail->isSMTP();
$mail->Host = 'host.com';
$mail->SMTPAuth = false;
$mail->Port = xx;

$mail->setFrom($_POST['email'], $_POST['name']);
$mail->Subject = $_POST['subject'];
$mail->msgHTML($_POST['message']);

foreach($contacts as $contact)
    $mail->addAddress($contact['email']);

// If the user has attached some files
foreach ($_FILES as $file)
    $mail->addAttachment($file['tmp_name'], basename($file['name']));

$response = array("status" => $mail->send() ? "sent" : "error");

echo json_encode($response);

您需要使用正确的 RFC 2822 格式。

不要使用@,因为您不知道错误是什么。如果您将邮件格式化为 "user@example.com, anotheruser@example.com" 格式,这是正确的,您需要在别处搜索问题。

您还可以在 http://php.net/manual/en/function.mail.php#example-3493 页面上查看示例 #4。

虽然这不是对您的问题的直接回应,但您可以通过使用预先存在的电子邮件发送库来避免麻烦,例如:

phpmailer https://github.com/PHPMailer/PHPMailer

或者简单的smtp https://bitbucket.org/ghorwood/simplesmtp/