Swiftmailer:向多个收件人

时间:2017-07-02 15:03:16

标签: php arrays email foreach swiftmailer

我正在尝试通过swiftmailer lib从联系表单发送电子邮件。我的设置将邮件发送给单个收件人,但是当我尝试发送到多个电子邮件时,它会抛出错误:

  

给出[email1 @ gmail.com,email2 @ gmail.com]的邮箱中的地址没有   符合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需要数组,但我没有得到数组。

有一次,我收到的错误是'收件人'未定义;这就是我添加if isset()检查的原因。

如何单独发送每封电子邮件?

1 个答案:

答案 0 :(得分:0)

看起来$_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);
}