Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Mailer Callback when using Queue

Is there a way to pass a callback function to Laravel's mailer?

I'm using the Mail facade with a mailable class, which is sending out an attachment. I would like to delete the attached file form storage once the email is sent.

The email job is being queue

Mail::to($user)->send(new MyMailable($file));

I wasn't able to use the Mailer fired event (https://laravel.com/docs/5.4/mail#events). One reason, because the event happens before the email is sent, meaning I wouldn't be able to delete the file at that moment, or the message won't have the attachment. Second, the application has multiple email jobs, some where the attachment must be deleted, and others where it won't be. The event data has the swiftmailer instance only, with no extra information about the job itself (data in mailable for ex.).

like image 456
crabbly Avatar asked May 31 '17 19:05

crabbly


1 Answers

Laravel fires off an event right when the email is being sent. This does not mean that the message was queued, or that the user received it, but that it is sent.

Pop open your EventServiceProvider and add the following to the $listen array:

'Illuminate\Mail\Events\MessageSending' => [
    'App\Listeners\HandleSentMessage',
],

Then in the public function handle() method of the HandleSentMessage listener, accept the MessageSending $event as the first argument, such as:

public function handle(MessageSending $event) {
    //do whatever with the event data
}
like image 99
Ohgodwhy Avatar answered Oct 18 '22 18:10

Ohgodwhy