Sub topic 10
Making unsubscribing simple and reliable
This chapter assumes you have the subscriber lifecycle (pending, confirmed, unsubscribed) and the signed token helpers (make_token, verify_token) from earlier chapters. It also assumes you know the difference between a GET and a POST request.
Unsubscribing is the last point where a sender can keep or lose a reader's trust. A reader who can't leave easily will click "Report spam" instead. A complaint costs you more than an unsubscribe does, because mailbox providers count complaints against your sender reputation. The goal is an unsubscribe flow that finishes in one step, can't be triggered by accident, and can't silently fail.
What "simple" and "reliable" mean
Simple means the reader does as little as possible:
- The link is easy to find in every message, usually in the footer, in readable text.
- It works without logging in or entering a password.
- It does not ask the reader to retype their email address.
- It does not ask for a reason before it acts. An optional question after the unsubscribe is fine.
Reliable means the system does what the reader asked and keeps doing it:
- The change is saved before the reader sees the success message.
- The request can be repeated safely.
- Every later send checks the result.
- The link keeps working long after the email was sent.
Many jurisdictions also set legal limits on how long you may take to honor a request. The legal chapter covers those. Treat "immediately" as the engineering target, not the deadline.
The request flow
An unsubscribe link in an email can be opened by three kinds of client: a person in a browser, a security scanner that fetches every link, and a mailbox provider sending a one-click POST. Your endpoint has to handle all three correctly.
The GET branch changes nothing. This is the same rule you applied to confirmation links: scanners follow links, and a scanner that unsubscribes your readers would quietly shrink your list. The POST branch does the work. Mail clients that support one-click unsubscribe send a POST directly to the HTTPS address in the List-Unsubscribe header, so the same endpoint serves both the button on your page and those automated requests. The header itself is covered in a later chapter.
Tokens for unsubscribe links
Use the same signed token scheme as before, with the purpose set to "unsubscribe". The purpose check means a leaked confirmation token cannot unsubscribe anyone, and an unsubscribe token cannot confirm anyone.
Choose the lifetime deliberately. A confirmation link can expire in 48 hours because the sign-up is fresh. An unsubscribe link sits in an inbox for months or years, and readers do open old emails to leave. An expired unsubscribe link is a bad failure, because the reader has no easy way out except the spam button. Use a long lifetime, for example five years, and give the failure page a working fallback (see the table below).
FIVE_YEARS = 5 * 365 * 24 * 3600
def unsubscribe_link(email: str) -> str:
token = make_token(email, "unsubscribe", ttl_seconds=FIVE_YEARS)
return f"https://example.com/unsubscribe/{token}"The handler
The code below uses the subscribers and consent_events tables from the lifecycle and audit-trail chapters. It assumes a small database wrapper named db with transaction(), query_one() and execute() methods, and the render() helper used in the confirmation handlers. Adapt these names to your framework.
def show_unsubscribe_page(token: str):
"""Handle GET: display a button; change nothing."""
email = verify_token(token, "unsubscribe")
if email is None:
return render("unsubscribe_link_problem.html")
return render("unsubscribe_button.html", token=token)
def unsubscribe(db, token: str, source: str, ip: str, user_agent: str):
"""Handle POST: unsubscribe the address. Safe to call more than once.
source is "web_page" for the button and "one_click_header" for
requests sent by a mail client.
"""
email = verify_token(token, "unsubscribe")
if email is None:
return render("unsubscribe_link_problem.html")
with db.transaction():
row = db.query_one(
"UPDATE subscribers SET status = 'unsubscribed' "
"WHERE email = %s AND status <> 'unsubscribed' "
"RETURNING id",
(email,),
)
if row is not None:
db.execute(
"INSERT INTO consent_events "
"(subscriber_id, event_type, source, ip_address, user_agent) "
"VALUES (%s, 'unsubscribe', %s, %s, %s)",
(row[0], source, ip, user_agent),
)
return render("unsubscribed.html")Three details matter here.
- The status change and the audit record share one transaction. If the event insert fails, the status change rolls back and the reader sees an error instead of a false success.
status <> 'unsubscribed'makes the call idempotent. A double click, a retried one-click request, or a second POST from a mail client updates zero rows and writes no duplicate event. The reader still sees the success page.- Pending subscribers are covered. Someone who signed up but never confirmed can still unsubscribe, and the status becomes
unsubscribedrather than stayingpendingand eligible for a reminder.
The handler changes the status only. It does not yet put the address on a suppression list. The next chapter covers that list and why every send must check it.
Reliability gaps to close
| Failure | What goes wrong | Fix |
|---|---|---|
| Unsubscribe applied by a nightly batch job | Readers get more email after unsubscribing, then complain | Update the status in the request itself. Every send reads that status |
| GET changes state | Scanners unsubscribe real readers | Show a button on GET and change state on POST only |
| Link expires | Reader can't leave and reports spam | Use a long token lifetime and a fallback on the failure page |
| Message already queued | Email goes out after the click | Check status at send time, not only when the campaign is built |
| Reader has several addresses | Mail forwarded to a second address keeps arriving | Explain on the success page which address was removed. Offer a contact route |
| Handler returns success on error | Reader believes they left but didn't | Return the success page only after the transaction commits |
The failure page deserves care. If the token is invalid or damaged, show a plain message and a way to ask for help, such as a contact address or a form that sends a new link to the address on file. Do not build a form that unsubscribes whatever email address someone types, because anyone could then remove other people from your list. Sending a fresh signed link to that address avoids the problem.
The page after the click
Keep the success page short. Say which address was unsubscribed and when the change takes effect. If you have a preference centre, a secondary link such as "Changed your mind? Manage what you receive" is acceptable, but it must not block or delay the unsubscribe. The decision to leave is already done when the page loads. Offering alternatives before the click, such as a "fewer emails" option on the confirmation page, is a design choice for the preference centre chapter, and it must never replace the plain unsubscribe button.
A short optional question such as "Why did you leave?" can give useful data. Keep it optional, and make sure the unsubscribe is stored whether or not it is answered.
Testing the flow
Test these cases against a staging copy before shipping:
- A GET request leaves the subscriber's status unchanged.
- A POST with a valid token sets the status to
unsubscribedand writes oneconsent_eventsrow. - A second identical POST writes no second row and still returns the success page.
- A confirmation token sent to the unsubscribe endpoint is rejected.
- A pending subscriber can unsubscribe.
- A token older than the confirmation lifetime but younger than the unsubscribe lifetime still works.
Exercise
A security scanner opens every link in a newsletter, including the unsubscribe link, using a GET request. Your handler unsubscribes on GET. What happens, and how do you change the design so that one-click unsubscribe from a mail client still works?
Show answer
The scanner unsubscribes readers who never asked to leave, and your list shrinks without anyone noticing. Change the GET handler to show a page with an Unsubscribe button that changes nothing, and perform the status update only on POST. Mail clients that support one-click unsubscribe send a POST to the HTTPS address in the List-Unsubscribe header, so the same POST handler serves both the button and those requests.
Exercise
Why does the handler update with WHERE status <> 'unsubscribed' and write the consent event only when a row came back?
Show answer
It makes the request idempotent. A repeated or retried POST changes nothing and adds no duplicate audit event, but the reader still sees a success page. The audit trail then holds one unsubscribe event for each real change in status.