Installation of Swiftmailer
The preferred way to install this extension is through composer.Either run below code in composer
php composer.phar require --prefer-dist yiisoft/yii2-swiftmailer
or add code to the require section of your composer.json.
"yiisoft/yii2-swiftmailer": "~2.1.0"
Note: Version 2.1 of this extensions uses Swiftmailer 6, which requires PHP 7. If you are using PHP 5, you have to use version 2.0 of this extension, which uses Swiftmailer 5, which is compatible with PHP 5.4 and higher. Use the following version constraint in that case:
"yiisoft/yii2-swiftmailer": "~2.0.0"
Send Mail via SMTP from Yii2 Basic
Open the configuration file /config/web.php and add your email credentials in array element inside components as shown below:
<?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,
],
],
//...
];
To send email, use the following code in any model file:
Yii::$app->mailer->compose()
->setFrom('<fromUsername>@<yourDomain>')
->setTo('<user@Email>')
->setSubject('Your Subject <yourDomain>')
->setTextBody('Body Content Here')
->setHtmlBody('<p>HTML Content Here</p>')
->send();
Send Mail via SMTP from Yii2 Advanced
Send Mail via SMTP from Yii2 advanced is same as basic. Open the configuration file /common/config/main-local.php and add your email credentials in array element inside components as shown below:
<?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,
],
],
];
To send email, use the following code in any model file:
Yii::$app->mailer->compose()
->setFrom('<fromUsername>@<yourDomain>')
->setTo('<user@Email>')
->setSubject('Your Subject <yourDomain>')
->setTextBody('Body Content Here')
->setHtmlBody('<p>HTML Content Here</p>')
->send();
Major differences in these examples only the configuration file.
Comments
Post a Comment