Send Mail via SMTP in Yii2 basic
Open the configuration file /config/web.php and add sending mail setting in array element components:
<?php
$params = require(__DIR__ . '/params.php');
$config = [
//...
'components' => [ 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@app/mail', 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'smtp.yandex.ru', 'username' => '<username>@<yourDomain>', 'password' => '<userPassword>', 'port' => 465, 'encryption' => 'ssl', ], 'useFileTransport' => false, ], ], //... ];
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:
Yii::$app->mailer->compose()
->setFrom('<fromUsername>@<yourDomain>')
->setTo('<user@Email>')
->setSubject('Уведемление с сайта <yourDomain>') // тема письма
->setTextBody('Текстовая версия письма (без HTML)')
->setHtmlBody('<p>HTML версия письма</p>')
->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:
<?php
return [
'components' => [
//...
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.yandex.ru',
'username' => '<username>@<yourDomain>',
'password' => '<userPassword>',
'port' => 465,
'encryption' => 'ssl',
],
'useFileTransport' => false,
],
],
];
And send in the right place:
Yii::$app->mailer->compose()
->setFrom('<fromUsername>@<yourDomain>')
->setTo('<user@Email>')
->setSubject('Уведемление с сайта <yourDomain>') // тема письма
->setTextBody('Текстовая версия письма (без HTML)')
->setHtmlBody('<p>HTML версия письма</p>')
->send();
Differences in these examples only the configuration file and value of viewPath. Enjoy using.