[英]Swiftmailer: sending email to multiple recipient
I am trying to send email from a contact form through swiftmailer lib. 我正在尝试通过swiftmailer lib从联系表单发送电子邮件。 My setup sends mail to a single recipient, but when I try sending to more than one email, it throws an error: 我的设置将邮件发送给单个收件人,但是当我尝试发送多个电子邮件时,会引发错误:
Address in mailbox given [email1@gmail.com,email2@gmail.com] does not comply with RFC 2822, 3.6.2. 给定[email1 @ gmail.com,email2 @ gmail.com]邮箱中的地址不符合RFC 2822,3.6.2。
but the two emails are valid according to the specification. 但根据规范,这两封电子邮件有效。
Here is the code; 这是代码;
$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);
When I sent with one email in the input field, print_r($recipients)
gave me this array: (Array ( [0] => email1@gmail.com ) Sent 1 messages)
before but now it's not giving the array. 当我在输入字段中发送一封电子邮件时, print_r($recipients)
给了我这个数组: (Array ( [0] => email1@gmail.com ) Sent 1 messages)
之前但现在没有给出该数组。
I learnt that foreach
expects array, but I'm not getting an array. 我了解到foreach
期望使用数组,但是我没有得到数组。
At one point, I was getting an error that 'recipients' is undefined; 有一次,我收到一个错误,指出“收件人”未定义。 that is why I added the if isset()
check. 这就是为什么我添加了if isset()
检查的原因。
How do I send the each email individually? 如何分别发送每封电子邮件?
It looks like $_POST['recipients']
is a comma separated string. 看起来$_POST['recipients']
是一个逗号分隔的字符串。 You need to use explode()
to split the string on the commas. 您需要使用explode()
在逗号上分割字符串。 Casting it as an array won't do that for you: 将其强制转换为数组不会为您做到这一点:
// 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.