Swift Mailer - 多个收件人无法正常工作

时间:2017-12-19 20:13:16

标签: php swiftmailer

我遇到了Swift Mailer的问题,看起来很简单,但我已经花了好几个小时了。 我需要向多个收件人发送电子邮件。 这是我开头的字符串($ email-> getRecipients()的内容):

// Just an example
first@gmail.com, second@gmail.com

首先,我删除所有不可见的字符:

$string = preg_replace('/[\x00-\x1F\x7F]/u', '', $email->getRecipients());

然后我添加了引用的引用:

$addQuotes = "'" . str_replace(",", "','", $string) . "'";

删除空格:

$recipients = str_replace(' ', '', $addQuotes);

这给了我:

'first@gmail.com','second@gmail.com'

如果我手动粘贴字符串:

->setTo(['first@gmail.com','second@gmail.com'])

有效。但是当我尝试将变量放到这样的时候:

$array = explode(',', $recipients);
...
->setTo($array)

未发送电子邮件。

当我这样做时:

->setTo([$recipients])

我在邮箱中收到错误地址['...','...']不符合RFC 2822,3.6.2。

我也尝试过:

foreach($array as $recipient) {
    $message->setTo($recipient);
    $this->get('mailer')->send($message);
}

不工作!但同样,如果我直接粘贴字符串,它可以工作:

foreach($array as $recipient) {
    $message->setTo('first@gmail.com');
    $this->get('mailer')->send($message);
}

代码:

private function sendEmail($email)
{
    //$email->getRecipients() = 'first@gmail.com, second@gmail.com'

    $string = preg_replace('/[\x00-\x1F\x7F]/u', '', $email->getRecipients());
    $addQuotes = "'" . str_replace(",", "','", $string) . "'";
    $recipients = str_replace(' ', '', $addQuotes);
    $array = explode(',', $recipients);

    $message = \Swift_Message::newInstance()
        ->setSubject($email->getSubject())    
        ->setFrom($email->getSender())
        ->setTo($array)
        ->setBody(
            $this->renderView(
                'Emails/default.html.twig',
                array('body' => $email->getBody())
            ),
            'text/html'
        );

    //foreach($array as $recipient) {
    //    $message->setTo($recipient);   
    //    $this->get('mailer')->send($message);
    //}        

    $this->get('mailer')->send($message);           
}

0 个答案:

没有答案