this piece of php code如何与多个收件人合作?
仅当$to
只有一个地址时才有效,例如:
$to = 'aa@bb.com';
修改
如果电子邮件地址位于同一个域中,则有效。例如,如果网站为www.example.com
,则xxx@example.com
等电子邮件将有效,但y yy@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);
答案 0 :(得分:1)
您需要使用正确的RFC 2822格式化。
不要使用@,因为你不知道错误是什么。如果您格式化邮件格式为&#34; user@example.com,alotheruser@example.com"它是正确的,你需要在其他地方搜索问题。
您还可以在http://php.net/manual/en/function.mail.php#example-3493页面上看到示例#4。
答案 1 :(得分:0)
虽然这不是对您的问题的直接回复,但您可以通过使用预先存在的电子邮件发送库来避免麻烦:
PHPMailer的 https://github.com/PHPMailer/PHPMailer
或simplesmtp https://bitbucket.org/ghorwood/simplesmtp/