首页 > 解决方案 > 如何在 Laravel 中使用 SwiftMailer 获取 SMTP 会话错误

问题描述

我尝试向虚假地址发送电子邮件。如果此电子邮件地址不可用并且无法发送电子邮件,我将无法捕获错误。在 SMTP 服务器日志中,我看到:

Fri 2020-12-11 12:08:58.582: 03: --> 250-STARTTLS
Fri 2020-12-11 12:08:58.582: 03: --> 250 SIZE
Fri 2020-12-11 12:08:58.582: 02: <-- MAIL FROM:<my_email@mydomain.com>
Fri 2020-12-11 12:08:58.583: 03: --> 250 2.1.0 Sender OK
Fri 2020-12-11 12:08:58.583: 02: <-- RCPT TO:<somefakeaddress@mydomain.com>
Fri 2020-12-11 12:08:58.584: 03: --> 550 5.1.1 Recipient unknown <mi@f
Fri 2020-12-11 12:08:58.585: 02: <-- RSET
Fri 2020-12-11 12:08:58.585: 03: --> 250 2.0.0 RSET? Well, OK
Fri 2020-12-11 12:08:58.586: 02: <-- QUIT
Fri 2020-12-11 12:08:58.586: 03: --> 221 2.0.0 See ya in cyberspace
Fri 2020-12-11 12:08:58.586: 04: SMTP session terminated (Bytes in/out

但是在我的 Laravel 应用程序中,即使我使用事件监听器https://laravel.com/docs/7.x/mail#events ,我也无法捕捉到这个错误

当然,代码

Mail::to('somefakeaddress@mydomain.com')->send(new Mailable($mail_data));

什么都不返回。

是否知道如何在 Laravel 中捕获 SMTP 会话的错误?

标签: laravelemailsmtpswiftmailer

解决方案


找到了这个解决方案:

将 SwiftMailer 插件添加到邮件程序

$mailer = Mail::getSwiftMailer();

$logger = new \Swift_Plugins_Loggers_ArrayLogger();

$mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));

然后我们就可以像往常一样发送邮件了:

Mail::to(...)->send(new Mailable($data_for_mailable_class));

之后,我们可以在 $logger 数组中搜索任何错误消息。

对于我使用的测试dump($logger);

这帮助我找到了解决方案: How to set SwifMailer plugins when using the Laravel mail class?


推荐阅读