I am working on queue jobs in laravel v5.4. Now I want to send an email to users through email later function. Below is my function that I am using
public static function singleEmailQueueJob(){
for($i=1; $i<=2; $i++){
$time = $i * 10;
$data['email'] = 'abc#gmail.com';
$data['name'] = "Rizwan_$time";
$data['subject'] = 'Queue Job Testing->'.$i;
$data['verification_code'] = base64_encode($i.time());
\Mail::later($time,'emails.password', $data, function ($m) use ($data) {
$m->from(CommonHelper::$email_info['admin_email'],CommonHelper::$email_info['site_title']);
$m->to($data['email'],$data['name']);
$m->subject($data['email']);
});
}
echo "Email send successfully";
}
when I run this function i receive following error in exception
{"success":"false","message":"Only mailables may be queued."}
in .eve file i set
QUEUE_DRIVER=database
and in config/queue.php
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
I don't know where is the problem in code. Please help.
I have found the issue by using the following code
$date = Carbon::now()->addMinutes($time);
Queue::later($date, new EmailSending($data));
Now I am able to send emails in queue
Thanks to help me
In my case I have created job 'SendVerificationEmail' and I call this job after successful registration of user like this.
dispatch(new SendVerificationEmail($user));
Do you also dispatch(your_job) in your code???
Related
I run a cronjob every minute and data returne, i save on db in a table notification. But here i need to save also user_id. I mean i know we can not find Auth::user()->id on cronjob but how can we get this user id?
public function handle(ReminderEventServices $reminderServices)
{
// return 0;
// $getLastReminders = $reminderServices->ReminderEvent();
$getLastReminders = Reminder::orderBy('id', 'DESC')->get();
return app('App\Http\Controllers\NotificationController')->store($getLastReminders);
}
I have send request to Notification controller , hoping there i can use there Auth but i was wrong.
public function store($getLastReminders)
{
$user_id = Auth::user()->id;
foreach($getLastReminders as $reminder) {
if (!Notification::where('title', $reminder->title)->exists()) {
$notification = Notification::create([
'title' => $reminder->title,
'user_id' => $user_id,
'description' => $reminder->description,
'remindTime' => $reminder->remindTime
]);
}
event(new ReminderEvent($reminder));
}
}
You should try another approach - the cron job is not supposed to handle users in that way. Consider trying an event listener or an observer instead. I've included the link to Laravels documentation on events for your convienience.
I'm trying to setup a cron job to run a console command every minute.
class RescanCommand extends Command {
public function sendMail() {
$email = new Email();
// Sample SMTP configuration.
Email::setConfigTransport('mailtrap', [
'host' => 'smtp.mailtrap.io',
'port' => 25,
'username' => 'username',
'password' => 'pass',
'className' => 'Smtp'
]);
$email->setFrom(['test#test.com' => 'CSV file'])
->setTo('test#test.com')
->setSubject('CSV Link File')
->send('Please find attached a copy of the links');
}
public function execute(Arguments $args, ConsoleIo $io) {
$this->sendMail();
}
}
I can run the above code from command line by
bin/cake rescan execute
and I receive the test email, but after creating a cron job by editing cron tabs like
crontab -e
and inside the file by writing
*/1 * * * * cd /Applications/MAMP/htdocs/music && bin/cake Rescan execute
nothing happens, I was expecting to receive emails every minute,
can anyone please help find out what I'm doing wrong.
Thanks
Goodnight
Porblem 1.-
I need to send more than 1000 emails for each event created, and for this I use queue (as Laravel's documentation says), but when sending the emails I have to wait until all the emails are sent to return to the view of control Panel
this is my "store" function in NewsEvents.php controller that sends the emails
public function store(Request $request)
{
$attributes = request()->validate(News::$rules, News::$messages);
$news = $this->createEntry(News::class, $attributes);
//queue for sending emails
$this->dispatch(new Nevent($news));
return redirect_to_resource();
}
the "handle" function of job "Nevent.php"
public function handle()
{
//
$users=User::where('tipo_user','user')->get();
foreach($users as $user)
{
$user->notify(new EventCreated($this->news));
echo 'enviado correo';
Informe::create([
'event_id' => $this->news->id,
'total' => '1',
'tipo' => 'invitacion',
'dst_id' => $user->id,
'estado' => 'correcto',
]);
}
}
What could be the problem?
problem 2.-
How could I send an email for every minute?
since when sending all emails my server responded with this message:
Domain mu.edu.fi has exceeded the max emails per hour (100/100 (100%)) allowed. Message will be reattempted later
If u are using Redis server for managing jobs, Laravel provides a simple
API for Rate Limiting API's
Redis::throttle('your job id')->allow(10)->every(60)->then(function () {
// Job logic...
}, function () {
return $this->release(10);
});
Hope this helps.
I'm trying to dispatch Welcome Email on Laravel 5.2 but the job is failing and I have no idea how to figure out why.
Here is what I have so far:
public function test(Request $request) {
$email = $request->get('email');
$subject = $this->word('emails.welcome.subject');
// Mail::send # I use this to Send it synchronously
// $this->mailQueue->queue # I use this to Queue
('emails.welcome', ['domain' => 'blablabla', 'name' => 'Marco Aurélio Deleu', 'date' => Carbon::now(),
'total' => 100, 'pretext' => '', 'score' => '', 'surtext' => '', 'password' => 'blabla', 'shop' => ''],
function ($message) use ($email, $subject) {
$message->to($email);
$message->subject($subject);
}, true);
return 'queued';
}
I noticed that Jobs can easily fail when any kind of exception is thrown, so I figured that I could use Mail::send to find out which exception was being thrown / what was the problem and then use the $this->mailQueue->queue() when I had it sorted out.
I managed to use this strategy to find out that I can't use function calls inside the closure, but now I just don't know what else to do in order to find where the problem lies. The synchronous method of sending the email directly works just fine and the email arrives, but the job will fail at a queue.
The last piece of evidence that I have is that the problem is in the $data array, because if I use it without any $data, the job will be processed and the email arrives.
...
// If I use it like this, it will work perfectly.
$this->mailQueue->queue
('emails.welcome', [ /* empty array */ ], function ($message) use ($email, $subject) {
$message->to($email);
$message->subject($subject);
}, true);
Here is the Queue Listener:
// --> This is the job failing with $data array <--
[06:34 PM]-[root#local]-[/project/]-[git sign-up-with-email]
# php artisan queue:listen --timeout=30 --tries=1
[2016-06-28 21:34:29] Failed: mailer#handleQueuedMessage
^C
// --> This is the job working with empty $data array <--
[06:35 PM]-[root#local]-[/project/]-[git sign-up-with-email]
# php artisan queue:listen --timeout=30 --tries=1
[2016-06-28 21:44:31] Processed: mailer#handleQueuedMessage
I have been able to get my Iron.io push queue subscription to work great, but not with mail queues for some reason. In the code below I am pushing a job onto the queue with an email address and username in the $data array. For reasons unknown to me, the email address and username are not getting passed to the Mail function. The job just sits there, failing to send.
FooController.php
<?php
$data = array(
'email_address' => Input::get('email'),
'username' => Input::get('username'),
);
Queue::push('SendEmail#reserve', $data);
routes.php
<?php
// iron.io push queue path
Route::post('queue/push', function()
{
return Queue::marshal();
});
class SendEmail
{
public function reserve($job, $data)
{
Mail::send('emails.reserve', $data, function($message)
{
$message->to($data['email_address'], $data['username'])->subject($data['username'] . ', welcome to RockedIn!');
});
$job->delete();
}
}
?>
You need to pass $data to the closure.
public function reserve($job, $data)
{
Mail::send('emails.reserve', $data, function($message) use ($data)
{
$message->to($data['email_address'], $data['username'])->subject($data['username'] . ', welcome to RockedIn!');
});
$job->delete();
}