Skip to content

Instantly share code, notes, and snippets.

@jaygaha
Created February 16, 2024 04:59
Show Gist options
  • Save jaygaha/0790f62c1b94662167cbb2633777c4d9 to your computer and use it in GitHub Desktop.
Save jaygaha/0790f62c1b94662167cbb2633777c4d9 to your computer and use it in GitHub Desktop.
Get sender & receiver information in Mailable event listner in the Laravel

How to retrieve the name and email address in Laravel listner event to track emails status?

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment