How to send emails using SMTP

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »

  1. Configuration
  2. Send emails

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

6 0
11 followers
Viewed: 144 973 times
Version: Unknown (update)
Category: How-tos
Written by: robregonm robregonm
Last updated by: Wade Shuler Wade Shuler
Created on: Apr 29, 2014
Last updated: 6 years ago
Update Article

Revisions

View all history

Related Articles