Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the laravel Mail::failures() function works?

I've been trying to get the list of recipients who did not get email using laravel Mail::send() function. I am trying following code. for loop is used as because each user to be received customized message.

// First recipient is actual, the second is dummy.
$mail_to_users = ["[email protected]","[email protected]"];
$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);

I've been trying all the possible option. I changed the correct mail config in config/mail.php to the wrong one. But if I do this then laravel shows error page, but $failure variable always return empty.

like image 716
Rajan Rawal Avatar asked Aug 17 '15 07:08

Rajan Rawal


People also ask

How do I know if an email failed in Laravel?

You can use the Mail::failures() function for that.

How do I know if my Mail is working in Laravel?

You could try emailing yourself. If you get the email, that's a pretty good indication that it's working. Its a complex topic.

Can we use PHP Mail function in Laravel?

Laravel provides drivers for SMTP, Mailgun, Mandrill, SparkPost, Amazon SES, PHP's mail function, and sendmail , allowing you to quickly get started sending mail through a local or cloud based service of your choice.


2 Answers

I am working with a similar issue. When an email fails to be sent, I want to do a few things with it. I read the source code and the Illuminate\Mail\SendQueuedMailable::failed() method indicates that we can add a failed method to the Mailable object to handle the $exception when the email fails.

So we can do this:

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

As I understand, this only works with queued mailables.

like image 123
Kevin Bui Avatar answered Sep 22 '22 13:09

Kevin Bui


I think there is no way to check email is actually gone to the receipient or not. As long as the email is valid (even though dummy) it will return true. However, Instead of Mail::failures() you can use try catch block as follows:

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;
                }
            }
        }
like image 43
Hasan Tareque Avatar answered Sep 19 '22 13:09

Hasan Tareque