How to send emails using SMTP

  1. Configuration
  2. Send emails

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' => [
     ...
     'mailer' => [
         '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->mailer->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->mailer->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->mailer->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']).

6 0
11 followers
Viewed: 138 387 times
Version: 2.0
Category: How-tos
Written by: robregonm
Last updated by: Wade Shuler
Created on: Apr 29, 2014
Last updated: 5 years ago
Update Article

Revisions

View all history

Related Articles