Reputation: 77
Im using laravel 7, and I want to log every email that the system sends. I created a table for that. So I need to insert a record when the email is created, and then, when it's successfully sent, update that record with the sent date.
I use Mail class to make mails and send it. So, to prevent modifying the class (an avoid making a new one, because the class is used everywhere) I think I need to "tie" send method to my custom log action. Is that possible? I think in middleware but I need to modify the Mail class, or not?
What should I do?
Upvotes: 1
Views: 575
Reputation: 549
even you can avoid creating tables for logging. Just using Redis to store these kinds of data permanently and use events to catch what's happening in your web application.
Upvotes: 0
Reputation: 15786
According to the 7.x documentation
# Events
Laravel fires two events during the process of sending mail messages. The MessageSending event is fired prior to a message being sent, while the MessageSent event is fired after a message has been sent. Remember, these events are fired when the mail is being sent, not when it is queued. You may register an event listener for this event in your EventServiceProvider:
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'Illuminate\Mail\Events\MessageSending' => [ 'App\Listeners\LogSendingMessage', ], 'Illuminate\Mail\Events\MessageSent' => [ 'App\Listeners\LogSentMessage', ], ];
The example looks pretty much like what you're looking for. As for logging when a mail is not successful, you could just do it in a catch
block.
try {
Mail::to(...)->send(...);
} catch (\Exception $e) { // Maybe use a more specific mail-related exception.
// Log failed mail.
}
or use the Exception handler to write a way every mail related exception should be handled.
Upvotes: 6