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.).
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With