使用swiftmailer发送多封电子邮件时如何绕过失败的电子邮件?

Bri*_*ier 1 php email swiftmailer

我在MySQL数据库中有一个电子邮件队列,通过cron我每分钟处理X个未发送的电子邮件.我遇到的问题是,如果任何特定的电子邮件失败,它将停止执行其余的电子邮件.在一个案例中,这是因为SMTP身份验证失败,并且电子邮件处理基本上停止了,因为尝试发送失败的电子邮件不断发生.还有其他方式swiftmailer可能会失败,我应该知道吗?

我想知道我能在这做什么来使这个循环防弹?如果任何一封电子邮件失败,我想用错误代码(我的或swiftmailers)标记数据库中的记录.

Swiftmailer不是我们发送电子邮件的唯一方式,以下方法是驱动程序的一部分.有什么解决方案?

public function process_queue()
{
    $result = [... a few mail queue records ...];

    foreach( $result as $params )
    {
        if( ! class_exists( 'Swift', FALSE ) )
        {
            require '/libraries/Mail/swiftmailer/lib/swift_required.php';
        }

        // Prepare transport for sending mail through SMTP
        if( $params['protocol'] == 'smtp' )
        {
            $transport = Swift_SmtpTransport::newInstance( $params['smtp_host'], $params['smtp_port'] )
                ->setUsername( $params['smtp_user'] )
                ->setPassword( $params['smtp_pass'] );
        }

        // Prepare transport for simple mail sending
        else
        {
            $transport = Swift_MailTransport::newInstance();
        }

        // Prepare swiftmailer mailer object
        $mailer = Swift_Mailer::newInstance( $transport );

        // Get a new message instance, and apply its attributes
        $message = Swift_Message::newInstance()
            ->setSubject( $params['subject'] )
            ->setFrom( [ $params['from_email'] => $params['from_name'] ] )
            ->setTo( $params['to'] )
            ->setBody( $params['body'], $params['mailtype'] );

        $mailer->send( $message );
    }
}
Run Code Online (Sandbox Code Playgroud)

Tri*_*tan 5

您可以将发送放在一个try-catch块中,并在完成循环后处理任何异常.

try {
    $mailer->send($message);
} catch(Exception $exception) {
    // do something with $exception that contains the error message
}
Run Code Online (Sandbox Code Playgroud)

或者您可以添加第二个参数send并使用故障.

// Pass a variable name to the send() method
if (!$mailer->send($message, $failures))
{
  // do something with $failures that contains the error message
}
Run Code Online (Sandbox Code Playgroud)

此外,如果setTo因为电子邮件地址无效而失败,Swift将返回错误,因此您可以单独执行每个方法并捕获/处理任何错误,而不是链接构建消息.

try {
    $message->setTo($params['to']);
} catch(Swift_RfcComplianceException $e) {
    echo "The email ".$params['to']." seems invalid";
}
Run Code Online (Sandbox Code Playgroud)