welfordian's avatar

Laravel Mail Before Send Event?

Hi,

Is there an event which is fired when an email is about to be sent? If there is, is it also possible to cancel that email from being sent directly within the event listener?

I am looking for the easiest way to exclude a domain name from receiving emails without changing this functionality in multiple places.

Thanks!

0 likes
10 replies
Skipp's avatar

Couldn't you just check the domain before you actually send the mail?

welfordian's avatar

Well, I could have done this if the emails hadn't already been set in the code. There are far too many places in the code base to go through and replace them all. Isn't there an easier way to do it? No events or anything?

ricardoarg's avatar

Are you using the Notifiable trait? If that's the case, you could have public function routeNotificationForMail() in your model, and I think that, if you return empty string, it will not send the mail to that user.

welfordian's avatar

I'm also using Laravel 5.2 and I'm sure Notifiables are in 5.3?

shez1983's avatar

when you say emails set in the code.. do you mean same email in different places or different emails?

if same.. i would do a find all in library /replace with an env('mail') or use config.mail.email_from or whatever it is. it feels a bit 'weird' having email (personal identifying info) in the code..

if different then it depends on how many differnet emails.. if <5 you could create a new env() for each and do a replace all mentioned above..

finally https://laravel.com/docs/master/mail#events mention an event being fired which you can listen to and hopefully do something..

welfordian's avatar

Thanks for the above reply, however there's a lot more than... Probably 30+ places in my code base where different emails are sent. And, unfortunately, the only event Laravel seems to provide is an event AFTER the email has been sent.

shez1983's avatar

the doc say:

'Laravel fires an event just before sending mail messages. Remember, this event is fired when the mail is sent, not when it is queued. You may register an event listener for this event in your EventServiceProvider:'

welfordian's avatar

Yeah, so it fires the event when the email has been SENT. Not when it has been queued. :-(

Snapey's avatar

I just tried it, so the event fires before the email is sent, (if I die in the event the mail is not sent) but I don't think there is any way to abort it or alter the actual message object?

Please or to participate in this conversation.