Laravel 8 Schedule Task not sending Email on Cpanel - php

I would like to send an email via task scheduler every minute using Laravel 8.
Below is my code on Kernel.php
$schedule->call(function () {
$adminController = new AdminController();
$adminController->test();
})->everyMinute();
On the Admin Controller I have a method called test
public function test()
{
try {
$fp = fopen('cronJobTest.txt', 'a');
fwrite($fp, "Testing Started. ");
fclose($fp);
$email = new \stdClass();
$email->subject = "Cron Job Test";
$email->greetings = "Hi, Tested";
$email->message1 = "This is a cron job tester";
$email->btn_text = 'Test';
$email->message2 = "";
$email->url = "dashboard/test";
\Illuminate\Support\Facades\Notification::route('mail', 'myemailaddressHere#gmail.com')->notify(new EmailNotification($email));
}catch (Exception $exception){
$fp = fopen('cronJobTest.txt', 'a');
fwrite($fp, "Failed with exception ".$exception->getMessage());
fclose($fp);
}
}
On my local machine I then run the command:
php artisan schedule:work
An email is sent to the provided email address as expected.
However, after uploading the source code to shared hosting cpanel and setting up the Cron Job, the scheduler does not send an email.
I am sure the method test() is fired because if you look at the test() method, I am creating a file 'cronJobTest.txt' everytime the method is called and appending the text 'Test Started'.
In my web routes I have created a route to direct to the test() method and if I call the method via the route, an email is sent. ie https://mylaraveldomain.com/test
Route::get("test", [AdminController::class, 'test']);
However the same same method does not send an email if fired from the scheduler.
What might be causing this?

Do you have a cron in your server? If not, then that is the problem. Refer to this page.
Edit: Have you confirmed that the cron is running properly? If not, put an everyMinute job that logs something first. Check first if the log shows up.

Related

How can i send mailable into schedule in Laravel

i'm trying to send a mailable into schedule, but the mail is ommited when schedule is execute
$schedule->call(function () {
Log::debug("START TEST MAIL"); //this is write in log
$result = Mail::to('myemail#gmail.com')->send(new MailRecover('12345678aZ*'));
Log::debug("END TEST MAIL, RESULT: $result"); //this is write in log
})->everyMinute();
i put the same lines of codes (the logs and the mailable) in a controller and work perfectly, but in the schedule (kernel.php) doesnt work (only write every minute the two logs).
If you want to use closure command, add it to routes/console.php:
Artisan::command('send:email', function ($project) {
Log::debug("START TEST MAIL"); //this is write in log
$result = Mail::to('myemail#gmail.com')->send(new MailRecover('12345678aZ*'));
Log::debug("END TEST MAIL, RESULT: $result"); //this is write in log
});
Then run it in scheduler:
$schedule->call('send:email')->everyMinute();

Laravel sending email

I am trying to send an email from my application that uses the Laravel framework. I have installed Sximo as a theme for working with Laravel and the application is running on Amazon AWS. All seems to be good with the setup as it is working as intended.
I have a API setup on *C:\xampp\htdocs\public\api\savequestionnaire.php * that receives data from a mobile application and saves the data to a MySQL table. This also is working as intended.
The idea is that if the API receives some data, an email is generated to a predefined email address. With that, I have a file for receiving the data, writing it to a database and then generating the email as below.
For the Mail section I am following the example on the Laravel website from HERE
savequestionnaire.php
<?php
$json = file_get_contents('php://input');
$questionnairevalues = json_decode($json, true);
$position = $questionnairevalues['position'];
$question_one = $questionnairevalues['question_one'];
$question_two = $questionnairevalues['question_two'];
$question_three = $questionnairevalues['question_three'];
$question_four = $questionnairevalues['question_four'];
$question_five = $questionnairevalues['question_five'];
$query = "INSERT INTO tb_q (position, question_one, question_two, question_three, question_four, question_five) "
. "VALUES('$position', '$question_one', '$question_two', '$question_three', '$question_four', '$question_five')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if ($result) {
echo 'Success';
// Getting error here
Mail::send('emails.contact.blade', $position, function ($message) {
$message->from('myEmail#test.com', 'Laravel');
$message->to('myOtherEmail#test.com');
});
echo '\r\nMail sent success';
}
else {
echo 'Error';
}
mysqli_close($mysqli);
When I run the above code I get the error: "Success
Fatal error: Class 'Mail' not found in C:\xampp\htdocs\public\api\savequestionnaire.php on line 56"
I have also tried adding
use Mail;
to the top of the file but then I get the error: "Warning: The use statement with non-compound name 'Mail' has no effect in C:\xampp\htdocs\public\api\savequestionnaire.php on line 2"
How do I go about implementing the Mail feature correctly using Laravel?
I have also tried using PHP's built in
mail('myEmail#test.com', 'My Subject', 'My message');
function. This generates no errors - but no emails are sent or received.
add this at top of controller:
use Illuminate\Support\Facades\Mail;
In your case directly use :
\Illuminate\Support\Facades\Mail::send('emails.contact.blade', $position, function ($message) {
instead of Mail::send('emails.contact.blade', $position, function ($message) {
In Your Config / app.php Check whether there is
Illuminate\Mail\MailServiceProvider::class,
under providers. And Check Under Aliases you have
'Mail' => Illuminate\Support\Facades\Mail::class,
Edit :
According to the Error, it is looking the facade inside the questionnaire.php you are now in. So try putting this code inside of a controller.
To create a controller, in the terminal type,
php artisan make:controller controllerName
If this page is standalone, you have to use composer to be able to use Mail:
add
require 'vendor/autoload.php';
at the top of your page (replace the path for matching the location of your vendor/autoload.php file

Delay laravel push notification for 5 second

I am using ""davibennun/laravel-push-notification": "dev-laravel5" " for sending push notification. What i want is delay in sending notification after hit but dont want to stop the process. Is there any idea how can i do this or is this possible?
Following is the code to send push notification:
$pushNotification = PushNotification::app('appNameAndroid')->to($token);
$pushNotification->adapter->setAdapterParameters(['sslverifypeer' => false]);
$pushNotification->send($message);
Thanks in advance.
I found how to do this.
Following are the steps.
Run the following command
php artisan queue:table
php artisan migrate
Change .env
QUEUE_DRIVER=database
Create a job
php artisan make:job JobName
//In Job file
I have mentioned 2 protected variable in my job file
$message,$deviceToken
In _construct i assigned a value to the above variables.
public function __construct($deviceToken, $message)
{
$this->deviceToken = $deviceToken;
$this->message = $message;
}
In handle method
$pushNotification = PushNotification::app('appNameAndroid')->to($this->deviceToken);
$pushNotification->adapter->setAdapterParameters(['sslverifypeer' => false]);
$pushNotification->send($this->message);
//In my controller
$job = (new JobName($deviceToken, $message))->delay(10);
$this->dispatch($job);

Sending bulk emails using different credentials

I need to send hundreds of emails using different credentials from laravel.
Each customer of mine has his/hers mail list and needs to provide their own SMTP server. I process that list and send emails on customer's behalf.
This is what I have so far. It is working, but it is very slow and I don't have many emails so far. I see a problem when I get more emails.
Any suggestions on how to improve?
PS- I use cron Console Command and use Kernel to schedule the job.
public function sendMailings($allMailings) {
foreach ($allMailings as $email) {
Config::set('mail.host', $email['smtpServer']);
Config::set('mail.port', $email['smtpPort']);
Config::set('mail.username', $email['smtpUser']);
Config::set('mail.password', $email['smtpPassword']);
Config::set('mail.encryption', $email['smtpProtocol']);
Config::set('mail.frommmail', trim($email['fromEmail']));
Config::set('mail.fromuser', trim($email['fromUser']));
Config::set('mail.subject', trim($email['subject']));
Config::set('mail.toEmail', trim($email['toEmail']));
Config::set('mail.toName', trim($email['toName']));
Config::set('mail.pretend', false);
$email_body = $email['emailBody'];
Mail::send('emails.availability, compact('email_body')
, function($message) {
$message->from(config('mail.username'), config('mail.fromUser'));
$message->replyTo(config('mail.frommmail'), config('mail.fromUser'));
$message->to(config('mail.toEmail'), config('mail.toName'))->subject(config('mail.subject'));
});
Log::info('Mail was sent');
}
}
You can not change email provider configs on-the-fly, so you must make new instance of mailer in service container. I did it before, i wrote a method in my own class to get new mailer instance:
/**
* #return Mailer
*/
protected function getMailer()
{
// Changing mailer configuration
config(['mail.driver' => static::getName()]);
// Register new instance of mailer on-the-fly
(new MailServiceProvider($this->container))->register();
// Get mailer instance from service container
return $this->container->make('mailer');
}
Sending e-mail messages directly in web app can drastically slow down the responsiveness of your application. You should always queue your messages.
Instead of Mail::send You can use Mail::queue
and then from cron or manually call
php artisan queue:work
That will process the next item on the queue. This command will do nothing if the queue is empty. But if there’s an item on the queue it will fetch the item and attempt to execute it.

Need support about BLPOP Predis PHP

I am building chat message system long poll use BLPOP.
I used Predis PHP. When I run test/get ->it runs okie with 30s timeout.
While running test/get I try to push data by test/push but it has problem. Push not execute immediately unless test/get finished. test/push takes 30s.
I use command line to push data: RPUSH message:test hello -> It executes immediately and very nice.
require './vendor/autoload.php';
class Test extends CI_Controller {
public $keyChat = 'message:test';
public function __construct() {
parent::__construct();
}
public function push() {
$redis = new Predis\Client(['host' => 'localhost','port' => 6379]);
$redis->rpush($this->keyChat, 'hello you');
$redis->expire($this->keyChat, 3600);
echo "send message success";
}
public function get() {
$redis = new Predis\Client(['host' => '127.0.0.1','port' => 6379]);
$res = $redis->blpop($this->keyChat, 30);
var_dump($res);
}
}
If you checked the BLPOP documentation, you will find that it is a blocking operation, I suppose that you are trying to push by instantiating another Redis client, so BLPOP can find the value and return it.
The 30 seconds issue, is the timeout for BLPOP to unblock as in:
$redis->blpop($this->keyChat, 30);
The reason it works when you push it from the command line, is that it is a different connection, I am not sure in the case of Predis, but I think the same connection is returned when you try to RPUSH , that is why it is giving you that issue.

Categories