jiannius / mailog
Jiannius Mailog - outgoing email audit logging for Laravel
Requires
- php: ^8.3
- illuminate/support: ^13.0
Requires (Dev)
- laravel/boost: ^2.0
- laravel/pint: ^1.0
- orchestra/testbench: ^11.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-laravel: ^4.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Audit-log every outgoing email your Laravel app sends — straight to the database, with no code
changes. Mailog listens to Laravel's mail events and records each message (sender, recipients,
subject, bodies, attachments, tags, the originating mailer/Mailable, the acting user, and the
send outcome) in a mail_logs table.
Requirements
- PHP 8.3+
- Laravel 13
Installation
composer require jiannius/mailog php artisan migrate
Not on Packagist yet — until it is, add a VCS repository to the host app's
composer.json:"repositories": [ { "type": "vcs", "url": "https://github.com/jiannius/mailog" } ], "require": { "jiannius/mailog": "dev-main" }
The service provider auto-registers and the migration auto-loads, so php artisan migrate
creates the mail_logs table. From that point every outgoing email is logged — Mail::send,
Mailables, framework notifications, queued mail, all of it. No further wiring.
What gets logged
Each send creates one Jiannius\Mailog\Models\MailLog row:
| Column | Contents |
|---|---|
status |
pending → sent, failed or cancelled (a row left pending means the send never completed) |
mailer |
the mailer name (e.g. smtp, ses) |
mailable |
the Mailable class, when sent via one |
user_id / user_name |
the resolved acting user + a name snapshot (see below) |
from / to / cc / bcc / reply_to |
[{address, name}] arrays |
subject |
the subject line |
html_body / text_body |
the full rendered bodies |
attachments |
[{filename, mime, size}] metadata (no file bytes) |
tags / metadata |
Symfony tag + metadata headers (Mailable::tag() / metadata()) |
message_id |
the transport message id, set once sent |
sent_at |
timestamp the transport accepted the message |
A row is created pending just before the transport sends the message and flipped to sent
once the transport accepts it. A message a MessageSending listener cancels (returns false)
never reaches the transport, so it gets no row. If the transport throws, the row becomes failed
(the exception goes in error, with failed_at); if the transport rejects the message before
sending, it becomes cancelled. A row left pending means the send never completed (e.g. the
worker died mid-send).
Mailog wraps a mailer's transport the first time it logs a send from that mailer, so
Mail::getSymfonyTransport() is the raw transport until the first logged send and a Mailog
decorator afterwards; unknown methods are forwarded to the real transport. Mailers are resolved
lazily, so config changed after boot is honoured.
Known caveats:
- On-demand mailers (
Mail::mailer([...]),Mail::build()) can't be wrapped, so Mailog inserts their row onMessageSending. A cancel, a throw, a rejection, or a transport that clones the message (most real transports) leaves their rowpending. - Mailers that aren't Laravel's cached instance (a
Mail::build()with a configured mailer name, a mailer instance held acrossMail::purge()) are logged when the message is sent, but only if their transport doesn't clone the message; with a cloning transport they get no row. - Earlier listeners. Mailog registers its
MessageSendinglistener in its service provider'sregister(), ahead of listeners registered during boot, but Laravel stops at the first listener that returns a non-null value. If a listener registered in another provider'sregister()before Mailog's does that, Mailog's listener is skipped. A mailer already wrapped by an earlier send still gets its row, built from the message alone:mailableis empty,except.mailablescan't apply, and data resolvers receive an event carrying onlymessageandmailer(no__laravel_*keys). A mailer not yet wrapped (its first send), and on-demand mailers, get no row, and the skip header is not stripped.
Querying logs
use Jiannius\Mailog\Models\MailLog; MailLog::sent()->latest()->get(); // confirmed sent MailLog::failed()->get(); // transport threw; see ->error MailLog::cancelled()->get(); // transport rejected the message MailLog::pending()->get(); // in-flight or never completed MailLog::where('to', 'like', '%@acme.com%')->get();
status is cast to Jiannius\Mailog\Enums\Status (PENDING, SENT, FAILED,
CANCELLED). FAILED is set automatically when the transport throws at send time, and you may
also set it from a bounce/complaint webhook. CANCELLED means the transport rejected the message
before sending.
Configuration
Logging works with no config. To customise, publish the file:
php artisan vendor:publish --tag=mailog-config
// config/mailog.php return [ 'enabled' => env('MAILOG_ENABLED', true), // master switch 'table' => 'mail_logs', 'except' => [ 'mailers' => [], // mailer names to skip, e.g. ['log', 'array'] 'mailables' => [], // Mailable classes to skip, e.g. [App\Mail\OrderShipped::class] ], ];
Opting out
Logging is on by default; opt specific email out three ways:
-
Master switch —
MAILOG_ENABLED=false(orconfig('mailog.enabled')) turns all logging off. -
Config exclude — list mailer names in
mailog.except.mailersor Mailable classes inmailog.except.mailables. -
Per-email — add the
X-Mailog-Skipheader to a message. Mailog skips it and strips the header before the message is sent:use Jiannius\Mailog\Mailog; // in a Mailable's headers(), or via ->withSymfonyMessage(...) $message->getHeaders()->addTextHeader(Mailog::SKIP_HEADER, '1');
Attaching the acting user
Each log records user_id + a user_name snapshot (so the log survives the user being
deleted — there is no foreign key). By default the user is auth()->user(). Override the
resolver in a service provider (cache-safe — never put a closure in a config file):
use Jiannius\Mailog\Mailog; public function boot(): void { // Return a model (uses getKey() + ->name), an ['id' => ..., 'name' => ...] array, or null. Mailog::resolveUserUsing(fn () => auth()->user()); }
Returning null (guests, queued jobs, console) leaves both columns null.
Custom columns (multi-tenant, etc.)
The MailLog model is unguarded, so you can attach your own columns — e.g. a tenant_id for a
multi-tenant app:
-
Publish and edit the migration:
php artisan vendor:publish --tag=mailog-migrations
$table->ulid('tenant_id')->nullable()->index();
-
Feed the value through the data resolver in a service provider:
use Jiannius\Mailog\Mailog; Mailog::resolveDataUsing(fn () => ['tenant_id' => tenant()->id]);
The returned array is filled onto the log, so the value lands in your real, indexed column:
MailLog::where('tenant_id', $id)->get().
How it works
Mailog subscribes to Laravel's MessageSending and MessageSent events. On sending it applies the
opt-outs, extracts every field from the Symfony Email, and keeps them aside; it also wraps the
mailer's transport in a decorator the first time it logs a send. The decorator inserts the
pending row just before the real send, so a cancelled mail leaves nothing behind, then flips it to
sent with the transport's message id, or to failed / cancelled when the send throws or is
rejected. The MessageSent handler is the fallback for mailers the decorator can't cover. The
message is correlated by the message object itself (via a WeakMap), so logging is reliable even
in long-running workers (Octane, queue:work).
Capture is wrapped so that a logging failure can never break your application's email — any exception while logging is reported and swallowed; the email still sends.
Development
This is a Composer library, so it has no artisan binary — Orchestra Testbench provides one
(vendor/bin/testbench boots a throwaway Laravel app configured by testbench.yaml).
composer install composer test # Pest 4 + Testbench suite vendor/bin/pest tests/Feature/MailLogTest.php # one file composer lint # Pint
Tests run against in-memory sqlite and extend Tests\TestCase (wired automatically via
tests/Pest.php).
License
MIT.