Yii2 SwiftMailer sending email via remote smtp server (gmail) - yii2

I want to send emails via my gmail account.
My mailer config:
[
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,//set this property to false to send mails to real email addresses
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'my#gmail.com',
'password' => 'pass',
'port' => '587',
'encryption' => 'tls',
],
]
I wrote command MailController:
<?php
namespace app\commands;
use yii\console\Controller;
use Yii;
/**
* Sanding mail
* Class MailController
* #package app\commands
*/
class MailController extends Controller
{
private $from = 'my#gmail.com';
private $to = 'to#gmail.com';
public function actionIndex($type = 'test', $data = null)
{
Yii::$app->mailer->compose($type, ['data' => $data])
->setFrom($this->from)
->setTo($this->to)
->setSubject($this->subjects[$type])
->send();
}
}
When I'm trying to run: php yii mail
I get: sh: 1: /usr/sbin/sendmail: not found
But why it requires sendmail if I want just SMTP connection to smtp.gmail.com?

I think you have configured the mailer wrongly. Because it is still using the default mail function. From the documentation the configuration should be like below. The mailer should be inside components.
'components' => [
...
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'username',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
],
],
...
],
One more suggestion is to use port "465" and encryption as "ssl" instead of port "587", encryption "tls".

Yii2 Has different config files for web and console works. So you need to config both of them. Regarding this issue, I had to make mail config file (for example mailer.php) and include it in both config files (web.php & console.php) like:
'components' => [
...
'mailer' => require(__DIR__ . '/mailer.php'),
...
],

Might be useful for someone as reference:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'username',
'password' => 'password',
'port' => 587,
'encryption' => 'tls',
'streamOptions' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
]
],
]

Related

SwiftMailer - Yii2 can't send email

I have problem using swiftmailer with yii2.
'components' => [
'mailer' => [
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.mandrillapp.com',
'port' => 587,
'username' => 'noreply#mysociete.com',
'password' => 'MY API KEY HERE',
],
],
],
to send after user registration i use the code below :
$isSuccessfullySaved = $leadModel->save();
if (!$isSuccessfullySaved) {
$response = $this->asJson(['errors' => ['webservice' => 'Error while saving the lead']]);
$response->statusCode = 550;
return $response->send();
}
$lastStep = Json::decode(file_get_contents(__DIR__ . '/../config-offers/offers.json'));
$isSuccessfullySent = Yii::$app->mailer->compose(
'offer-summary',
ArrayHelper::merge($leadModel->getAttributes(), $lastStep['offres'][$bestOffer])
)
->setFrom(['noreply#mysociete.com' => 'My Societe'])
->setTo($leadModel->emailAddress)
->setSubject('mysociete.com- Votre offre')
->send();
if (!$isSuccessfullySent) {
Yii::error("Could not send the email", __METHOD__);
}
What should be wrong. There is no error written in any log.
Have you tried setting the encryption in the transport? I am not sure about Mandrillapp needing it, but you could give it a try:
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.mandrillapp.com',
'port' => 587,
'username' => 'noreply#mysociete.com',
'password' => 'MY API KEY HERE',
'encryption' => 'tls',
],

Update swiftmailer configuration based on user input

I need to update SwiftMailer configuration based on user input, particularly, the user may decide to send emails using SMTP protocol or store them locally (in an specific filesystem's folder). The user will use a view to decide the option, then the controller catch the decision and update a session var. The current approach is to read that session var from config/web.php and then choose the appropriate configuration.
I am not sure whether web.php is loaded just once during the application execution, in fact I can not check if the session is active and then get the info from the var. I'm not sure what approach may be the appropriate one.
This is my config/web.php:
<?php
use yii\web\Session;
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$session = Yii::$app->session;
if($session->isActive){
$mailTransport = Yii::app()->session->get('emailtransport');
}
else{ //session is not started
$mailTransport = 'local';
}
if($mailTransport=='local'){
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'a4ARdWYauHJ-UEAvVfagzk0LTyT_KEuZ',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mail',
'htmlLayout' => 'layouts/main-html', //template to Send Emails Html based
'textLayout' => 'layouts/main-text', //template to Send Emails text based
'messageConfig' => [
'charset' => 'UTF-8',
'from' => ['clients#ok.com' => 'OK Premiun Clients'],
], //end of messageConfig
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
//'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'ok#gmail.com',
'password' => "password",
'port' => '465',
'encryption' => 'ssl',
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
}//end of if loop
else{
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'a4ARdWYauHJ-UEAvVfagzk0LTyT_KEuZ',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mail',
'htmlLayout' => 'layouts/main-html', //template to Send Emails Html based
'textLayout' => 'layouts/main-text', //template to Send Emails text based
'messageConfig' => [
'charset' => 'UTF-8',
'from' => ['ok#namesilo.com' => 'OK Premiun Clients'],
], //end of messageConfig
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'ok#gmail.com',
'password' => "password",
'port' => '465',
'encryption' => 'ssl',
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
}//end of if else loop
Because the session is never reached on web.php the emails are always stored locally.
What you are trying to do requires you to instantiate the yii\swiftmailer\Mailer class from within your code and set the transport by calling setTransport(), rather than using it via defining under the components in the config file.
I will give you an example where i will use the smtp.gmail.com as the host for the transport and send an email
public function actionTest(){
//instantiate the mailer
$mailer = new \yii\swiftmailer\Mailer(
[
'useFileTransport' => false
]
);
//set the transport params
$mailer->setTransport(
[
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'username',
'password' => 'password',
'port' => '587',
'encryption' => 'tls'
]
);
//to email
$to = "someemail#gmail.com";
//email subject
$subject = "this is a test mail";
//email body
$body ="Some body text for email";
//send the email
$mailer->compose()->setTo($to)->setFrom(
[
'support#site.com' => 'Site Support'
]
)->setTextBody($body)->setSubject($subject)->send();
}
Another solution is this: I did some changes using my Model Class:
public function sendMail($transport, $view, $subject, $params = []){
//set layout params
\Yii::$app->mailer->getView()->params['userName'] = $this->username;
if($transport == 'local'){
\Yii::$app->mailer->useFileTransport=true;
}
else{
\Yii::$app->mailer->useFileTransport=false;
}
$result = \Yii::$app->mailer->compose([
'html' => 'views/' . $view . '-html',
'text' => 'views/' . $view . '-text',
], $params)->setTo([$this->email => $this->username])
->setSubject($subject)
->send();
//reset layout params
\Yii::$app->mailer->getView()->params['userName'] = null;
return $result;
} //end of sendMail
It helped me to simplify my web.php, it wasn't necessary to use session vars.

Yii2 smtp email is not working on godaddy

I have deploy a Yii2 website from one server to godaddy. Its showing an error :-
'If you receive error " Connection could not be established with host smtp.gmail.com [Connection refused #111] "'
I have set the mail configs below:-
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 't********m#gmail.com',
'password' => '***************',
'port' => '465',
'encryption' => 'tls', //depends if you need it
],
],
I resolved it by just commenting the transport tag as below:-
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
//'transport' => [
// 'class' => 'Swift_SmtpTransport',
// 'host' => 'smtp.gmail.com',
// 'username' => 't********m#gmail.com',
// 'password' => '***************',
// 'port' => '465',
// 'encryption' => 'tls', //depends if you need it
// ],
],

Yii2 Email How to set sender name

i using Mailer to send email, so i have problem about sender name
This is my config
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'messageConfig' => [
'charset' => 'UTF-8',
'from' => ['admin#app.com' => 'App Sender Name'],
],
'transport' => [
'class' => 'Swift_MailTransport',
],
],
So it's not work. I goto inbox and only email showed.
And i need show as
Example:
it's work when i update setFrom() method.
Ex: $mailer->setFrom(['email#app.com' => 'App Name']). And here is config Yii2 for send by PHP mail and with sender name
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'messageConfig' => [
'charset' => 'UTF-8',
'from' => ['admin#app.com' => 'App Sender Name'],
],
'transport' => [
'class' => 'Swift_MailTransport',
],
],
and send email
Yii::$app->mailer->compose()
->setTo('client#email.com')
->setFrom(['admin#app.com' => 'App Name'])
....
Every component and sub-component in yii2 is configurable by dependency injection, this case is same, eg:
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'noreply.yourcompany#gmail.com',
'password' => '123456',
'port' => '465',
'encryption' => 'ssl',
],

Send email from other smtp in yii2

I use swiftmailer to send email from yii2. I get code from websites, but most of them send email from gmail.com. I want to send email from my university email, but it's not working. What's the problem. This is the code:
In main-local.php
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => /*true*/false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.students.del.ac.id',
'username' => 'if414024#students.del.ac.id',
'password' => 'bmelar28',
'port' => '587',
'encryption' => 'tls',
],
],
Remove smtp in 'host' => students.del.ac.id
show below code
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'students.del.ac.id',
'username' => 'if414024#students.del.ac.id',
'password' => 'bmelar28',
'port' => '587',
'encryption' => 'tls',
]
]
Try this : change port number and host
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => /*true*/false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'students.del.ac.id',
'username' => 'if414024#students.del.ac.id',
'password' => 'bmelar28',
'port' => '25',
'encryption' => 'tls',
],
],