Laravel provides excellent support for email sending. Sometimes you need to record the status of outgoing emails in the system. You must construct two tables: email_logs
and email_log_statuses
. The 'email_logs' table contains all outgoing emails, while the email_log_statuses
table contains all email statuses such as sent, failed, queued, scheduled to send, and so on.
Now, create Event Listeners During the email-sending process, Laravel triggers multiple events. You can set up event listeners to record these events and update the email log accordingly.
php artisan make:listener SendEmailListener --event='Illuminate\Mail\Events\MessageSending'
php artisan make:listener SentEmailListener --event='Illuminate\Mail\Events\MessageSent'
php artisan make:listener FailedEmailListener --event='Illuminate\Mail\Events\MessageFailed'
Implement Event Listeners In each listener, write logic to create or update the email_logs
entry based on the event.
// app/Listeners/SendEmailListener.php
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
public function handle(MessageSending $event): null|bool
{
// Generate a unique ID for the email
$uniqueId = Str::uuid()->toString();
// Attach unique ID to message headers so it can be tracked in logs and database
$event->message->getHeaders()->addTextHeader('X-Message-ID', $uniqueId);
$fromEmail = Arr::first($event->message->getFrom())?->getAddress();
$fromName = Arr::first($event->message->getFrom())?->getName();
$toEmail = Arr::first($event->message->getTo())?->getAddress();
$toName = Arr::first($event->message->getTo())?->getName();
// add above variables in the array and insert into the table
EmailLog::create([
...
]);
// Add status in the status table
}
With this implementation, you can retrieve the sender & receiver information to add into the table.