Yii 2.0: How to send emails using SMTP

8 followers

Ver en Español

To send emails from Yii2 is pretty straightforward, since it now uses Swiftmailer for that purpose.

Configuration

In your config file just add (it has been already added if you created your project using composer):

'components' => [
     ...
     'mail' => [
         'class' => 'yii\swiftmailer\Mailer',
         'transport' => [
             'class' => 'Swift_SmtpTransport',
             'host' => 'localhost',  // e.g. smtp.mandrillapp.com or smtp.gmail.com
             'username' => 'username',
             'password' => 'password',
             'port' => '587', // Port 25 is a very common port too
             'encryption' => 'tls', // It is often used, check your provider or mail server specs
         ],
     ],
     ...
 ],

Plugins

If you want to use a Swiftmailer plugin (very useful in many cases, btw), you can do it in your conf file too. Something ike this will work:

'transport' => [
     'class' => 'Swift_SmtpTransport',
     ...
     'plugins' => [
         [
             'class' => 'Swift_Plugins_ThrottlerPlugin',
             'constructArgs' => [20],
         ],
     ],
 ],

Send emails

Use this code for sending emails from your application:

Yii::$app->mail->compose()
     ->setFrom('somebody@domain.com')
     ->setTo('myemail@yourserver.com')
     ->setSubject('Email sent from Yii2-Swiftmailer')
     ->send();

Advanced email templates

In some cases you might want to use templates for email rendering, so, in that case you just need to do something like:

Yii::$app->mail->compose('@app/mail-templates/email01', [/*Some params for the view */])
     ->setFrom('from@domain.com')
     ->setTo('someemail@server.com')
     ->setSubject('Advanced email from Yii2-SwiftMailer')
     ->send();

Or, if you want to use one template for HTML rendering and another for text, do something like this:

Yii::$app->mail->compose(['html' => '@app/mail-templates/html-email-01', 'text' => '@app/mail-templates/text-email-01'], [/*Some params for the view */])
     ->setFrom('from@domain.com')
     ->setTo('someemail@server.com')
     ->setSubject('Advanced email from Yii2-SwiftMailer')
     ->send();

Notice that the path to the view can also be relative, like inside a controller (e.g. ['html' => 'html-email-01']).

Total 1 comment

#19402 report it
prPixabit at 2015/06/19 05:40am
Difficulty Including Plugin (OpenBuildings swiftmailer-css-inliner)

I tried including the plugin swiftmailer-css-inliner as suggested here. Unfortunately the plugin is ignored (my css style is still not included in the mails (which are sent). The tutorial suggest, css can be included into the mail template in style tags. This does not seem to be true at all (as e.g. Ink templates are not formatted). Is there anybody having similar issues?

Leave a comment

Please to leave your comment.

Write new article