April 14 2014

Yii2 send email through swiftmailer expansion

Tagged Under :

Yii
In here i wouldn’t introduced what is swiftmailer, who interested can find the information by yourself. In below will explain how to send email with SMTP through Yii2 swiftmailer.

Inside the config folder. Open the web.php configuration file. You will see the following code as below:
$config = [
  ......
  'components' => [
    ......
    'mailer' => [
      'class' => 'yii\swiftmailer\Mailer',
      'useFileTransport' => true, //for the testing purpose, you need to enable this
    ]
  ]
]
If useFileTransport is enable, all the email wouldn’t send out and the email contents will keep a copy at ‘runtime/mail‘ folder.

To send the email by SMTP server, you need set the configuration as below:
$config = [
  ......
  'components' => [
    ......
    'mailer' => [
      'class' => 'yii\swiftmailer\Mailer',
      'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'localhost',
        'username' => 'username',
        'password' => 'password',
        'port' => '587',
        'encryption' => 'tls',
      ],
    ],
  ]
]

To send the email, you can follow below code.
Yii::$app->mailer->compose()
    ->setTo($toEmail)
    ->setFrom([$this->email => $this->name])
    ->setSubject($this->subject)
    //text content
    ->setTextBody($this->body)
    //send Html content
    //->setHtmlBody('<b>HTML content</b>')
    ->send();

Make a Comment

You must be logged in to post a comment.