Brett Brett - 1 month ago 15
PHP Question

Returning the error why mail failed to send within Yii 2's base mailer class

I'm using

Yii 2
and am using the mailer from the base mailer class and for the most part it is working fine, but sometimes it fails to send..... so my code is like:

// Let's start composing the message
$mail = Yii::$app->mailer->compose($view_data, $view_params);

//.........

// Send the message
$send = $mail->send();


Sometimes
$send
is
false
but I'm not sure how you find out WHY it is false? Is there a way to get the error that made it become false?

Answer

If you are sending multiple recipients message, you should check for failures : http://swiftmailer.org/docs/sending.html#getting-failures-by-reference, e.g. :

if (Yii::$app->mailer->getSwiftMailer()->send($message->getSwiftMessage(), $failures))    
{
    // do what you want with $failures var
}

And if you really want to handle smtp errors in your yii app, you should use swiftmailer logger plugin : http://swiftmailer.org/docs/plugins.html#logger-plugin

PS : first I would check yii and smtp logs to see what kind of errors occurs...