Mail goes through Laravel’s mail notifications (TypedMailNotification), in the recipient’s locale (HasLocalePreference::preferredLocale()).
De-dup within the window
The de-dup key has the same parts as the inbox collapse key, so one inbox item and one delivery always pair up:
- Leading (the default, notifications.mail.strategy) — the first event mails now (or at the end of quiet hours); later events in the window fold into that delivery and send nothing more. Ten events in five minutes → one mail.
- Trailing (mailStrategy(): MailStrategy::Trailing) — the delivery waits first event + window; every event folds in, and one mail goes out with the final count and the latest content.
- Urgent types always mail on the leading edge. A mail not yet sent absorbs later events (Folded); a sent one only counts them (Deduplicated). When several events folded before it went out, it says “And N more updates”.
// Leading (default): the first event mails now; later ones in the window fold into it
Notifications::send('request.awaiting_approval', $request, $approver); // MailOutcome::Pending
Notifications::send('request.awaiting_approval', $request, $approver); // MailOutcome::Folded (or Deduplicated once sent)
// Trailing: one mail after the window, with the final count and the latest content
final class CommentPosted extends NotificationType
{
public function window(): ?string { return 'PT10M'; }
public function mailStrategy(): MailStrategy { return MailStrategy::Trailing; }
// …
}The life of a delivery
| Status | Meaning |
|---|---|
pending → sending → sent | The normal path. DeliverMailJob claims the row by compare-and-set, so a retried job or a second scheduler sends nothing. A mail over the rate limit goes back to pending until the limit frees up (when_limited defer), its attempt given back. |
held | Quiet hours — released by the sweep when they end; checked again at delivery and held again if quiet hours started meanwhile. A hold never uses up a transport attempt. |
digest | Parked for the user’s digest. |
cancelled | recipient_gone, unknown_type, subject_gone, no_access, muted (mandatory excepted), revoked — re-checked right before sending; rate_limited with when_limited skip. |
failed | render (a type hook threw — reported, no retry), transport (after mail.max_attempts with mail.backoff between tries), unknown (still sending after mail.lease — never re-sent). |
undeliverable | no_address — the resolver returned null, or the recipient has no mail route; suppressed — the suppression list suppresses an address the mail would go to. |
The address is resolved before Laravel’s mail channel: the configured address resolver, else routeNotificationFor('mail'). After the address the suppression list is asked and — when on — the rate limit (see below). With notifications.queue.enabled off the job runs inline after the commit; otherwise it is dispatched on notifications.queue.connection / queue, and the sweep dispatches a due delivery again only after notifications.mail.lease, in case its job was lost — a backlog never piles up duplicate jobs. Events: NotificationMailSent, NotificationMailFailed, NotificationMailHeld, NotificationMailSuppressed, NotificationMailThrottled.
A trailing mail held for quiet hours stays behind its window when the user changes quiet hours or timezone, so it still carries the window’s final count. A mail marked sent inside its window keeps its de-dup key without writing it back, so another mail that took the key over meanwhile never fails a delivered row.
Rendering
Subject = title(); a greeting (with the recipient’s name when present); the first line = body() (else the title); “And N more updates” when folded; the action button (url() + actionText(), absolute http(s) only); a footer — the mandatory notice for mandatory types, else the preferences link when notifications.mail.preferences_url (a URL or a route name) is set; then the type’s mail($message, $payload) hook. Text goes through Laravel’s markdown template, which escapes it. Assert it in a host test:
use Illuminate\Support\Facades\Notification;
use RoundlyConsulting\Notifications\Mail\TypedMailNotification;
Notification::assertSentTo($user, TypedMailNotification::class, fn ($n) => $n->type === 'security.alert'
&& $n->message->subject === 'Security alert');Minimal mail for sensitive subjects
When a type’s sensitive($subject) is true and notifications.mail.minimal_for_sensitive is on (the default), the mail carries minimalTitle() (“New notification from :app”), one line and the button — body() and mail() are not called. Digest lines of sensitive items use the minimal line too. The inbox is unaffected: it is behind your auth.
The address resolver
notifications.mail.address_resolver names a ResolvesMailAddress that decides the address of every mail the package sends — typed mail and digests alike; the payload is null for a digest. A string sends to that address; null makes the delivery undeliverable (a digest run fails as no_address). With contacts-for-laravel, mail goes to the user’s primary email contact:
class User extends Authenticatable
{
use HasContacts;
use Notifiable;
use ReceivesNotifications;
use RoutesNotificationsViaContacts; // mail goes to the primary email contact
}For verified addresses only, bind a resolver — a user without a verified primary email then gets undeliverable, and no digest either:
use Illuminate\Database\Eloquent\Model;
use RoundlyConsulting\Contacts\Enums\ContactType;
use RoundlyConsulting\Notifications\Contracts\ResolvesMailAddress;
use RoundlyConsulting\Notifications\NotificationPayload;
final class VerifiedEmailResolver implements ResolvesMailAddress
{
public function address(Model $recipient, ?NotificationPayload $payload): ?string // null payload = a digest
{
$contact = $recipient->primaryContact(ContactType::Email);
return $contact?->verified_at !== null ? $contact->value : null;
}
}
// config/notifications.php
'mail' => ['address_resolver' => App\Notifications\VerifiedEmailResolver::class],Suppression list
SuppressionList — isSuppressed(string $address): bool — is asked before every typed mail and digest with each address the mail would go to: the resolver’s address, or every address routeNotificationFor('mail') names (a string, a list, objects with an email, or an address => name map), trimmed with the case kept — compare case-insensitively in your list if it needs it. One suppressed address stops the whole mail: a delivery ends undeliverable (suppressed), a digest run failed with its entries failed (suppressed), and NotificationMailSuppressed fires with the recipient, the suppressed addresses and the delivery or the digest run. Other packages’ mapped mail (interop) is not checked.
use RoundlyConsulting\Notifications\Contracts\SuppressionList;
final class BouncedAddresses implements SuppressionList
{
public function isSuppressed(string $address): bool
{
return Bounce::query()->where('email', strtolower($address))->exists();
}
}
// config/notifications.php
'mail' => ['suppression_list' => App\Mail\BouncedAddresses::class],Bind it through notifications.mail.suppression_list or in the container — a host or another package binding the contract in its own provider wins. The default NullSuppressionList suppresses nothing. A lookup that throws (the list’s database is down) is a transport error: retried, then failed (transport) — the mail never goes out unchecked. A class that does not implement the contract throws the toolkit’s InvalidConfigurationException naming the key when it is resolved.
Rate limit (opt-in)
With notifications.mail.rate_limit.enabled on, the ThrottlesMail contract is asked right before a typed mail goes to the mailer, with the recipient, the type, the delivery’s context key and the delivery id. Null sends the mail and counts it; a time means it is over a limit until then, and nothing is counted. Then, by rate_limit.when_limited:
- defer (the default) — the delivery goes back to pending with send_after at that time (at least one second ahead), its attempt given back like a quiet-hours hold; the sweep sends it then, and later events of its window still fold in.
- skip — the delivery is cancelled (rate_limited).
Either way NotificationMailThrottled (delivery, until, deferred) fires. Digests and other packages’ mapped mail are not limited, and urgent types never are. The default DefaultMailThrottle counts with Laravel’s RateLimiter — the cache.limiter store, else the default cache; use one shared across servers, the doctor warns about array and file:
| Key | Default (max / per) | Counts |
|---|---|---|
rate_limit.per_recipient | 20 / PT1H | Every typed mail to one recipient. |
rate_limit.per_context | off (max null) / PT1H | Every typed mail in one context, whoever receives it. |
// .env
NOTIFICATIONS_MAIL_RATE_LIMIT=on
// config/notifications.php
'mail' => [
'rate_limit' => [
'enabled' => env('NOTIFICATIONS_MAIL_RATE_LIMIT', 'off'),
'throttle' => DefaultMailThrottle::class, // or your own ThrottlesMail
'per_recipient' => ['max' => 20, 'per' => 'PT1H'],
'per_context' => ['max' => 200, 'per' => 'PT1H'], // null max: off (the default)
'when_limited' => 'defer', // or 'skip'
],
],A blank max turns a cap off. Each cap is counted increment-first — the cache increments atomically — so two workers never both take the last slot, and a mail refused by one cap gives back what it counted on the other. A mail whose transport then fails still counts. For other rules (per type, per recipient and context, tenant plans) bind your own ThrottlesMail through rate_limit.throttle:
namespace RoundlyConsulting\Notifications\Contracts;
use Carbon\CarbonImmutable;
use RoundlyConsulting\Notifications\DataTransferObjects\MailAttempt;
interface ThrottlesMail
{
// null: send now (and count it). A time: over a limit until then — nothing is counted,
// the mail is deferred to that time or skipped (rate_limit.when_limited)
public function attempt(MailAttempt $attempt): ?CarbonImmutable;
}
// MailAttempt: recipient (Model), type (NotificationType), contextKey (?string), deliveryId (int|string)use RoundlyConsulting\Notifications\Events\NotificationMailSuppressed;
use RoundlyConsulting\Notifications\Events\NotificationMailThrottled;
Event::listen(NotificationMailSuppressed::class, fn (NotificationMailSuppressed $event) => Log::info('Mail suppressed', [
'addresses' => $event->addresses, // list<string>
'delivery' => $event->delivery?->getKey(), // a typed mail…
'digest_run' => $event->digestRun?->getKey(), // …or a digest
]));
Event::listen(NotificationMailThrottled::class, fn (NotificationMailThrottled $event) => $event->deferred
? Log::info('Mail deferred until '.$event->until->toIso8601String())
: Log::info('Mail skipped (rate_limited)'));One-click unsubscribe (opt-in)
With notifications.mail.list_unsubscribe.enabled on, the mail of every type the recipient can switch off — never a mandatory type — carries the RFC 2369 List-Unsubscribe header and, over https, the RFC 8058 one-click header:
NOTIFICATIONS_LIST_UNSUBSCRIBE=onList-Unsubscribe: <https://app.example/notifications/unsubscribe/{token}>
List-Unsubscribe-Post: List-Unsubscribe=One-Click// config/notifications.php
'mail' => [
'list_unsubscribe' => [
'enabled' => env('NOTIFICATIONS_LIST_UNSUBSCRIBE', 'off'),
'middleware' => [], // never 'web': its CSRF check refuses a mail client's POST
'ttl' => null, // ISO-8601, e.g. 'P90D'; null: links never expire
],
],- The one-click header needs an https link (an https APP_URL); over http only List-Unsubscribe is added and the doctor warns. Mail clients and providers require the headers to be DKIM-signed — your mail setup’s job.
- Digests carry neither header: a digest mixes types, and switching it off would send its items one by one — the preferences footer covers it.
- The token is the credential: the recipient, the type and an optional expiry (list_unsubscribe.ttl), encrypted and signed with the app key through Laravel’s encrypter. It can be neither read nor forged, names no class, and app.previous_keys keep old links working after a key rotation.
- Redeeming switches the type’s mail off for the recipient — the same per-type override preferences($user)->mute($type, Channel::Mail) writes. The inbox keeps the item, the settings screen shows the change and can switch it back on, and NotificationPreferenceChanged fires.
The route (<routes.prefix>/unsubscribe/{token}) loads only while the feature is on, independent of routes.enabled, and has no login, session or CSRF — list_unsubscribe.middleware is []; never add web. Pages are plain HTML in the recipient’s locale (the notifications::unsubscribe view, English and Slovak):
| Method + path | Name | Does |
|---|---|---|
GET /notifications/unsubscribe/{token} | notifications.unsubscribe.show | Changes nothing — a confirmation page whose button POSTs, so link scanners never unsubscribe anyone. |
POST /notifications/unsubscribe/{token} | notifications.unsubscribe | Switches the type’s mail off and answers 200 with a small page every time — idempotent. A tampered, foreign or expired token is 403; a busy preference lock is 423 and the client retries. |
Publish the routes (--tag=notifications-routes) to change the path, or build your own endpoint on the accessor:
use RoundlyConsulting\Notifications\Enums\UnsubscribeOutcome;
Notifications::unsubscribe()->url($user, 'comment.posted'); // ?string — for your own mail or page
Notifications::unsubscribe()->claim($token); // UnsubscribeClaim {recipient, type}, changes nothing
$result = Notifications::unsubscribe()->redeem($token); // UnsubscribeResult {outcome, type, recipient}
$result->outcome === UnsubscribeOutcome::Unsubscribed; // or AlreadyUnsubscribed, Required, Gone
// claim() and redeem() throw InvalidUnsubscribeTokenException (403) for a bad token| UnsubscribeOutcome | Meaning |
|---|---|
Unsubscribed | The type’s mail is now off for the recipient — the same per-type override as preferences($user)->mute($type, Channel::Mail). |
AlreadyUnsubscribed | It was off already, or the type sends no mail: nothing changed. |
Required | The type has become mandatory: its mail stays on. |
Gone | The recipient or the type no longer exists. |
Under Notifications::fake() a redeem is recorded with the link’s recipient and type, and a bad token still throws:
$fake = Notifications::fake();
Notifications::unsubscribe()->redeem($token); // or the one-click POST — the controller goes through the manager
$fake->assertUnsubscribed($user, 'comment.posted'); // recipient and type optional; a key or a class
// $fake->assertNothingUnsubscribed(); // the negativeShow your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.