ruvelo / laravel-unsubscribe
One-click unsubscribe (RFC 8058) and a simple email preferences page for Laravel, as Gmail and Yahoo require of bulk senders.
Requires
- php: ^8.3
- laravel/framework: ^12.4.1|^13.0
Requires (Dev)
- larastan/larastan: ^3.13
- laravel/pint: ^1.32
- orchestra/testbench: ^10.0|^11.0
- phpunit/phpunit: ^11.5|^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Quick start Configuration Upgrading Developer guide Changelog
Laravel Unsubscribe
One-click unsubscribe and a simple email preferences page for your Laravel app, the way Gmail and Yahoo require of anyone sending marketing email in bulk.
Quick start
composer require ruvelo/laravel-unsubscribe
php artisan migrate
Add the trait to the Mailable (or Notification) people should be able to unsubscribe from:
use Ruvelo\Unsubscribe\Unsubscribable; class MonthlyNewsletter extends Mailable { use Unsubscribable; }
That's it. Every MonthlyNewsletter now carries the one-click unsubscribe headers, the link in them unsubscribes without a login, and it is no longer sent to anyone who did. The topic is newsletter until you add your own.
What you get
List-UnsubscribeandList-Unsubscribe-Postheaders on every email with a topic (RFC 8058), with a signed https link and an optionalmailto:.- A one-click endpoint that unsubscribes on POST, with no login, cookies or CSRF token, and never redirects.
- Email to anyone who unsubscribed is skipped automatically, for Mailables and Notifications.
- An email preferences page behind a signed link: a switch per topic, and "Unsubscribe from all".
- Works for your users and for plain email addresses, such as newsletter subscribers without an account.
<x-unsubscribe::footer />andunsubscribe_url()for the visible link in the email body.- Transactional topics (receipts, password resets) that can't be turned off and get no headers.
- In English, French, Spanish and German; light and dark; no JavaScript, no build step.
Optional features
All are off until you set them.
A mailto: fallback
Set UNSUBSCRIBE_MAILTO=unsubscribe@yourapp.com and the header also offers <mailto:unsubscribe@yourapp.com?subject=unsubscribe%20newsletter>, for mail clients without one-click support. Reading that mailbox is up to you. Details.
Your own "all marketing" switch
Already have a marketing_emails column on users? Set global_switch to its name and anyone with it off counts as unsubscribed from every topic that isn't required. Details.
Topics for classes you can't edit
Give a Mailable or Notification from another package a topic in config, without touching it: 'classes' => [InboxDigest::class => 'digests']. Details.
Why you need it
Gmail asks anyone sending close to 5,000 messages a day to Gmail accounts to make marketing and subscribed messages "support one-click unsubscribe, and include a clearly visible unsubscribe link in the message body". It wants both headers, List-Unsubscribe-Post: List-Unsubscribe=One-Click and List-Unsubscribe: <https://...>, and its FAQ says a mailto: link alone "doesn't meet our one-click unsubscribe requirement", that transactional messages are excluded, and that unsubscribes must be honoured within 48 hours. Yahoo asks bulk senders for "a functioning list-unsubscribe header, which supports one-click unsubscribe for marketing and subscribed messages", a clearly visible unsubscribe link in the body ("this may direct to a preference page"), and to honour unsubscribes within 2 days.
This package does the sending side of all of that, and unsubscribes immediately. What it can't do for you: sign your mail with DKIM. RFC 8058 (section 4) requires a valid DKIM signature that covers both headers, or providers won't offer the button. Most email services (Postmark, Mailgun, SES, Resend, …) sign every header they're given; check yours does.
What RFC 8058 asks, and how the package answers:
| RFC 8058 | Here |
|---|---|
One List-Unsubscribe with exactly one HTTPS URI, other URIs such as mailto: allowed (3.1) |
A signed https link, plus mailto: when you set one |
One List-Unsubscribe-Post: List-Unsubscribe=One-Click (3.1) |
Added with it |
| The URI should hold an opaque, hard-to-forge identifier, and the sender should check it (3.1) | An opaque token plus Laravel's URL signature; no address in the link |
| The POST comes without cookies, HTTP auth or other context (3.1) | The routes run outside the web group: no session, no CSRF |
| The sender must not answer the POST with a redirect (3.1) | A plain 200 page |
| Mail software fetches URLs in headers and accidentally unsubscribes people (abstract, 1) | GET only shows a confirmation page; only POST unsubscribes |
Using it
Topics
A topic is a kind of email people can leave: the newsletter, product updates, event invitations. Publish the config (php artisan vendor:publish --tag=unsubscribe-config) and list yours:
'topics' => [ 'newsletter' => [ 'label' => 'Newsletter', 'description' => 'News, tips and announcements, now and then.', ], 'product' => [ 'label' => 'Product updates', 'description' => 'New features, once a month.', ], 'account' => [ 'label' => 'Account emails', 'description' => 'Receipts, password resets and security alerts.', 'required' => true, ], ],
Keys are short slugs. Labels and descriptions go through Laravel's translator, so they can be plain text or translation keys. A required topic is listed on the preferences page as "Always on", can't be turned off, never suppresses an email, and gets no headers: use it for transactional mail. You can also register topics in a service provider with Unsubscribe::topics([...]).
Keep a topic in the config as long as sent emails may link to it: a link to a topic that no longer exists is a 404.
Mailables
use Ruvelo\Unsubscribe\Unsubscribable; class ProductUpdate extends Mailable { use Unsubscribable; protected string $unsubscribeTopic = 'product'; }
Without $unsubscribeTopic, the topic is default_topic (newsletter). To choose at send time, override unsubscribeTopic(): string.
Send it as usual, one recipient per message as bulk mail should be: Mail::to($subscriber)->send(new ProductUpdate). If a message has several recipients, those who unsubscribed are taken off it, and if nobody's left it isn't sent. A message with more than one recipient gets no headers, since there's no single person for the link to unsubscribe.
Notifications
The same trait:
use Ruvelo\Unsubscribe\Unsubscribable; class WeeklyTips extends Notification { use Unsubscribable; protected string $unsubscribeTopic = 'newsletter'; public function via(object $notifiable): array { return ['mail', 'database']; } }
Or the interface, if you'd rather:
use Ruvelo\Unsubscribe\Contracts\Unsubscribable; class WeeklyTips extends Notification implements Unsubscribable { public function unsubscribeTopic(): string { return 'newsletter'; } }
For someone who unsubscribed, only the mail channel is skipped: the in-app notification still arrives (add channels to unsubscribe.channels to skip them too). Users are checked by their model and by their address, so an unsubscribe from either a user's link or a plain-address link applies, and one made as a user follows them to a new address. On-demand notifications (Notification::route('mail', $address)) are checked by address.
The link in the email body
Both providers want a visible link too. In any email template:
<x-unsubscribe::footer topic="newsletter" />
It renders "You're getting this email because you subscribed to Newsletter. Unsubscribe · Email preferences" in small grey type, in the email's language. For a required topic it shows only "Email preferences". Or write your own:
<a href="{{ unsubscribe_url('newsletter') }}">Unsubscribe</a> <a href="{{ unsubscribe_preferences_url() }}">Email preferences</a>
In a template you don't pass a recipient: the helpers write a placeholder that is swapped for the recipient's own signed link as the email is sent, in the HTML and the text part. They work in Markdown mail and in a notification's MailMessage too (->action('Email preferences', unsubscribe_preferences_url())). Outside an email, pass one: unsubscribe_url('newsletter', $user).
The pages
/unsubscribe/{recipient}/{topic} is the link in the header and the footer. Opened in a browser (a GET), it asks "Unsubscribe from Newsletter?" with one button, because link scanners and previews fetch URLs and mustn't unsubscribe anyone. A POST, from that button or from Gmail's and Yahoo's own "Unsubscribe" button, unsubscribes and says so, with "Subscribe again" and a link to the preferences.
/unsubscribe/{recipient} is the preferences page: every topic with a switch, required ones locked on, and "Unsubscribe from all". Saving answers in place. Turning one topic back on after "Unsubscribe from all" brings back only that one.
Both are signed links: no login, no session, no cookies. They speak the language the email was sent in (Mail::to($user)->locale('fr'), or a notifiable's preferredLocale()), and send Cache-Control: no-store, Referrer-Policy: no-referrer and X-Robots-Tag: noindex so the links stay private.
Who is who
A recipient is a notifiable model, an email address, or both. Addresses are stored only as a SHA-256 hash of the trimmed, lowercased address: the suppression list never holds a plain address, and the links carry the hash, never the address. A user's link also carries their model type and id; it's signed, so it can't be changed to someone else's.
Optional features in detail
A mailto: fallback
UNSUBSCRIBE_MAILTO=unsubscribe@yourapp.com
The header becomes List-Unsubscribe: <https://…>, <mailto:unsubscribe@yourapp.com?subject=unsubscribe%20newsletter>. Gmail and Yahoo use the https link; some other clients send that email instead. Process it however you read inbound mail:
Unsubscribe::unsubscribe($fromAddress, $topicFromSubject, source: 'mailto');
A global marketing switch
'global_switch' => 'marketing_emails',
When a notifiable model has that attribute and it's false, every topic that isn't required counts as unsubscribed, and the preferences page shows those topics as off. The package only reads the column: turning it back on is up to your app. It applies wherever the model is known: notifications to it, and links made for it. A Mailable sent to a bare address is checked by address only.
Classes you can't edit
'classes' => [ \Ruvelo\Inbox\Notifications\InboxDigest::class => 'digests', \Vendor\Package\Mail\Announcement::class => 'newsletter', ],
Subclasses match too.
With ruvelo/laravel-inbox
The two packages fit together and don't overlap:
- laravel-inbox is for people signed in to your app: in-app notifications, and preferences per notification type and channel ("Invoice paid: email off, in app on") on a page behind their login.
- laravel-unsubscribe is about email that goes out in bulk: per-topic unsubscribes that work from the email itself, without signing in, for users and for addresses with no account, plus the headers Gmail and Yahoo ask for.
Use the inbox's preferences for product notifications people manage while signed in, and topics here for newsletters, announcements and digests. One notification can use both: RespectsInboxPreferences decides its channels in via(), and Unsubscribable then skips the mail channel for anyone who unsubscribed from its topic.
The inbox's digest email is a subscribed message too. To give it one-click unsubscribe, add a topic and map the class:
'topics' => [ // … 'digests' => ['label' => 'Notification digests'], ], 'classes' => [ \Ruvelo\Inbox\Notifications\InboxDigest::class => 'digests', ],
And to link the two preferences pages, put Unsubscribe::preferencesUrl(auth()->user()) on the inbox's page (publish its views) or in your account settings.
For developers
PHP API
use Ruvelo\Unsubscribe\Unsubscribe; // $who: a notifiable model, an email address, Notification::route(...) or a Recipient Unsubscribe::isUnsubscribed($who, 'newsletter'); // counts "all" and the global switch Unsubscribe::unsubscribedFromAll($who); Unsubscribe::preferences($who); // ['newsletter' => true, 'product' => false, ...] Unsubscribe::unsubscribe($who, 'newsletter'); // false if they already were Unsubscribe::unsubscribe($who); // from all: Unsubscribe::ALL Unsubscribe::resubscribe($who, 'newsletter'); Unsubscribe::resubscribe($who); // undo "unsubscribe from all" Unsubscribe::update($who, ['newsletter' => true, 'product' => false]); // returns what changed Unsubscribe::url($who, 'newsletter'); // the signed one-click link Unsubscribe::preferencesUrl($who); Unsubscribe::headers($who, 'newsletter'); // ['List-Unsubscribe' => …, 'List-Unsubscribe-Post' => …] Unsubscribe::topics(['events' => ['label' => 'Events near you']]); Unsubscribe::allTopics(); // [key => Topic] Unsubscribe::topic('newsletter'); // Topic: key, label(), description(), required
Every write takes an optional source (one-click, link, preferences, import or api from the package), stored with the row and passed to the events.
Events
| Event | When |
|---|---|
Unsubscribed |
Someone unsubscribed from a topic, or from all (topic is *) |
Resubscribed |
Someone subscribed again, or undid "unsubscribe from all" |
Both in Ruvelo\Unsubscribe\Events, with recipient, topic and source, and only fired when something changed. Listen to them to sync your email service's suppression list.
Commands
php artisan unsubscribe:list # newest first
php artisan unsubscribe:list --topic=newsletter --limit=200
php artisan unsubscribe:list --email=maya@example.com
php artisan unsubscribe:import suppressions.csv # unsubscribe from all
php artisan unsubscribe:import suppressions.csv --topic=newsletter --topic=product
php artisan unsubscribe:import suppressions.csv --dry-run
The import reads one address per line, or the first column of a CSV, or SHA-256 hashes of lowercased addresses (the format of this package's own email_hash). Lines that are neither are counted and skipped, so a header row is fine.
Routes
GET /unsubscribe/{recipient}/{topic} |
Asks to confirm (topic may be all) |
POST /unsubscribe/{recipient}/{topic} |
Unsubscribes: the one-click endpoint |
GET /unsubscribe/{recipient} |
The preferences page |
POST /unsubscribe/{recipient} |
Saves it (action: save, all or resubscribe) |
All need a valid signature. Links are signed over the path and query only, so they keep working behind a proxy that changes the scheme or host; rotate APP_KEY with APP_PREVIOUS_KEYS so links in old emails stay valid.
Exceptions
UnknownTopic (a topic that isn't registered: sending such an email fails, so you notice), RequiredTopic (unsubscribing from a required topic) and InvalidTopic (a malformed key or definition), all extending Ruvelo\Unsubscribe\Exceptions\UnsubscribeException.
In your tests
Mail::fake() and Notification::fake() never reach the mailer, so the headers and the skipping don't run under them. Use the array mailer and look at what it sent, or test the decision directly:
use Ruvelo\Unsubscribe\Models\Suppression; use Ruvelo\Unsubscribe\Unsubscribe; Suppression::factory()->of($user)->topic('newsletter')->create(); Suppression::factory()->of('maya@example.com')->create(); // unsubscribed from all $this->assertTrue(Unsubscribe::isUnsubscribed($user, 'newsletter')); $this->post(Unsubscribe::url($user, 'product'))->assertOk();
Making it look like your app
The pages use the Ruvelo house style through CSS variables (--unsub-accent, --unsub-bg, …), follow the system's light or dark mode, and show your APP_NAME. Publish the views to change them, and the translations to reword them or add a language:
php artisan vendor:publish --tag=unsubscribe-views
php artisan vendor:publish --tag=unsubscribe-lang
Using an AI coding agent?
The package ships Laravel Boost guidelines in resources/boost/guidelines/core.blade.php. With Boost installed (composer require laravel/boost --dev), run php artisan boost:install and pick ruvelo/laravel-unsubscribe from the third-party packages (or php artisan boost:update --discover if Boost is already set up). Your agent then knows how to mark emails unsubscribable, link to the pages from templates and test it, and what not to do.
Requirements
| Laravel | PHP | Tested in CI |
|---|---|---|
| 12 (12.4.1+) | 8.3, 8.4, 8.5 | yes |
| 13 | 8.3, 8.4, 8.5 | yes |
- An https
APP_URLin production (links are upgraded to https by default; seeforce_https) - DKIM signing that covers the
List-Unsubscribeheaders, from your email service
Configuration reference
php artisan vendor:publish --tag=unsubscribe-config
| Key | Default | |
|---|---|---|
topics |
newsletter |
The topics: label, description, required |
default_topic |
newsletter |
The topic of an Unsubscribable class that doesn't name one |
classes |
[] |
Topics for Mailables and Notifications you can't edit, by class |
routes |
true |
Set to false to register the routes yourself (copy routes/web.php) |
path |
unsubscribe (UNSUBSCRIBE_PATH) |
URL prefix of the pages |
domain |
null |
Serve them on their own (sub)domain |
middleware |
[] |
Added to the pages; keep web and auth out |
mailto |
null (UNSUBSCRIBE_MAILTO) |
An address for a mailto: link in the header |
force_https |
true, except APP_ENV=local (UNSUBSCRIBE_FORCE_HTTPS) |
Make links https even if the app's URL says http |
channels |
['mail'] |
Notification channels an unsubscribe applies to |
global_switch |
null |
A notifiable attribute that, when false, means unsubscribed from all |
table_prefix |
unsubscribe_ |
The table: {prefix}suppressions |
run_migrations |
true |
Set to false if you publish the migration (--tag=unsubscribe-migrations) and run it yourself |
Upgrading
To 1.0
First release; nothing to upgrade from.
Contributing
Pull requests are welcome. Clone, composer install, then composer check runs code style (Pint), static analysis (PHPStan level 8) and the tests, exactly as CI does. See CONTRIBUTING.md and the changelog.
Credits
Built by François Bultez at Valtry, the website security scanner, and everyone who contributes.
License
MIT. See LICENSE.