【问题标题】:Swiftmailer: sending email to multiple recipientSwiftmailer:向多个收件人发送电子邮件
【发布时间】:2017-12-05 22:23:27
【问题描述】:

我正在尝试通过 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() 检查的原因。

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

【问题讨论】:

    标签: php arrays email foreach swiftmailer


    【解决方案1】:

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

    【讨论】:

    • 是的,就是这样!我正在做爆炸性的事情,一个交付了 ,Array ( [0] => email1@gmail.com 但是在其他错误之后我注释掉了这些行并忘记重新打开。那是我的问题。谢谢我的问题解决了.
    • @Mariobrown 如果它解决了您的问题,请随时投票并接受答案。
    • 我可以在这里再问一件事关于表单上的文件上传,当有attacted文件时它工作得很好,但是当我把它留空时,它说路径不能为空。按照建议完成投票。
    • 我不太明白你的意思。您应该为此创建一个新问题。我们需要查看它的代码。除非解决方案是在没有文件上传的情况下不调用addAttachement()-方法。
    • 是的,正在寻找解决方案,如果没有附加文件,则不调用 addAttachement()。任何关于如何处理的 sudo 代码?
    猜你喜欢
    • 2012-05-18
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    相关资源
    最近更新 更多