Laravel 4 mail class, how to know if the email was sent?

ebelendez picture ebelendez · Jun 11, 2013 · Viewed 10k times · Source

I'm using the new mail class in Laravel 4, does anybody know how to check if the email was sent? At least that the mail was successfully handed over to the MTA...

Answer

Antonio Carlos Ribeiro picture Antonio Carlos Ribeiro · Jun 11, 2013

If you do

if ( ! Mail::send(array('text' => 'view'), $data, $callback) )
{
   return View::make('errors.sendMail');
}

You will know when it was sent or not, but it could be better, because SwiftMailer knows to wich recipients it failed, but Laravel is not exposing the related parameter to help us get that information:

/**
 * Send the given Message like it would be sent in a mail client.
 *
 * All recipients (with the exception of Bcc) will be able to see the other
 * recipients this message was sent to.
 *
 * Recipient/sender data will be retrieved from the Message object.
 *
 * The return value is the number of recipients who were accepted for
 * delivery.
 *
 * @param Swift_Mime_Message $message
 * @param array              $failedRecipients An array of failures by-reference
 *
 * @return integer
 */
public function send(Swift_Mime_Message $message, &$failedRecipients = null)
{
    $failedRecipients = (array) $failedRecipients;

    if (!$this->_transport->isStarted()) {
        $this->_transport->start();
    }

    $sent = 0;

    try {
        $sent = $this->_transport->send($message, $failedRecipients);
    } catch (Swift_RfcComplianceException $e) {
        foreach ($message->getTo() as $address => $name) {
            $failedRecipients[] = $address;
        }
    }

    return $sent;
}

But you can extend Laravel's Mailer and add that functionality ($failedRecipients) to the method send of your new class.

EDIT

In 4.1 you can now have access to failed recipients using

Mail::failures();