Laravel Mail Listener (can be canceled before sending)

Is there a way to use the Laravel Event class to run code before sending each message? I would also like to cancel Mail::send(); .

Of course, I could do this before sending an email:

 Event::fire('email.beforeSend'); 

And then I could listen like this:

 Event::listen('email.beforeSend', function() { //my code here }); 

The problem is that I have to remember to fire Event::fire() , which I would rather not do. In my case, I bounce the email address from the unsubscribe list to make sure that I do not send spam.

+5
source share
1 answer

The Laravel Mail class starts mailer.sending as part of the sending process.

 protected function sendSwiftMessage($message) { if ($this->events) { $this->events->fire('mailer.sending', array($message)); } if ( ! $this->pretending) { $this->swift->send($message, $this->failedRecipients); } elseif (isset($this->logger)) { $this->logMessage($message); } } 

You can catch this event and adjust the $message object, or you can probably prevent sending by calling Mail::pretend(); inside your event handler.

+4
source

Source: https://habr.com/ru/post/1210506/


All Articles