Yii 2, sending mail through SMTP

December 19, 2016 77 Alex

Simple instruction by sending mail to Yii 2 (basic, advanced) via SMTP

Send Mail via SMTP in Yii2 basic

Open the configuration file /config/web.php and add sending mail setting in array element components:

  1. <?php
  2. $params = require(__DIR__ . '/params.php');
  3. $config = [
  4. //...
  5. 'components' => [
  6. 'mailer' => [
  7. 'class' => 'yii\swiftmailer\Mailer',
  8. 'viewPath' => '@app/mail',
  9. 'transport' => [
  10. 'class' => 'Swift_SmtpTransport',
  11. 'host' => 'smtp.yandex.ru',
  12. 'username' => '<username>@<yourDomain>',
  13. 'password' => '<userPassword>',
  14. 'port' => 465,
  15. 'encryption' => 'ssl',
  16. ],
  17. 'useFileTransport' => false,
  18. ],
  19. ],
  20. //...
  21. ];

Where <username>@<yourDomain> - e-mail with a letter which will be sent (for example: info@devreadwrite.com), <userpassword> - password from the mailbox <username>@<yourdomain>.

To send mail use the following code in the correct location:

  1. Yii::$app->mailer->compose()
  2. ->setFrom('<fromUsername>@<yourDomain>')
  3. ->setTo('<user@Email>')
  4. ->setSubject('Уведемление с сайта <yourDomain>') // тема письма
  5. ->setTextBody('Текстовая версия письма (без HTML)')
  6. ->setHtmlBody('<p>HTML версия письма</p>')
  7. ->send();

Where <fromUsername>@<yourDomain> - sender e-mail (<username>@<yourDomain>), <user@Email> - recipient e-mail.

Send Mail via SMTP in Yii2 advanced

Send Mail via SMTP in Yii2 advanced virtually identical as to send in basic. Open the configuration file /common/config/main-local.php and add sending mail setting in array element components:

  1. <?php
  2. return [
  3. 'components' => [
  4. //...
  5. 'mailer' => [
  6. 'class' => 'yii\swiftmailer\Mailer',
  7. 'viewPath' => '@common/mail',
  8. 'transport' => [
  9. 'class' => 'Swift_SmtpTransport',
  10. 'host' => 'smtp.yandex.ru',
  11. 'username' => '<username>@<yourDomain>',
  12. 'password' => '<userPassword>',
  13. 'port' => 465,
  14. 'encryption' => 'ssl',
  15. ],
  16. 'useFileTransport' => false,
  17. ],
  18. ],
  19. ];

And send in the right place:

  1. Yii::$app->mailer->compose()
  2. ->setFrom('<fromUsername>@<yourDomain>')
  3. ->setTo('<user@Email>')
  4. ->setSubject('Уведемление с сайта <yourDomain>') // тема письма
  5. ->setTextBody('Текстовая версия письма (без HTML)')
  6. ->setHtmlBody('<p>HTML версия письма</p>')
  7. ->send();

Differences in these examples only the configuration file and value of viewPath. Enjoy using.