【问题标题】:How the laravel Mail::failures() function works?laravel Mail::failures() 函数是如何工作的?
【发布时间】:2023-03-27 05:48:01
【问题描述】:

我一直在尝试使用 laravel Mail::send() 函数获取未收到电子邮件的收件人列表。我正在尝试以下代码。 for循环被用作因为每个用户要接收定制的消息。

// First recipient is actual, the second is dummy.
$mail_to_users = ["original_account@domain.com","dummy_account@domain.com"];
$failures = [];

foreach($mail_to_users as $mail_to_user) {
   Mail::send('email', [], function($msg) use ($mail_to_user){
     $msg->to($mail_to_user);
     $msg->subject("Document Shared");
   });

   if( count( Mail::failures() ) > 0 ) {
      $failures[] = Mail::failures()[0];
   }
}

print_r($failures);

我一直在尝试所有可能的选择。我将config/mail.php 中的正确邮件配置更改为错误的配置。但如果我这样做,laravel 会显示错误页面,但 $failure 变量总是返回空。

【问题讨论】:

  • 从 Swiftmailer 只重新调整非常特定类型的故障是毫无价值的:几乎只有故障,因为用于邮件的方法拒绝了地址/电子邮件。使用SMTP 这通常没问题,因为 SMTP 服务器会立即返回失败,但使用 sendmail 之类的东西很少(如果有的话)返回失败,因为无论如何电子邮件都会被接受,然后再发送。因此,如果您在邮件配置中使用sendmail(甚至可能是mail),您可能需要使用不同的方式来监控投递失败。
  • 请参阅swiftmailer.org/docs/sending.html,了解有关何时返回失败和不返回失败的文档。

标签: php email laravel laravel-4 swiftmailer


【解决方案1】:

我正在处理类似的问题。当电子邮件发送失败时,我想用它做一些事情。看了源码,Illuminate\Mail\SendQueuedMailable::failed()方法表明我们可以在Mailable对象中添加failed方法来处理邮件失败时的$exception。

所以我们可以这样做:

class SampleMail extends Mailable
{
    public function failed($e)
    {
        // Do something with the exception when the email fails.
    }
}

据我了解,这只适用于排队的邮件。

【讨论】:

    【解决方案2】:

    我认为没有办法检查电子邮件实际上是否已发送给收件人。只要电子邮件有效(即使是虚拟的),它就会返回 true。但是,您可以使用 try catch 块代替 Mail::failures(),如下所示:

    foreach ($mail_to_users as $mail_to_user) {
                try {
                    Mail::send('email', [], function($msg) use ($mail_to_user) {
                        $msg->to($mail_to_user);
                        $msg->subject("Document Shared");
                    });
                } catch (Exception $e) {
    
                    if (count(Mail::failures()) > 0) {
                        $failures[] = $mail_to_user;
                    }
                }
            }
    

    【讨论】:

    • 如果你能告诉读者方法调用会抛出什么样的异常,那将会很有帮助:)
    猜你喜欢
    • 1970-01-01
    • 2017-07-12
    • 2012-04-22
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    相关资源
    最近更新 更多