使用 PHP 向多个收件人发送电子邮件(多个 TO CC BCC)

要使用 PHP 向多个收件人发送电子邮件,我们只需使用逗号分隔电子邮件即可。例如,mail("john@doe.com, jane@doe.com", SUBJECT, MESSAGE);

要在 PHP 邮件中添加抄送和密件抄送,我们必须手动设置邮件标头中的“抄送”和“密件抄送”字段。例如,mail(TO, SUBJECT, MESSAGE, "Cc: joy@doe.com\r\nBcc: joe@doe.com");

1.基本 PHP 邮件发送

<?php
$to = "goodboy@doge.com";
$subject = "Hey Doge!";
$message = "Wow. Very message. Such test. Much words.";
echo mail($to, $subject, $message)
? "Mail send OK"
: "Mail send ERROR" ;

 

我知道,这不是“多个收件人”,而是对可能忘记的人的快速回顾:

PHP Mail 函数接受 5 个参数 – mail(TO, SUBJECT, MESSAGE, HEADERS, OPTIONS).
我们对本教程感兴趣的是使用TO并将HEADERS其发送给多人......在空闲时间阅读其余内容(下面的链接)。
现在,如果邮件发送成功,mail()实际上会返回一个布尔值trueor 。false有些人似乎忘记了一些事情。

2.发送具有多个“收件人”收件人的邮件

<?php
// (A) SEPARATE EACH EMAIL WITH A COMMA
$to = "first@doge.com, second@doge.com";

// (B) TRICK - IMPLODE AN ARRAY
$to = implode(", ", [
"first@doge.com",
"second@doge.com"
]);

// (C) SUBJECT + MESSAGE
$subject = "Hey Doges!";
$message = "Wow. Very message. Such test. Much words.";

// (D) SEND!
echo mail($to, $subject, $message)
? "Mail send OK"
: "Mail send ERROR" ;

该mail()函数的“email to”参数实际上接受符合 RFC 2822 标准的字符串。这意味着,我们只需要向它提供一串格式正确的多个收件人:

用逗号分隔每封电子邮件。例如,first@doge.com, second@doge.com。
或者添加自定义名称,John Doe <john@doe.com>, Jane Doe <jane@doe.com>.

3.在 PHP MAIL 中添加抄送和密件抄送

<?php
// (A) TO, CC, BCC
$to = implode(", ", [
"first@doge.com",
"second@doge.com"
]);
$cc = implode(", ", [
"third@doge.com",
"forth@doge.com"
]);
$bcc = implode(", ", [
"fifth@doge.com",
"sixth@doge.com"
]);

// (B) SUBJECT + MESSAGE
$subject = "Hey Doges!";
$message = "Wow. Very message. Such test. Much words.";

// (C) EMAIL HEADER
$head = implode("\r\n", [
"MIME-Version: 1.0",
"Content-type: text/plain; charset=utf-8",
"Cc: $cc",
"Bcc: $bcc"
]);

// (D) SEND!
echo mail($to, $subject, $message, $head)
? "Mail send OK"
: "Mail send ERROR" ;

 

将抄送和密件抄送收件人添加到电子邮件中有点棘手,我们需要定义自定义电子邮件标头。

本质上,我们需要在电子邮件标头中一行表示Cc: EMAIL ADDRESSES,另一行表示Bcc: EMAIL ADDRESSES。
当然,为了创建“正确的电子邮件标题”,我们还添加MIME-Version和Content-type。

4.PHP 发送多封邮件功能

<?php
// (A) MAIL TO MANY FUNCTION
// Subject & Message are strings, as usual.
// To, CC, BCC should be arrays
function mmail ($subject, $message, $to, $cc=null, $bcc=null) {
// (A1) BUILD HEADER
$head = [
"MIME-Version: 1.0",
"Content-type: text/plain; charset=utf-8"
];
if ($cc !== null) { $head[] = "Cc: ". implode(", ", $cc); }
if ($bcc !== null) { $head[] = "Bcc: ". implode(", ", $bcc); }
$head = implode("\r\n", $head);

// (A2) SEND!
return mail(implode(", ", $to), $subject, $message, $head);
}

// (B) TEST
echo mmail(
// (B1) SUBJECT + MESSAGE
"Hello World!", "This is a test email",
// (B2) TO
[
"jo@doe.com",
"joe@doe.com",
],
// (B3) CC
[
"jon@doe.com",
"joy@doe.com"
],
// (B4) BCC
[
"john@doe.com",
"jane@doe.com"
]
) ? "OK" : "ERROR" ;
THE END
分享
二维码
海报
使用 PHP 向多个收件人发送电子邮件(多个 TO CC BCC)
要使用 PHP 向多个收件人发送电子邮件,我们只需使用逗号分隔电子邮件即可。例如,mail("john@doe.com, jane@doe.com", SUBJECT, MESSAGE);
<<上一篇
下一篇>>