If someone still is looking here. This works for me:
The event handler:
//App/Providers/EventServiceProvider.php
<?php
namespace App\Providers;
use App\Listeners\SentEmailListener;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
MessageSent::class => [
SentEmailListener::class,
],
];
And the listener:
//App/Listeners/SentEmailListener.php
<?php
namespace App\Listeners;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class SentEmailListener
{
private $recipients;
private $subject;
public function handle(MessageSent $event)
{
$message = $event->message;
$this->subject = $message->getSubject();
$this->recipients = $event->sent->getEnvelope()->getRecipients();
$this->recipients = implode(', ', array_map(function(\Symfony\Component\Mime\Address $r){
return $r->getAddress();
}, $this->recipients));
$this->logMail($event);
$this->storeMail($event);
}
public function logMail(MessageSent $event)
{
Log::debug('E-Mail sent to '. $this->recipients . ': ' . $this->subject);
}
// https://pipo.blog/articles/20211203-laravel-mailer-log-eml
public function storeMail(MessageSent $event)
{
$messageId = $this->recipients . '_' . Str::slug($this->subject);
Storage::disk('emails')->put(
sprintf('%s_%s.eml', now()->format('Y-m-d_H-i-s_u'), $messageId),
$event->message->toString()
);
}
}
And the storage definition in config/filesystems.php
<?php
// ...
'disks' => [
// ...
'emails' => [
'driver' => 'local',
'root' => storage_path('logs/emails'),
],
],