I'm using Yii 2 with the yii2-queue package to send a batch of e-mails from a queue process.
class SendEmailReminder extends \yii\base\BaseObject implements \yii\queue\JobInterface
{
public $userId;
public function execute($queue)
{
$user = \app\models\User::find()
->select(['id', 'email', 'username'])
->where('id=:uid AND verified=false')
->params([':uid' => $this->userId])
->asArray()
->one();
if ($user) {
$body = 'test mail';
Yii::$app->mailer->compose()
->setFrom(Yii::$app->params['fromEmail'])
->setTo('myemail#address')
->setSubject('Reminder')
->setTextBody($body)
->send();
}
}
}
In another controller action I have this:
public function actionRemindUsersWithNoValidatedEmail()
{
$users = User::find()
->select(['id'])
->where(['and', 'verified=false', '(NOW() - registered) > INTERVAL \'6 day\''])
->asArray()
->all();
foreach ($users as $user) {
Yii::$app->queue->push(new SendEmailReminder([
'userId' => $user['id']
]));
}
}
My web.php config:
'components' => [
..............
'queue' => [
'class' => \yii\queue\file\Queue::class,
'path' => '#runtime/queues',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// 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' => 'host',
'username' => 'user',
'password' => 'pass',
'port' => '587',
'encryption' => 'tls',
]
],
]
and my console.php config:
'components' => [
'queue' => [
'class' => \yii\queue\file\Queue::class,
'path' => '#runtime/queues',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// 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' => 'host',
'username' => 'user',
'password' => 'pass',
'port' => '587',
'encryption' => 'tls',
]
],
],
I call the action remind-users-with-no-validated-email and I can see #runtime/queues filling up with the queue files. If I execute ./yii queue/run, I can see that the queue is emptied (thus, processed), but unfortunately no e-mail messages get sent. What am I missing here?
Got it. Because I run ./yii queue/run from the command line, it has trouble to find the base url. So I had to insert this code in console.php (inside the component part):
'urlManager' => [
'class' => 'yii\web\UrlManager',
'scriptUrl' => 'http://myurl'
]
I discovered the error after running ./yii queue/run -v with the verbose flag. Thanks everyone!
Related
Any help would be highly appreciated.
I do not understand what I am doing wrong. I have used Swiftmailer before and it has never been this difficult to configure it.
I am using an advanced Yii2 project.
This is part of my backend/config/main.php (I have tried with backend/config/main-local.php, common/config/main.php and common/config/main-local.php just in case):
....
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'localhost',
'username' => 'name#example.com',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
'plugins' => [
[
'class' => 'Swift_Plugins_ThrottlerPlugin',
'constructArgs' => [20],
],
],
],
],
....
],
This is part of my controller:
public function actionTests()
{
Yii::$app->mailer->compose()
->setFrom('name#example.com')
->setTo('name_2#example.com')
->setSubject('Email sent from Yii2-Swiftmailer')
->send();
}
This is the error I am getting:
I upgraded my cakephp3.2 to cakephp3.6 . The emailing function doesnt work and i copied the same code in app file from the working emails in cakephp3.2 to the app file in cakephp3.6. The passwords exist and work fine. I edited them here for security. What has changed in 3.6?
It says the "SMTP server did not accept the password."
//in model
public function sendemail($to,$from,$subject,$message) {
$to='xxxx#gmail.com';
$Email = new Email('default');
// $Email->config('gmail3');
$Email->from(['xxx#gmail.com' => 'My Email'])
->to($to)
->subject($subject)
->send($message);
}//public
//in app file
'EmailTransport' => [
'default' => [
'className' => 'Smtp',
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username'=>'xx#gmail.com',
'password'=>'xx',
'log' => true,
'context' => [
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]
],
],
'Email' => [
'default' => [
'transport' => 'default',
'from' => 'xx#gmail.com',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
],
'default' => [
'className' => 'Smtp',
'host' => 'smtp.gmail.com',
'port' => 587 //or 465,
'timeout' => 30,
'username' => 'email',
'password' => 'pass',
'client' => null,
'tls' => true,
],
This config works for me.
I have problem using swiftmailer with yii2. I write code on dev machine which runs in windows and it work smoothly. But when I move the same code to the production site, swiftmailer is not sending email but it save email to file. I send mail from console
composer.json
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "dev-master",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "~2.0.0",
main.php
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'xxx',
'password' => 'xxx',
'port' => '587',
'encryption' => 'tls',
'streamOptions' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
]
],
'useFileTransport' => false,
],
sendEmail.php
$res = \Yii::$app->mailer->compose()
->setFrom("stat#test.net")
->setTo(self::getRecipients())
->setHtmlBody($data)->setSubject("Stat Report ".date("d.m.Y H:i"))
->send();
What should be wrong. There is no error written in any log.
Confirm if there's no error by try-catch-ing it:
try {
$res = \Yii::$app->mailer->compose()
->setFrom("stat#test.net")
->setTo(self::getRecipients())
->setHtmlBody($data)->setSubject("Stat Report ".date("d.m.Y H:i"))
->send()
}
catch (\Swift_TransportException $e) {
var_dump($e->getMessage());
}
Or try the logger for Yii-swiftmalier :
[
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'enableSwiftMailerLogging' => true,
],
],
// ...
],
Try without streamOptions, like:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'xxx',
'password' => 'xxx',
'port' => '587',
'encryption' => 'tls',
],
],
I have configured mailer in this way
In the component
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'useFileTransport' => false,
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'gmailaccount',
'password' => 'gmailpassword',
'port' => '587',
'encryption' => 'tls',
],
],
],
],
In my controller i have
public function actionTestmail(){
return \Yii::$app->mailer->compose('testmail')
->setFrom([Yii::$app->params['supportEmail']]) //this is set in params
->setTo("mysecondmail#gmail.com")
->setSubject('Testing yii2 mailer ')
->send();
}
The above always returns an error of setting unknown property: yii\swiftmailer\Mailer::mailer, what could be wrong,
The above configuration is a copy paste from yii2 website yet it fails to work
You have two times repeated mailer in components configuration.
This is right configuration:
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'gmailaccount',
'password' => 'gmailpassword',
'port' => '587',
'encryption' => 'tls',
],
],
],
I have a trouble.
I install a yii2-user module by folowing link https://github.com/dektrium/yii2-user/tree/0.9.9
When I trying to register I got a success message, but I not receiving confirmation email.
I used OpenServer
config/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'language' => 'ru-RU',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
'mailer' => [
'sender' => ['name#gmail.com' => 'Vlad'], // or ['no-reply#myhost.com' => 'Sender name']
'welcomeSubject' => 'Welcome subject',
'confirmationSubject' => 'Confirmation subject',
'reconfirmationSubject' => 'Email change subject',
'recoverySubject' => 'Recovery subject',
],
],
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'QqvFfvH3g3PwMMu_bRRHB4Qz0uPJwiB-',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
// 'user' => [
// 'identityClass' => 'app\models\User',
// 'enableAutoLogin' => true,
// ],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// 'transport' => [
// 'class' => 'Swift_SmtpTransport',
// 'host' => 'smtp.gmail.com',
// 'username' => 'name#gmail.com',
// 'password' => 'mypassword',
// 'port' => '587',
// 'encryption' => 'tls',
// ],
// 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,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
Untill your environment is in dev mode, you will never receive the emails.
You have 3 differents way for read the emails:
the dev bar in bottom, if there is not any redirect after send email, you can open and find it there
in the server, looking for runtime/mail/ folder and there will be the sended emails
deploy enviroment from developer to production
The mailer component should be at the same level as model component.
You can configure it as follows:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.mailtrap.io', // your host, here using fake email server (https://mailtrap.io/). You can use gmail: 'host' => 'smtp.gmail.com'
'username' => 'your host username',
'password' => 'your host password',
'port' => '2525',
'encryption' => 'tls',
],
],