Cron job not working in Yii2 - php

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();

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

Mailgun emails not sending from Laravel 8 Valet app

Here's my relevant .env:
MAIL_MAILER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
MAILGUN_DOMAIN=https://api.mailgun.net/v3/mail.example.com
MAILGUN_SECRET=fb...a1
Note: I use example.com as an example above, but I've put my actual domain name there. I do not get any errors from the Laravel app, and I do not see anything in the logs on the Mailgun dashboard. My domain is verified. fb...a1 is also the redacted API code, I of course use my full API code I get from the mailgun dashboard.
config/mail.php:
<?php
return [
'default' => env('MAIL_MAILER', 'mailgun'),
'mailers' => [
'mailgun' => [
'transport' => 'mailgun',
],
],
];
config/services.php:
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
In my controller I have:
$email = $validated['email']; // I've verified this is my actual email
Mail::to($email)->send(new OrderCreated());
app/Mail/OrderCreated.php:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class OrderCreated extends Mailable
{
use Queueable, SerializesModels;
public function __construct()
{
//
}
public function build()
{
return $this
->from('no-reply#example.com')
->markdown('emails.order-created');
}
}
And finally, resources/views/emails/order-created.blade.php:
#component('mail::message')
# Order Confirmation
This email is test.
#endcomponent
I'm using Laravel 8.14.0 and Valet 2.13.0, so I'm testing it locally with an https://my-app.test domain. The app is using InertiaJS, in case that makes any difference. The controller code runs without error, but I see no logs on my mailgun dashboard and the email never arrives in my inbox. I have no idea what's wrong or how to debug this.
UPDATE:
I've noticed if I set MAILGUN_DOMAIN and MAILGUN_SECRET to null, I get the same behaviour as above. If I set MAILGUN_DOMAIN to a nonsense value like abcd I get the following error:
GuzzleHttp\Exception\ClientException
Client error: `POST https://api.mailgun.net/v3/abcd/messages.mime` resulted in a `401 UNAUTHORIZED` response: Forbidden
And if I set MAILGUN_SECRET to abcd it works as originally described (no error, but also no email).
These days I've worked with mailgun. It was on Laravel 7, and it worked perfectly. I dont think that it will cause a problem for v8.
Actually I've sent emails from controller, but you can implement the same for you as you want.
So I'll share my experience anyway.
.env
#MAIL_DRIVER=mailgun
MAIL_MAILER=mailgun
MAIL_HOST="smtp.mailgun.org"
MAIL_PORT=587
MAIL_USERNAME="postmaster#sandbox********************************.mailgun.org"
MAIL_PASSWORD="123456"
MAIL_ENCRYPTION=tls
MAILGUN_DOMAIN="sandbox********************************.mailgun.org"
MAILGUN_SECRET="key-********************************"
MAIL_FROM_NAME="ProjectName"
MAIL_FROM_ADDRESS="no-reply#yourfuturesite.com"
MAIL_ENV=test
MAIL_TEST="recipient#yourfuturesite.com"
#MAIL_LOG_CHANNEL
#MAILGUN_ENDPOINT="api.eu.mailgun.net"
config/mail.php
<?php
return [
'default' => env('MAIL_MAILER'),
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
'ses' => [
'transport' => 'ses',
],
'mailgun' => [
'transport' => 'mailgun',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
'postmark' => [
'transport' => 'postmark',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => '/usr/sbin/sendmail -bs',
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
],
'from' => [
'address' => env('MAIL_FROM_ADDRESS'),
'name' => env('MAIL_FROM_NAME'),
],
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
// CUSTOM CONFIGS
'mail_env' => env('MAIL_ENV'), // 'local' for testing via mailgun, 'production' for all mails
'mail_test' => env('MAIL_TEST'), // test email for 'local' testing
// ADDITIONAL UNNECESSARY CONFIGS
// 'sendmail' => '/usr/sbin/sendmail -bs',
// 'sendmail' => '/usr/sbin/sendmail -t-i',
// 'pretend' => false,
// 'log_channel' => env('MAIL_LOG_CHANNEL'),
// 'pretend' => false,
];
config/services.php (the same as you have)
Controller
try {
$name = array_key_exists('first_name', $email_data) ? $email_data['first_name'] : $email_data['name'];
Mail::send('emails.confirm-registration', [
'role' => $email_data['role'],
'name' => $name,
'email' => $email_data['email'],
'confirm_registration' => route('front.auth.confirm_registration', ['registration_token' => $email_data['registration_token']]),
], function ($message) use ($email_data, $name) {
$to = (config('mail.mail_env') == 'prod' || config('mail.mail_env') == 'production') ? $email_data['email'] : config('mail.mail_test');
$message
->subject(config('app.name') . ": Email Confirmation")
->from(config('mail.from.address'), config('mail.from.name'))
->to($to, $name);
});
return true;
}
catch(\Exception $e) {
// TODO: report all the "$e->message"s like this
return false;
}
resources/views/emails/confirm-registration.php
<a href="{{ route('front.main') }}" target="_blank">
<img label="logo" alt="{{ config('app.name') }}"
src="{{ $message->embed(public_path('images/logo.svg')) }}" width="128" height="96">
</a>
<p>{{ $name }}</p>
<p>{{ $confirm_registration }}</p>
<p>© {{ date("Y") == 2020 ? '2020' : '2020-' . date("Y") }} {{ config('app.name') }}</p>
This is just my example, so there you may need to replace as you want.
Just pay attention to "config/mail.php" file. I think there you need to set some additional props. (Also don't forget to reload your cache after these last config changes: "php artisan config:cache")

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!

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

Config mailer parameters from model - Yii2

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

Categories