Sub topic 6
Confirming consent with double opt-in
This chapter assumes you know how a sign-up form submits data to a server and how to read short Python and HTML snippets. It also assumes you have read the earlier chapters on what makes consent valid and how to design a consent request. Here we cover the step after the form: proving that the person who owns the address actually agreed. This is general education, not legal advice.
The problem double opt-in solves
A sign-up form proves only that someone typed an address and submitted it. It doesn't prove the address belongs to that person. Several things can go wrong:
- A visitor mistypes their own address, and a stranger starts receiving your newsletter.
- Someone enters another person's address on purpose, as a prank or as harassment.
- A bot fills in your form with addresses scraped from elsewhere.
In each case you hold no valid consent from the address owner. You may also be sending to a spam trap, which is an address that exists to catch senders with poor list practices. The result is complaints, bounces, and damage to your sending reputation.
Double opt-in adds a confirmation step. After the form is submitted, you send one email to the address with a link. The subscription becomes active only when the link is clicked. Clicking shows that someone with access to the mailbox took a second deliberate action.
Single versus double opt-in
| Aspect | Single opt-in | Double opt-in |
|---|---|---|
| Steps | Form submission activates the subscription | Form submission, then a click in a confirmation email |
| Proves the address owner agreed | No, only that someone submitted the address | Largely yes, because the mailbox owner clicked |
| Typos and fake addresses | Enter your list | Never get confirmed |
| Sign-up completion | Higher | Lower, because some people never click |
| Legal position | Acceptable in many regimes if consent is otherwise valid | Not required by most laws, but strongest evidence |
| Typical deliverability | More bounces and complaints | Cleaner list, fewer complaints |
No major regime in this tutorial (GDPR/ePrivacy, CAN-SPAM, CASL) states in its text that you must use double opt-in. The legal question is whether you can show valid consent. Double opt-in is the most common way to answer that question. In some countries, notably Germany, regulators and courts have in practice treated it as the expected standard for email marketing. Check what applies in the markets you send to.
The flow
The confirmation step sits between the form and the first marketing email.
Notice two details. The record exists in a pending state before the email is sent, so you keep the original consent evidence from the form. The subscriber receives marketing only after the final step.
Building the confirmation token
The link in the email must prove that it was issued by you for that address, and it must stop working after a while. A signed token does both without storing the token itself. The signature is an HMAC, a keyed hash. Only someone holding your secret key can produce a valid one.
import hashlib
import hmac
import os
import time
from urllib.parse import quote
SECRET_KEY = os.environ.get("CONSENT_TOKEN_KEY", "dev-only-secret").encode()
MAX_AGE_SECONDS = 48 * 60 * 60
# In production this is a database table. A dict keeps the example runnable.
subscriptions: dict[str, dict] = {}
def make_token(email: str, issued_at: int) -> str:
message = f"{email}|{issued_at}".encode()
signature = hmac.new(SECRET_KEY, message, hashlib.sha256).hexdigest()
return f"{issued_at}.{signature}"
def verify_token(email: str, token: str, now: int) -> bool:
try:
issued_text, signature = token.split(".", 1)
issued_at = int(issued_text)
except ValueError:
return False
if now - issued_at > MAX_AGE_SECONDS:
return False
message = f"{email}|{issued_at}".encode()
expected = hmac.new(SECRET_KEY, message, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature, expected)
def request_subscription(email: str, now: int) -> str:
email = email.strip().lower()
subscriptions[email] = {"status": "pending", "collected_at": now, "confirmed_at": None}
token = make_token(email, now)
return f"https://example.com/confirm?email={quote(email)}&token={token}"
def confirm(email: str, token: str, now: int) -> str:
email = email.strip().lower()
if not verify_token(email, token, now):
return "invalid_or_expired"
record = subscriptions.get(email)
if record is None:
return "unknown"
if record["status"] == "confirmed":
return "already_confirmed"
record["status"] = "confirmed"
record["confirmed_at"] = now
return "confirmed"
if __name__ == "__main__":
now = int(time.time())
link = request_subscription("[email protected]", now)
token = link.split("token=")[1]
print(confirm("[email protected]", token, now + 60))
print(confirm("[email protected]", token, now + 120))
print(confirm("[email protected]", token + "x", now + 120))
link2 = request_subscription("[email protected]", now)
token2 = link2.split("token=")[1]
print(confirm("[email protected]", token2, now + MAX_AGE_SECONDS + 1))Running it prints confirmed, already_confirmed, invalid_or_expired, and invalid_or_expired.
Four design choices matter here:
- Normalize the address. The code strips whitespace and lowercases before signing and looking up. Otherwise
[email protected]and[email protected]produce different tokens. - Compare signatures in constant time.
hmac.compare_digestavoids leaking information through timing differences. - Load the key from the environment. The default value is for local experiments only. A real key must be long, random, and never committed to source control.
- Check state as well as signature. A signed token alone is not one-time. The
already_confirmedbranch makes repeated clicks harmless. If you also need to invalidate tokens after a resend, store a random nonce in the record and include it in the signed message.
Writing the confirmation email
The confirmation email is a transactional message. It should do one job: ask the recipient to confirm.
- State what they signed up for, for example "the monthly Example Co. product newsletter", and where they signed up.
- Use a single clear button or link, plus a plain-text fallback URL.
- Say what happens if they ignore it: nothing, and you will not email them again.
- Leave out promotions, product offers, and unrelated links. Marketing content in a confirmation email undermines the argument that you sent it without consent.
Edge cases and common errors
Security scanners click links for you
Corporate mail gateways and some mailbox providers fetch every link in an incoming email to check it for malware. If your confirmation link activates the subscription on a plain GET request, a scanner can confirm an address that no human ever saw. This produces false confirmations that look like valid evidence but aren't.
The standard defense is a two-stage link:
- The
GETrequest to the link shows a page with a "Confirm my subscription" button. - The button sends a
POSTrequest, which does the actual state change.
Scanners rarely submit forms, so the human click remains the evidence. You can also log the user agent and timing of each confirmation and flag clicks that happen within a second or two of delivery.
Resubmission and already-subscribed addresses
If someone submits the form again while pending, issue a fresh link and keep the earlier collection timestamp or record both. If the address is already confirmed, don't send a new confirmation email. Show the same neutral message in both cases, such as "Check your inbox", so the form can't be used to find out who is on your list. Revealing list membership is a privacy leak.
Expired and unconfirmed sign-ups
An unconfirmed record is not consent. Do not send any marketing to it, and do not move it to your main list. After the token expires, delete the pending record, or keep only a minimal suppression entry if you need to avoid re-sending confirmation requests to an address that complained. Keeping unconfirmed addresses indefinitely conflicts with the data minimization principle.
Confirmation does not fix a bad request
Double opt-in verifies the address owner and records a second action. It doesn't repair a consent request that was invalid to begin with. If the form used a pre-ticked box or bundled several purposes, the confirmed address still rests on defective consent. Consent must still be specific and unbundled. The confirmation email should repeat the specific purpose, not widen it.
Imported contacts
You can't launch double opt-in for people who never filled in your form by sending them a "please confirm" email as a way to create consent. If you have no valid basis to contact them at all, that email can itself be an unsolicited message. A later chapter on re-permission covers when asking is acceptable.
Recording the confirmation
Double opt-in earns its value when you store the evidence. Extend the consent record from the form step so it shows the full path. The confirmed_at timestamp is the new field.
{
"email": "[email protected]",
"purpose": "monthly_newsletter",
"consent_text_version": "2026-11-v3",
"consent_text": "Email me the monthly Example Co. product newsletter. You can unsubscribe at any time.",
"source_url": "https://example.com/newsletter",
"method": "unticked_checkbox",
"collected_at": "2026-11-26T13:56:57Z",
"confirmed_at": "2026-11-26T14:02:10Z",
"withdrawn_at": null
}Useful additions for a confirmation event are the confirmation IP address and user agent, the ID of the confirmation email, and the token issue time. Treat IP addresses as personal data too, and set a retention period for them. Keep the collected_at and confirmed_at values separate, because the gap between them shows a real person took time to respond.
When to choose which
Use double opt-in when you send to the EU or UK, when you operate in countries where it is the expected practice, when your form is public and attracts bots, or when your sending reputation is fragile. Single opt-in can be reasonable when the address is verified another way, for example during checkout with a logged-in account whose email was already verified. Even then, keep the full consent record. If you choose single opt-in, you take on more of the work of showing that the address owner agreed.
The cost of double opt-in is a drop in completed sign-ups. You can reduce it by telling people on the success page to check their inbox, sending from a recognizable name, and delivering the confirmation email within seconds. Measure the confirmation rate. A very low rate suggests that emails land in spam or that the form attracts bad addresses.
Exercise
Your confirmation link activates the subscription on a plain GET request. A customer reports that she never signed up, yet your records show a confirmation four seconds after the email was delivered to her company address. What is the likely cause, and how do you fix the flow?
Show answer
The company's mail security scanner probably fetched the link automatically, so the GET request confirmed the address without a human action. Change the link so the GET request shows a page with a confirm button, and make the button send a POST request that marks the subscription confirmed. Treat the existing confirmation as unreliable evidence: do not rely on it, and ask the customer to re-confirm if she wants the newsletter.
Exercise
A visitor submits your form but never clicks the confirmation link, and 48 hours later the token expires. What should happen to the pending record, and may you add the address to your marketing list?
Show answer
You may not add the address to the marketing list, because an unconfirmed record is not valid consent. Delete the pending record after expiry, or keep only a minimal suppression entry if you need it to stop repeated confirmation requests. Do not keep the address indefinitely.