I’m creating one webapp and sending bunch of emails through laravel Mail helper function (code is given below), Now i want to store the log each mails including everything. i.e. email subject, recipients, bcc. in my local database to display admin. but code is old so at many places the mail helper function is used, but I want to achieve it at doing at only one place. Is it possible in laravel? see the code I’m using to send mail and store log at every places.
Mail::to($to)->cc($bcc)->send(new \App\Mail\Mailer($maildata));
2
Answers
If Mail is PEAR’s Mail:: interface, then ->send returns true on successfull delivery or false otherwise. If there are some errors in the mail communication, eg. related to malformed headers, you have a Pear Error.
Having this in your mind, you can access the Mail object and find what you need inside the object himself.
Check this little function as a starting points: it uses Mail Pear class
You can use Laravel’s built-in event system and logging system.
First, you need to define an event listener that will listen for the IlluminateMailEventsMessageSending event. This event is triggered just before the email message is sent, so it’s the perfect place to log the email data.
This event listener will log the recipient’s email addresses, CC email addresses, BCC email addresses, subject, and body of the email message.
Next, you need to register the event listener in your EventServiceProvider.
Finally, you can use Laravel’s built-in logging system to log any exceptions that occur during email sending. You can define a Mail log channel in your config/logging.php:
Also log any errors in the following way: