Search code examples
phplaravelemailswiftmailer

Could email be sent but still throws an exception?


So I am want to send an email and record in the database that it was sent successfully, here is what I do:

  • First, try sending an email to the user containing the product information

  • Second, check if the email was sent successfully. If yes, then record in the database that it was sent successfully.

But if sending the email failed (an exception was thrown) I want to catch that exception and return an error message.

My question is: Is there a case that the email gets sent but still throws an exception?

So by that the code returns error thinking that the email wasn't sent .. but it was actually sent and the exception was throw later after that.

    // pseudo code      
    try{
        $is_sent = send_email();
        if($is_sent){
            $db->email_was_sent();
        }
    }catch(Exception $e){
        return 'Email was not sent. An exception';
    }

Solution

  • Is there a case that the email gets sent but still throws an exception?

    It depends.

    If email is sent for a single recipient, any 3 of these situation could result:

    • email is delivered to recipient
    • email failed to be delivered to recipient
    • an exception was raised

    For this case, it would be undocumented behaviour of the SwiftMailer email client to have an email sent but still throw an exception.

    If email is sent to several recipients, any 3 of these situation could result:

    • email is delivered to all recipients
    • email failed to be delivered to one or more recipient(s)
    • an exception was raised

    For this other case, email could be delivered to some recipients and still raise an exception.

    https://swiftmailer.symfony.com/docs/sending.html#using-the-send-method

    AbstractSmtpTransport::send() shows that email may fail to be sent for one or more of the recipients. https://github.com/swiftmailer/swiftmailer/blob/v6.2.1/lib/classes/Swift/Transport/AbstractSmtpTransport.php#L178