Radon8472
Radon8472

Reputation: 4931

How to get error message from yii2 symfonymailer

I am using Yii2 to send e-mails using yii2-symfonymailer.

And in case of errors it returns false from the send() method, so I can check if sendind was successfull.

My question is: How can I get the error messages, when send fails?

This is the code for sending.

$message = Yii::$app->mailer->compose()
    ->setFrom('[email protected]')
    ->setTo('[email protected]')
    ->setSubject('Message subject')
    ->setTextBody('Plain text content')
    ->setHtmlBody('<b>HTML content</b>');

if (!$message->send()) {
  // handle the errors
}

For debugging I need a way either to get an exception with the error info from the send() method like in php mailer (https://stackoverflow.com/a/2386576/2377961).

Or a way to "ask" the mailer about the "lastErrors", e.g. like this:

if (!$message->send()) {
  echo "Could not send: " . Yii::$app->mailer->getLastError();
}

I found similar question for another yii2 mailer (see Returning error within Yii 2's base mailer ).

But this works not for my mailer, and changing the mailer is no option.

Upvotes: 0

Views: 480

Answers (1)

Michal Hynčica
Michal Hynčica

Reputation: 6144

There is no point in trying to get last error from mailer when $message->send() return false.

When you are using yii2-symfonymailer $message->send() will never return false when sending fails in mailer itself. It will return true on success or throw exception on failure.

See sendMessage() function implementation in mailer.

The only case when the $message->send() method will return false is when beforeSend() callback returns false. And that will only happen if something sets yii\mail\MailEvent::$isValid property to false during yii\mail\BaseMailer::EVENT_BEFORE_SEND event.

Upvotes: 2

Related Questions