Test the List-Unsubscribe header and one-click unsubscribe
Marketing and notification emails usually carry a List-Unsubscribe header, and many senders add a second header, List-Unsubscribe-Post, so that mail clients can unsubscribe the reader with one click. Nobody sees these headers in the message body, which is why they break unnoticed: a template change drops the header, the URL points at a staging host, or the endpoint answers a POST with an error. This guide shows a test that catches all three. It triggers a real email, reads the header through AssertInbox, calls the unsubscribe URL the way a mail client would, and then checks through your own API that the user is unsubscribed.
What the headers are
List-Unsubscribe is defined in RFC 2369. Its value is a list of angle-bracketed URLs, for example <https://app.example.com/unsub?t=abc>, <mailto:unsub@example.com>. List-Unsubscribe-Post is defined in RFC 8058 for one-click unsubscribe: when it has the value List-Unsubscribe=One-Click and the message is signed as that RFC describes, a mail client may send an HTTPS POST with the body List-Unsubscribe=One-Click to the URL, without showing a web page. Large mailbox providers publish sender requirements for bulk mail, and those change over time, so read the current ones for the providers your recipients use. This guide quotes no provider numbers or dates.
AssertInbox keeps a short list of headers with each message and returns them as the headers object, with lower-case names. The list is message-id, in-reply-to, list-unsubscribe, list-unsubscribe-post, auto-submitted, precedence and content-language. Other headers are not stored. A header that the message does not have is simply missing from the object.
Get an API key
Get one in a click at /start. One request creates a key and your private namespace, with no email address or card. The key is shown once, so keep it in your secret store and export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page, and the client files can replace the helper functions below.
The test file
Save this as list-unsubscribe.test.js and run it with node --test on Node 18 or newer. It assumes a staging app with three things you must adapt: an endpoint that subscribes an address to a newsletter (/api/subscribe), an endpoint that triggers a marketing email to it (/api/test/send-newsletter), and an endpoint that reports the subscription state (/api/subscribers). Replace these with your own routes. Only run it against an app you own.
const { test, after } = require("node:test");
const assert = require("node:assert");
const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
const APP = process.env.APP_URL || "http://localhost:3000";
const tags = [];
function newInbox() {
const tag = ("unsub-" + Date.now() + "-" + Math.random().toString(36).slice(2, 8)).toLowerCase();
tags.push(tag);
return { tag, email: NAMESPACE + "." + tag + "@assertinbox.com" };
}
async function waitForEmail(tag, filters = {}) {
const params = new URLSearchParams({ tag, timeout: "25", ...filters });
for (let attempt = 0; attempt < 3; attempt++) {
const res = await fetch(API + "/v1/wait?" + params, {
headers: { Authorization: "Bearer " + KEY },
});
if (res.status === 200) return res.json();
if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status);
}
throw new Error("No email arrived for tag " + tag);
}
async function appJson(path, options) {
const res = await fetch(APP + path, options);
assert.ok(res.ok, path + " returned " + res.status);
return res.json();
}
function unsubscribeTargets(header) {
return [...header.matchAll(/<([^>]+)>/g)].map((m) => m[1]);
}
after(async () => {
for (const tag of tags) {
await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), {
method: "DELETE",
headers: { Authorization: "Bearer " + KEY },
});
}
});
test("newsletter email supports one-click unsubscribe", { timeout: 120000 }, async () => {
const inbox = newInbox();
await appJson("/api/subscribe", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: inbox.email }),
});
await appJson("/api/test/send-newsletter", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: inbox.email }),
});
const mail = await waitForEmail(inbox.tag, { subject: "newsletter" });
const header = mail.headers["list-unsubscribe"];
assert.ok(header, "no List-Unsubscribe header");
const targets = unsubscribeTargets(header);
const url = targets.find((t) => t.startsWith("https://") || t.startsWith("http://localhost"));
assert.ok(url, "no https unsubscribe URL in: " + header);
assert.strictEqual(mail.headers["list-unsubscribe-post"], "List-Unsubscribe=One-Click");
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "List-Unsubscribe=One-Click",
});
assert.ok(res.status >= 200 && res.status < 300, "one-click POST returned " + res.status);
const state = await appJson("/api/subscribers?email=" + encodeURIComponent(inbox.email));
assert.strictEqual(state.subscribed, false);
});
test("a mailto target is optional but must be well formed when present", { timeout: 120000 }, async () => {
const inbox = newInbox();
await appJson("/api/subscribe", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: inbox.email }),
});
await appJson("/api/test/send-newsletter", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: inbox.email }),
});
const mail = await waitForEmail(inbox.tag, { subject: "newsletter" });
for (const target of unsubscribeTargets(mail.headers["list-unsubscribe"] || "")) {
if (target.startsWith("mailto:")) assert.match(target, /^mailto:[^@\s]+@[^@\s]+$/);
}
});
Run it with the key in the environment:
export ASSERTINBOX_KEY=ai_your_key_here
export ASSERTINBOX_NAMESPACE=your_namespace
APP_URL=https://staging.example.com node --test list-unsubscribe.test.js
The first test is the important one. It uses the subject filter so that a welcome email sent at sign-up is not mistaken for the newsletter, and it picks the HTTPS target out of the header by pattern instead of by position, because senders list the URL and the mailto address in either order.
Why POST, and why check the state afterwards
A mail client that supports one-click unsubscribe sends a POST, not a GET, and sends no cookies and no logged-in session. If your endpoint needs a session, or answers the POST with a redirect to a login page, real clients fail even though the link works in a browser. The test sends exactly that request. A 2xx answer is not enough on its own: the assertion on /api/subscribers confirms that the POST changed the data. Keep the final assertion in your own test, because only your app knows how it stores the preference.
What to assert, and what not to
- Assert that the header exists, that it has an HTTPS URL, and that the one-click header has the exact value from RFC 8058.
- Do not assert the whole URL. It usually contains a token that changes on every send. Assert its host and, if you like, that the path starts with your unsubscribe route.
- Do not call the URL with GET in the test. For some senders a GET shows a confirmation page, for others it already unsubscribes; use POST for the one-click check and a browser test for the page.
- Do not run the unsubscribe against a real subscriber list. Use an address created for the test, as above.
Transactional emails, such as a password reset, normally have no unsubscribe header. Add a negative test for those if your policy says so: wait for the email and assert that mail.headers["list-unsubscribe"] is undefined. For the opposite check, that no email is sent at all after an unsubscribe, see the guide on asserting that an email was not sent.
Troubleshooting
mail.headersis empty. The message has none of the seven stored headers. Open it in the inbox viewer and check with your mail provider's logs whether the header is added at send time or only for some message types.- The POST returns 403 or 405. The endpoint probably expects a CSRF token or a session, or only allows GET. One-click requests carry neither.
- The URL points at another host. The template builds links from a configuration value; staging is often left at its default.
- The wait times out. Check the
subjectfilter, which is a case-insensitive substring of the real subject. - HTTP 429. The key used its 2,000 requests for the day; see the limits page.
Next steps
For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.