Config mailer parameters from model - Yii2 - php

im using Yii2 and i want to config mailer parameters geting the data from db.
Example:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'enableSwiftMailerLogging' =>true,
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => $model->getSmtpHost(),
'username' => $model->getSmtpUser(),
'password' => $model->getSmtpPass(),
'port' => $model->getSmtpPort(),
'encryption' => $model->getSmtpEncryption(),
],
]
but from web.php can't call methods from models, i tried but throws a error

Yii initialized application from this config. You can't use yii2 before yii2 is runned.
$application = new yii\web\Application($config);
As alternative you can configure mailer after create application in bootstrap.php file like this: Yii::$app->set('mailer', (new MailerConfigurator())->getConfig());

thanks to #Onedev.Link and #arogachev for his answer.that gave me an idea and i solve the problem.
i solve the problem modyfing swiftmailer component, in Mailer.php added this:
use app\models\Administracion; //The model i needed for access bd
class Mailer extends BaseMailer
{
...
...
//this parameter is for the config (web.php)
public $CustomMailerConfig = false;
...
...
...
/**
* Creates Swift mailer instance.
* #return \Swift_Mailer mailer instance.
*/
protected function createSwiftMailer()
{
if ($this->CustomMailerConfig) {
$model = new Administracion();
$this->setTransport([
'class' => 'Swift_SmtpTransport',
'host' => $model->getSmtpHost(),
'username' => $model->getSmtpUser(),
'password' => $model->getSmtpPass(),
'port' => $model->getSmtpPort(),
'encryption' => $model->getSmtpEncryption(),
]);
}
return \Swift_Mailer::newInstance($this->getTransport());
}
And in Web.php added this:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'enableSwiftMailerLogging' =>true,
'CustomMailerConfig' => true, //if its true use the bd config else set the transport here
'useFileTransport' => false,
],

Related

How to setup mail folder path in Yii2 framework

I have a yiisoft/yii2-app-advanced installed. There are three main folders - common, frontend, backend. The folder for emails is in common/mail folder. If I try to send email from frontend controller on register user it throws me an error:
The view file does not exist:
C:\wamp64-3-2-0\www\yii2\frontend/mail\emailVerify-html.php
Registration is generated via console command. But is obvious that the path to mail folder is wrong. I found a workaround to it via
\Yii::$app->mailer->htmlLayout = '#common/mail/layouts/html';
\Yii::$app->mailer->textLayout = '#common/mail/layouts/text';
but it does not look very good. Is it possible to set it up in config file? Hope so. Thanks.
SO as I found out there is an option in config file named viewPath which is not mentioned in documentation.
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'encryption' => 'tls',
'host' => 'localhost',
'port' => '587',
'username' => 'your_username',
'password' => 'your_password',
],
],

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

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:

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!

Cron job not working in Yii2

I am facing some issue with cron job in Yii2 application.
I am define Controller in console as follow
namespace console\controllers;
use yii\console\Controller;
/**
* Job controller
*/
class JobController extends Controller {
public function actionIndex() {
echo "cron service runnning";
mail("mail#gmail.com","Cron",'Testing');
}
}
Path in cpenal is
php /home/user/public_html/root/ yii job
I always receiving email with error
Status: 404 Not Found
X-Powered-By: PHP/5.5.38
Content-type: text/html
No input file specified.
I think there is issue with cmd supplied for it.
Please help me to sort out this issue.
Thankyou
1.show system crontab log
why you do not use yii\swiftmailer\Mailer
$components = [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.xxx.com',
'username' => 'xx#xxx.com',
'password' => 'xxx',
'port' => '25',
'encryption' => 'tls',
],
'messageConfig' => [
'charset' => 'UTF-8',
'from' => ['xx#xx.com' => 'contents']
],
]
];
Yii::$app->setComponents($components);
$mail= Yii::$app->mailer->compose();
$mail->setTo(['from#xxx.com', 'to#xx.com']);
$mail->setSubject($subject);
$mail->setHtmlBody($content);
$mail->send();

Sending Mail - Yii 2.0

I'm trying to send mail, but getting error like.
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: yii\web\Application::mail
After changing Yii::$app->mail->compose() to Yii::$app->mailer->compose()
I got this error
Invalid Parameter – yii\base\InvalidParamException
Invalid path alias:#backend/mail
I'm not getting where i'm doing mistake.
I'm using yii-app-basic.
config/console.php
...
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
],
],
...
config/web.php
...
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#backend/mail',
'useFileTransport' => true,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'localhost',
'username' => 'root',
'password' => '',
'port' => '8080',
'encryption' => 'tls',
],
],
],
...
SiteController.php
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
class SiteController extends Controller
{
public function actionRegister()
{
Yii::$app->mail->compose()
->setFrom('enamRaj#gmail.com')
->setTo('Raj#infotech.com')
->setSubject('This is a test mail')
->send();
}
}
Error Screenshot
I'm new to Yii. I don't have much idea. If this is a silly question,please forgive me.
Taking help from Mailing- Yii 2.0. But, not getting much idea.
Please help me to send email
Use mailer component.
Yii::$app->mailer->compose()
In your config you write components that will be avalible on Yii::$app application.
Example:
In config:
'components' => [
'myComponent' => ['class' => '\common\MyClass']
]
In controller:
Yii::$app->myComponent->foo();
You are using the basic template. Path '#backend/mail' is only for advanced template. The correct path is #app/mail (or whatever path where you are storing your email templates).
well it's an old question but if you still using yii if you want to send a mail with no effort use dektrium it's an abandoned project but it provides many features user management email login etc

Categories