【问题标题】:How do I bypass a failing email when sending multiple emails with swiftmailer?使用 swiftmailer 发送多封电子邮件时如何绕过失败的电子邮件?
【发布时间】:2015-12-18 18:16:48
【问题描述】:

我在 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 );
    }
}

【问题讨论】:

  • 何不发一次,抄送给大家
  • @meda 因为每个人都知道他的邮件列表?隐私多少?
  • 电子邮件不是抄送或密送。在大多数情况下,它们是完全不同的,而且在许多情况下,它们具有不同的 SMTP 连接。

标签: php email swiftmailer


【解决方案1】:

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

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

或者您可以将第二个参数添加到send 并利用失败。

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

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

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

【讨论】:

  • 对不起,我的代码错了。真正的代码是不同的,我试图拼凑足够多的东西来显示发生了什么。我想实现尽可能多的错误处理,所以感谢您的建议。
  • 排除现在不相关的返回部分,这是否回答了您的问题,还是您正在寻找更多的错误处理?
  • 我正在寻找尽可能多的错误处理。
  • 幸好你指出setTo 也可以抛出异常
猜你喜欢
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2011-02-08
  • 2016-10-08
  • 2015-04-16
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
相关资源
最近更新 更多