Swiftmailer:向多个收件人发送电子邮件
Swiftmailer: sending email to multiple recipient
我正在尝试通过 swiftmailer 库从联系表单发送电子邮件。我的设置将邮件发送给单个收件人,但是当我尝试发送给多个电子邮件时,它会引发错误:
Address in mailbox given [email1@gmail.com,email2@gmail.com] does not
comply with RFC 2822, 3.6.2.
但这两个电子邮件根据规范有效。
这是代码;
$failed = [];
$sent = 0;
$to = [];
if (isset($_POST['recipients'])) {
$recipients = $_POST['recipients'];
}
// Send the message
foreach ((array) $recipients as $to) {
$message->setTo($to);
$sent += $mailer->send($message, $failed);
}
print_r($recipients);
printf("Sent %d messages\n", $sent);
当我在输入字段中发送一封电子邮件时,print_r($recipients)
之前给了我这个数组:(Array ( [0] => email1@gmail.com ) Sent 1 messages)
但现在它没有给数组。
我了解到 foreach
需要数组,但我没有得到数组。
有一次,我收到一个错误,提示 'recipients' 未定义;这就是为什么我添加了 if isset()
检查。
如何单独发送每封电子邮件?
看起来 $_POST['recipients']
是一个逗号分隔的字符串。您需要使用 explode()
在逗号上拆分字符串。将其转换为数组不会为您做这些:
// We should give $recipients a default value, in case it's empty.
// Otherwise, you would get an error when trying to use it in your foreach-loop
$recipients = [];
if(!empty($_POST['recipients'])){
// Explode the string
$recipients = explode(',', $_POST['recipients']);
}
// Send the message
foreach ($recipients as $to) {
// To be safe, we should trim the addresses as well, removing any potential spaces.
$message ->setTo(trim($to));
$sent += $mailer->send($message, $failed);
}
我正在尝试通过 swiftmailer 库从联系表单发送电子邮件。我的设置将邮件发送给单个收件人,但是当我尝试发送给多个电子邮件时,它会引发错误:
Address in mailbox given [email1@gmail.com,email2@gmail.com] does not comply with RFC 2822, 3.6.2.
但这两个电子邮件根据规范有效。
这是代码;
$failed = [];
$sent = 0;
$to = [];
if (isset($_POST['recipients'])) {
$recipients = $_POST['recipients'];
}
// Send the message
foreach ((array) $recipients as $to) {
$message->setTo($to);
$sent += $mailer->send($message, $failed);
}
print_r($recipients);
printf("Sent %d messages\n", $sent);
当我在输入字段中发送一封电子邮件时,print_r($recipients)
之前给了我这个数组:(Array ( [0] => email1@gmail.com ) Sent 1 messages)
但现在它没有给数组。
我了解到 foreach
需要数组,但我没有得到数组。
有一次,我收到一个错误,提示 'recipients' 未定义;这就是为什么我添加了 if isset()
检查。
如何单独发送每封电子邮件?
看起来 $_POST['recipients']
是一个逗号分隔的字符串。您需要使用 explode()
在逗号上拆分字符串。将其转换为数组不会为您做这些:
// We should give $recipients a default value, in case it's empty.
// Otherwise, you would get an error when trying to use it in your foreach-loop
$recipients = [];
if(!empty($_POST['recipients'])){
// Explode the string
$recipients = explode(',', $_POST['recipients']);
}
// Send the message
foreach ($recipients as $to) {
// To be safe, we should trim the addresses as well, removing any potential spaces.
$message ->setTo(trim($to));
$sent += $mailer->send($message, $failed);
}