Error:"Call to undefined method ping." Using Yii2 and Swiftmailer - php

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:

Related

CakePHP Mailer "Unknown email configuration" error

I am having troubles with the Mailer after upgrading from CakePHP 3 to 4.
This is the relevant part my configuration:
<?php
return [
'EmailTransport' => [
'default' => [
'className' => 'Mail',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'password',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
'cronjob' => [
'className' => 'Mail',
],
'accounts' => [
'className' => 'Mail',
],
],
'Email' => [
'default' => [
'transport' => 'default',
'from' => 'you#localhost',
],
'cronjob' => [
'transport' => 'cronjob',
'from' => 'cronjob#foobar.com',
],
'accounts' => [
'transport' => 'accounts',
'from' => 'accounts#foobar.com',
],
],
];
This is the snippet that's causing the error:
private function sendActivationEmail(User $user)
{
$url = Router::url([
'prefix' => 'Admin',
'plugin' => 'UserManager',
'controller' => 'Users',
'action' => 'activate',
$user->username,
$user->activation_key,
], true);
debug(Configure::read('EmailTransport'));
debug(Configure::read('Email'));
$mailer = new Mailer('accounts');
$mailer->setFrom(['accounts#foobar.com' => 'Foobar Website Manager'])
->setTo($user->email, $user->fullName)
->setSubject('Please activate your account')
->setEmailFormat('html')
->setViewVars(compact('url', 'user'))
->viewBuilder()
->setTemplate('UserManager.register');
return $mailer->deliver();
}
The error is Unknown email configuration "accounts"., thrown in
The output of the two debug functions is the following:
/vendor/plugins/usermanager/src/Model/Table/UsersTable.php (line 72)
[
'default' => [
'className' => 'Mail'
],
'cronjob' => [
'className' => 'Mail'
],
'accounts' => [
'className' => 'Mail'
]
]
/vendor/plugins/usermanager/src/Model/Table/UsersTable.php (line 73)
[
'default' => [
'transport' => 'default',
'from' => 'something#foobar.com'
],
'cronjob' => [
'transport' => 'cronjob',
'from' => 'cronjob#foobar.com'
],
'accounts' => [
'transport' => 'accounts',
'from' => 'accounts#foobar.com'
]
]
So it seems like the accounts key is present in the mail configuration, then why am I getting this error?
Make sure that you have upgraded your bootstrap.php accordingly along the way, specifically with regards to how EmailTransport and Email are being consumed, this was introduced with CakePHP 3.7 and 4.1 if I'm not mistaken:
TransportFactory::setConfig(Configure::consume('EmailTransport'));
Mailer::setConfig(Configure::consume('Email'));
https://github.com/cakephp/app/blob/4.2.2/config/bootstrap.php#L163-L164

Cannot send e-mail from queue process

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!

Getting unknown property: yii\console\Application::session while run ./yii

I want to run yii2 console command, then I test it with run this ./yii
When I run ./yii I got this response
Exception 'yii\base\UnknownPropertyException' with message 'Getting unknown property: yii\console\Application::session'
in /var/www/html/myweb/vendor/yiisoft/yii2/base/Component.php:143
Stack trace:
#0 /var/www/html/myweb/vendor/yiisoft/yii2/di/ServiceLocator.php(73): yii\base\Component->__get('session')
#1 /var/www/html/myweb/vendor/kartik-v/yii2-grid/Module.php(62): yii\di\ServiceLocator->__get('session')
Here is my common/config/params-local.php
return [
'uploadPath' => __DIR__ .'/../../uploads/',
'baseurl' => 'http://localhost/myweb/'
];
Here is my common\config\params.php
<?php
return [
'adminEmail' => 'no-reply#myweb.com',
'supportEmail' => 'no-reply#myweb.com',
'user.passwordResetTokenExpire' => 3600,
];
Here is my console\config\params-local.php
<?php
return [
];
Here is my console\config\params.php
<?php
return [
'adminEmail' => 'no-reply#myweb.com',
];
Here is my common\config\main.php
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
'modules' => [
'redactor' => [
'class' => 'yii\redactor\RedactorModule',
'uploadDir' => __DIR__ .'/../../uploads/konten',
'uploadUrl' => '/myweb/uploads/konten',
'imageAllowExtensions'=>['jpg','png','gif']
],
'gridview' => [
'class' => '\kartik\grid\Module',
]
],
];
Here is my common\config\main-local.php
<?php
return [
'language' => 'en-US',
'sourceLanguage' => 'id-ID',
'components' => [
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'google' => [
'class' => 'yii\authclient\clients\Google',
'clientId' => 'xxxxx-cppd86jm9qfrt77pc684pau01nilf261.apps.googleusercontent.com',
],
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
'clientId'=> 'xxxxxx16917400',
'clientSecret' => 'xxxxxx8d99ff80ce1f713424',
],
],
],
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=192.168.0.106;dbname=mydb',
'username' => 'dev',
'password' => 'dev123',
'charset' => 'utf8',
'enableSchemaCache' => false,
'schemaMap' => [
'pgsql'=> [
'class'=>'yii\db\pgsql\Schema',
'defaultSchema' => 'public2' //specify your schema here
]
], // PostgreSQL
],
'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,
],
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#backend/mail',
'useFileTransport' => false,//set this property to false to send mails to real email addresses
//comment the following array to send mail using php's mail function
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'iix70.hosting.com',
'username' => 'myuser',
'password' => 'mypass',
'port' => '465',
'encryption' => 'ssl',
],
],
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '../../messages',
'sourceLanguage' => 'id-ID',
'fileMap' => [
'app' => 'app.php',
],
],
],
],
]
];
Looks like something wrong with my script.
Currently i'm using ubuntu.
What should I do next in case to fix that? so it should response with yii command list instead of error.
and what cause these error?
Thanks in advance.
When you add a value to common/config folder files, configurations used in all applications like backend, frontend, console, api and others. So in advanced template, you must just add values which are related to all these applications. Based on documentation common folder is files common to all applications. This picture shows it clearly:
For your problem, as others mentioned, you don't have any session in console, but you added or used this module in common/config/params-local.php and based on introduction of this answer, it will be used in console/config/params-local.php and you get an error :).
Update: Based on your updated question, your common/config/main.php file is:
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
'modules' => [
'redactor' => [
'class' => 'yii\redactor\RedactorModule',
'uploadDir' => __DIR__ .'/../../uploads/konten',
'uploadUrl' => '/myweb/uploads/konten',
'imageAllowExtensions'=>['jpg','png','gif']
],
'gridview' => [
'class' => '\kartik\grid\Module',
]
],
];
gridviw module, implicitly uses session for saving state of sorting. In other side you added this to config folder of common, so based on previous notes, it also will be used in console application. Console doesn't have session (and I think you don't need a grid view in your console :D) and it causes an error. For solving this problem, move this lines
'modules' => [
'redactor' => [
'class' => 'yii\redactor\RedactorModule',
'uploadDir' => __DIR__ .'/../../uploads/konten',
'uploadUrl' => '/myweb/uploads/konten',
'imageAllowExtensions'=>['jpg','png','gif']
],
'gridview' => [
'class' => '\kartik\grid\Module',
]
],
to main.php of frontend or backend folder (based on your situations and use).

Yii2 mailer returns an error Setting unknown property: yii\swiftmailer\Mailer::mailer

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',
],
],
],

yii2-user dektrium module registration email was not received

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',
],
],

Categories