How to configure and send email messages in Yii Framework 2.0

Hi guys! In this tutorial I will explain to you how you can send email messages in Yii Framework 2.6. Yii supports composition and sending of the email messages. You can send HTML messages and email with attachments in very easy way.

So, if you want to like emails with Yii, open your config/web.php file and make sure that you have this code:

'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
],

Next, you must add this code in your controller:

Yii::$app->mailer->compose()
->setFrom('from@domain.com')
->setTo('to@domain.com')
->setSubject('Message subject')
->setTextBody('Plain text content')
->setHtmlBody('HTML content')
->send();

If you want to send an email message with attachment, use this code in your controller:

$message = Yii::$app->mailer->compose();

// Attach file from local file system:
$message->attach('/path/to/source/file.pdf');

// Create attachment on-the-fly
$message->attachContent('Attachment content', ['fileName' => 'attach.txt', 'contentType' => 'text/plain']);

Video Tutorial:









Leave a Comment