Check mail is sent successfully or not on Laravel 5
Asked Answered
G

5

37

I have a function that can send mail on Laravel5 using this

/**
 *  Send Mail from Parts Specification Form
 */
 public function sendMail(Request $request) {
    $data = $request->all();

    $messageBody = $this->getMessageBody($data);

    Mail::raw($messageBody, function ($message) {
        $message->from('[email protected]', 'Learning Laravel');
        $message->to('[email protected]');
        $message->subject('Learning Laravel test email');
    });

    return redirect()->back();
 }

 /**
  * Return message body from Parts Specification Form
  * @param object $data
  * @return string
  */
 private function getMessageBody($data) {

    $messageBody = 'dummy dummy dummy dummy';
 }

and is sent successfully. But how to check if it was sent or not? Like

if (Mail::sent == 'error') {
 echo 'Mail not sent';
} else {
 echo 'Mail sent successfully.';
}

I'm just guessing that code.

Godfrey answered 1/10, 2015 at 8:0 Comment(6)
Have you tried Mail::failures()Dragon
@Dragon how to change my code to be able to see if that work or not? To fire that method? ThanksGodfrey
Does this help? #24773031Dragon
Yes i use that one, thanks. But how to know if that work or not?Godfrey
If failures() doesn't return anything then it has been successfully sent.Dragon
Can I edit my code or something just to show that errors occured? If not then thanks for the answer. :)Godfrey
D
39

I'm not entirely sure this would work but you can give it a shot

/**
 *  Send Mail from Parts Specification Form
 */
public function sendMail(Request $request) {
    $data = $request->all();

    $messageBody = $this->getMessageBody($data);

    Mail::raw($messageBody, function ($message) {
        $message->from('[email protected]', 'Learning Laravel');
        $message->to('[email protected]');
        $message->subject('Learning Laravel test email');
    });

    // check for failures
    if (Mail::failures()) {
        // return response showing failed emails
    }

    // otherwise everything is okay ...
    return redirect()->back();
}
Dragon answered 1/10, 2015 at 8:34 Comment(7)
I don't suppose there is an equivalent method for the number of successes? Mail::successes() throws an error with Call to undefined method.Raconteur
laravel.com/api/5.2/Illuminate/Mail/Mailer.html nope. Just do number of recipients minus count of failures and you will get your success count.Dragon
i got "response showing failed emails" what should i do now ?Rae
@YoussefBoudaya Do you want to debug your failed emails? Did you check your error logs? You may also want to dive into the laravel and swiftmailer codebase to see what determines if an email is a failure.Dragon
Nice explanation, but I have a kind of another curiosity. Assume for example an email address is valid, but it's not sent properly because an internet disconnected, or something else maybe because an email address is not valid. Is laravel can give a warning about it?Sporocyst
Are failures limited to invalid emails? Look at my previous comment and I'm sure you'll get your answer. Here's a starting point: github.com/laravel/framework/blob/5.8/src/Illuminate/Mail/… and swiftmailer.symfony.com/docs/sending.htmlDragon
how can i use when i am sending email using Notification?Corkhill
F
26

Hope this helps

The Mail::failures() will return an array of failed emails.

Mail::send(...)

if( count(Mail::failures()) > 0 ) {

   echo "There was one or more failures. They were: <br />";

   foreach(Mail::failures() as $email_address) {
       echo " - $email_address <br />";
    }

} else {
    echo "No errors, all sent successfully!";
}

source : http://laravel.io/forum/08-08-2014-how-to-know-if-e-mail-was-sent

Fabricant answered 1/10, 2015 at 8:30 Comment(2)
At least source the answer ;) laravel.io/forum/08-08-2014-how-to-know-if-e-mail-was-sentDragon
How can i use when i am sending email from notification?Corkhill
P
9

For Laravel 9.11.0

Mail::failures() // is deprecated in laravel 9.11.0

To check if your email was sent successfully one could wrap mail send in a try catch block:

try {
    Mail::to($userEmail)->send($welcomeMailable);
} catch (Exception $e) {
  //Email sent failed.
}

or since Mail::to($email)->send($mailable) on success returns an instance of : SentMessage one could check:

$welcomeEmailSent = Mail::to($userEmail)->send($welcomeMailable);

if ($welcomeEmailSent instanceof \Illuminate\Mail\SentMessage) {
  //email sent success
} else {
  //email sent failed
}
Pinette answered 5/5, 2022 at 12:7 Comment(5)
it's not working bro. It always going to fail section in Laravel 8 Could you suggest another method?Thirlage
how do you mean ?Pinette
Means to say whenever I run the below code it always print not done. I am unable to check whether the email is sent or not? could you tell me the proper method to check it. Thank you $response = Mail::send('emailTemplate.email', $data, function($message) use ($data) { $message->to($data['email'], 'Notification')->subject('Notification Testing email'); $message->from('[email protected]','Notification Testing email'); }); if($responseinstanceof \Illuminate\Mail\SentMessage){ dd('done'); }else{ dd('not done'); }Thirlage
wrap it in a try catch instead, if exception not caught email is sent, otherwise it failed, try { Mail::to($userEmail)->send($welcomeMailable); } catch (Exception $e) { //Email sent failed. }Pinette
Firstly I'm very thankful to you because you're trying to solve my problem. Secondly, It's not working I did exactly what you said and I put my wrong email and it still not working.Thirlage
B
4

You may additionally can make use "Swift_TransportException" to identify any errors.

try{

   //code to send the mail

}catch(\Swift_TransportException $transportExp){
  //$transportExp->getMessage();
}
Biddick answered 22/4, 2020 at 7:33 Comment(0)
M
1

You can use the Mail::failures() function for that. It will have a collection of failed mails if it exists so you can use the code below to check for it.

public function sendMail(Request $request) {
    $data = $request->all();

    $messageBody = $this->getMessageBody($data);

    Mail::raw($messageBody, function ($message) use ($messageBody) {
        $message->from('[email protected]', 'Learning Laravel');
        $message->to('[email protected]');
        $message->subject($messageBody); 
    });

    // check for failed ones
    if (Mail::failures()) {
        // return failed mails
        return new Error(Mail::failures()); 
    }

    // else do redirect back to normal
    return redirect()->back();
}
Menchaca answered 22/4, 2020 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.