Honor unsubscribes and complaints

Honor unsubscribes and complaints

Stop writing to people who opt out or report spam, with Mailset’s link or your own.

On this page
  1. Let Mailset handle it
  2. Where the placeholder goes
  3. When someone unsubscribes
  4. Keep your own list in step
  5. Or run your own
  6. Make the link
  7. Host the endpoint
  8. Check your list before each send
  9. Complaints
  10. Watch out

Anyone who gets promotional email from you must be able to stop it in one click, and you must stop. Mailbox providers check both. Mailset can make the unsubscribe link and honor it for you, or you can run your own.

This is about promotional email: newsletters, offers, announcements. A sign-in code or a receipt is transactional, needs no unsubscribe, and can't carry one.

Let Mailset handle it

Send with mode: 'promotional' and no List-Unsubscribe header, and write {{mailset_unsubscribe}} where the link belongs.

{{mailset_unsubscribe}} is a placeholder that Mailset fills in for each message. You never generate the link. Mailset puts in a signed, one-click unsubscribe URL that is unique to that recipient and that message, and adds the matching List-Unsubscribe and List-Unsubscribe-Post headers itself.

import { Mailset } from 'mailset';

// Reads MAILSET_KEY from the environment.
const mailset = new Mailset();

const text = [
	'Three new things this month.',
	'',
	'Leave this list: {{mailset_unsubscribe}}',
].join('\n');

const html = [
	'<p>Three new things this month.</p>',
	'<a href="{{mailset_unsubscribe}}">Leave this list</a>',
].join('\n');

const sent = await mailset.send({
	from: 'Acme News <moc.elpmaxe.swen@swen>',
	to: 'gro.elpmaxe@ana',
	subject: 'What shipped in March',
	text,
	html,
	mode: 'promotional',
});

console.log(sent.id, sent.skipped);
from mailset import Mailset

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

text = (
    "Three new things this month.\n"
    "\n"
    "Leave this list: {{mailset_unsubscribe}}"
)
html = (
    "<p>Three new things this month.</p>\n"
    '<a href="{{mailset_unsubscribe}}">'
    "Leave this list</a>"
)
import (
	"context"
	"fmt"
	"log"
	"strings"

	mailset "mailset.app/go"
)

client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

text := strings.Join([]string{
	"Three new things this month.",
	"",
	"Leave this list: {{mailset_unsubscribe}}",
}, "\n")
require 'mailset'

mailset = Mailset::Client.new

text = <<~TEXT
  Three new things this month.

  Leave this list: {{mailset_unsubscribe}}
TEXT

html = <<~HTML
  <p>Three new things this month.</p>
  <a href="{{mailset_unsubscribe}}">Leave this list</a>
HTML

sent = mailset.send_email(
  from: 'Acme News <moc.elpmaxe.swen@swen>',
  to: 'gro.elpmaxe@ana',
  subject: 'What shipped in March',
  text: text,
  html: html,
  mode: 'promotional'
)

p sent.id, sent.skipped
<?php

require 'vendor/autoload.php';

// Reads MAILSET_KEY from the environment.
$mailset = new Mailset\Client();

$text = <<<'TEXT'
    Three new things this month.

    Leave this list: {{mailset_unsubscribe}}
    TEXT;

$html = <<<'HTML'
    <p>Three new things this month.</p>
    <a href="{{mailset_unsubscribe}}">Leave this list</a>
    HTML;
import app.mailset.Mailset;
import app.mailset.Message;
import app.mailset.Sent;

// Reads MAILSET_KEY from the environment.
Mailset mailset = Mailset.fromEnv();

String text = String.join("\n",
        "Three new things this month.",
        "",
        "Leave this list: {{mailset_unsubscribe}}");

String html = String.join("\n",
        "<p>Three new things this month.</p>",
        "<a href=\"{{mailset_unsubscribe}}\">"
                + "Leave this list</a>");

Sent sent = mailset.send(Message.builder()
        .from("Acme News <moc.elpmaxe.swen@swen>")
        .to("gro.elpmaxe@ana")
        .subject("What shipped in March")
        .text(text)
        .html(html)
        .mode(Message.Mode.PROMOTIONAL)
        .build());

System.out.println(sent.id() + " " + sent.skipped());
use mailset::{Client, Message, Mode};

// Reads MAILSET_KEY from the environment.
let mailset = Client::from_env()?;

let text = [
    "Three new things this month.",
    "",
    "Leave this list: {{mailset_unsubscribe}}",
]
.join("\n");

let html = [
    "<p>Three new things this month.</p>",
    "<a href=\"{{mailset_unsubscribe}}\">Leave</a>",
]
.join("\n");
What Ana receives
Headers Mailset adds
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
Text part
Three new things this month.

Leave this list: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
HTML part

Three new things this month.

Leave this list

A sample link. Mailset makes a new one for every message.

The link opens a page with one Unsubscribe button. The headers let a mail app's own unsubscribe button do the same in one click. The link never expires.

Where the placeholder goes

It works in text and in html, as often as you write it.

  • In text, it becomes the URL.
  • In html, inside a tag, as in href="{{mailset_unsubscribe}}", it becomes the URL, and the link keeps your words.
  • In the running text of html, it becomes a link that shows the URL.
  • Leave it out of a part, and that part gets a short Unsubscribe line at its end.
What Ana receives without the placeholder
Text part
Three new things this month.

Unsubscribe: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
HTML part

Three new things this month.

Unsubscribe

Mailset adds the last line of each part. The headers are the same.

When someone unsubscribes

  • Promotional email goes to one address in to, with no cc or bcc, so the link is that person's.
  • When they use it, Mailset records the opt-out for the mailbox that sent the message, or for its sending domain when a domain key sent it, and posts an unsubscribed event to your webhook.
  • From then on, promotional email from that mailbox to that address is skipped. With a domain key, promotional email from any address on that domain is skipped: someone who leaves moc.elpmaxe@swen's newsletter gets no moc.elpmaxe@sreffo promotions either. The receipt names them in skipped with reason: "unsubscribed", and nothing goes out.
  • Transactional email still reaches them. Someone who left your newsletter still gets their sign-in code.

An opt-out belongs to one sending mailbox, or with a domain key to one sending domain. It never carries over to another mailbox, another domain (news.example.com and example.com are two), another product or another org.

Keep your own list in step

for (const event of events) {
	if (event.type === 'unsubscribed') {
		await stopNewsletter(event.recipient);
	}
	if (event.type === 'complained') {
		await stopAllMarketing(event.recipient);
	}
}
for event in events:
    if event["type"] == "unsubscribed":
        stop_newsletter(event["recipient"])
    if event["type"] == "complained":
        stop_all_marketing(event["recipient"])
import (
	"io"
	"log"
	"net/http"
	"os"

	mailset "mailset.app/go"
)

for _, event := range events {
	switch event.Type {
	case mailset.EventUnsubscribed:
		stopNewsletter(event.Recipient)
	case mailset.EventComplained:
		stopAllMarketing(event.Recipient)
	}
}
events.each do |event|
  case event.type
  when 'unsubscribed'
    Marketing.stop_newsletter(event.recipient)
  when 'complained'
    Marketing.stop_all(event.recipient)
  end
end
foreach ($events as $event) {
    if ($event instanceof UnsubscribedEvent) {
        stopNewsletter($event->recipient);
    }
    if ($event instanceof ComplainedEvent) {
        stopAllMarketing($event->recipient);
    }
}
for (MailEvent event : events) {
    if (event instanceof MailEvent.Unsubscribed u) {
        stopNewsletter(u.recipient());
    }
    if (event instanceof MailEvent.Complained c) {
        stopAllMarketing(c.recipient());
    }
}
for event in events {
    match event {
        Event::Unsubscribed(left) => {
            stop_newsletter(&left.recipient).await
        }
        Event::Complained(spam) => {
            stop_all_marketing(&spam.recipient).await
        }
        _ => {}
    }
}

mailset unsubscribes list moc.elpmaxe.swen@swen shows who opted out, and an app key can ask the same over HTTP with unsubscribes.list. When someone asks you for your email again, unsubscribes.remove lets it through. With a domain key, both take the domain's name where they took a mailbox: mailset unsubscribes list news.example.com, mailset unsubscribes remove news.example.com --address gro.elpmaxe@ana.

Or run your own

Pass your own List-Unsubscribe in headers and Mailset leaves the message alone: it fills in no placeholder and adds no line. You make the link, host the endpoint and keep the list.

const url = `https://example.com/unsubscribe/${token}`;

const text = [
	'Three new things this month.',
	'',
	`Leave this list: ${url}`,
].join('\n');

const html = [
	'<p>Three new things this month.</p>',
	`<a href="${url}">Leave this list</a>`,
].join('\n');

await mailset.send({
	from: 'Acme News <moc.elpmaxe.swen@swen>',
	to: 'gro.elpmaxe@ana',
	subject: 'What shipped in March',
	text,
	html,
	headers: {
		'List-Unsubscribe': `<${url}>`,
		'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
	},
	mode: 'promotional',
});
url = f"https://example.com/unsubscribe/{token}"

text = (
    "Three new things this month.\n"
    "\n"
    f"Leave this list: {url}"
)
html = (
    "<p>Three new things this month.</p>\n"
    f'<a href="{url}">Leave this list</a>'
)
headers = {
    "List-Unsubscribe": f"<{url}>",
    "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
}

mailset.send(
    {
        "from": "Acme News <moc.elpmaxe.swen@swen>",
        "to": "gro.elpmaxe@ana",
        "subject": "What shipped in March",
        "text": text,
        "html": html,
        "headers": headers,
        "mode": "promotional",
    }
)
import (
	"context"
	"log"
	"strings"

	mailset "mailset.app/go"
)

url := "https://example.com/unsubscribe/" + token

text := strings.Join([]string{
	"Three new things this month.",
	"",
	"Leave this list: " + url,
}, "\n")

html := strings.Join([]string{
	"<p>Three new things this month.</p>",
	`<a href="` + url + `">Leave this list</a>`,
}, "\n")
url = "https://example.com/unsubscribe/#{token}"
one_click = 'List-Unsubscribe=One-Click'

text = <<~TEXT
  Three new things this month.

  Leave this list: #{url}
TEXT

html = <<~HTML
  <p>Three new things this month.</p>
  <a href="#{url}">Leave this list</a>
HTML

mailset.send_email(
  from: 'Acme News <moc.elpmaxe.swen@swen>',
  to: 'gro.elpmaxe@ana',
  subject: 'What shipped in March',
  text: text,
  html: html,
  headers: {
    'List-Unsubscribe' => "<#{url}>",
    'List-Unsubscribe-Post' => one_click
  },
  mode: 'promotional'
)
$url = "https://example.com/unsubscribe/{$token}";
$oneClick = 'List-Unsubscribe=One-Click';

$text = <<<TEXT
    Three new things this month.

    Leave this list: {$url}
    TEXT;

$html = <<<HTML
    <p>Three new things this month.</p>
    <a href="{$url}">Leave this list</a>
    HTML;

$mailset->send([
    'from' => 'Acme News <moc.elpmaxe.swen@swen>',
    'to' => 'gro.elpmaxe@ana',
    'subject' => 'What shipped in March',
    'text' => $text,
    'html' => $html,
    'headers' => [
        'List-Unsubscribe' => "<{$url}>",
        'List-Unsubscribe-Post' => $oneClick,
    ],
    'mode' => 'promotional',
]);
String url = "https://example.com/unsubscribe/"
        + token;

String text = String.join("\n",
        "Three new things this month.",
        "",
        "Leave this list: " + url);

String html = String.join("\n",
        "<p>Three new things this month.</p>",
        "<a href=\"" + url + "\">Leave this list</a>");

mailset.send(Message.builder()
        .from("Acme News <moc.elpmaxe.swen@swen>")
        .to("gro.elpmaxe@ana")
        .subject("What shipped in March")
        .text(text)
        .html(html)
        .header("List-Unsubscribe", "<" + url + ">")
        .header("List-Unsubscribe-Post",
                "List-Unsubscribe=One-Click")
        .mode(Message.Mode.PROMOTIONAL)
        .build());
let url = format!(
    "https://example.com/unsubscribe/{token}"
);

let text = [
    "Three new things this month.",
    "",
    &format!("Leave this list: {url}"),
]
.join("\n");

let html = [
    "<p>Three new things this month.</p>",
    &format!("<a href=\"{url}\">Leave this list</a>"),
]
.join("\n");

Mailset checks the form: an https URL, the one-click header, and the same URL in the text and in the HTML. Your endpoint has to answer a POST with no cookies and no login, since the mailbox provider sends it, and opt the person out without asking anything more. A GET should show a page with one button, never unsubscribe by itself: mail scanners follow links.

// A random token, kept with the address and the list:
// the URL says nothing about the person.
const token = crypto.randomUUID();
await saveToken(token, { address, list: 'news' });
const url = `https://example.com/unsubscribe/${token}`;

const text = [
	'Three new things this month.',
	'',
	`Leave this list: ${url}`,
].join('\n');

const html = [
	'<p>Three new things this month.</p>',
	`<a href="${url}">Leave this list</a>`,
].join('\n');
# A random token, kept with the address and the list:
# the URL says nothing about the person.
token = secrets.token_urlsafe(16)
save_token(token, {"address": address, "list": "news"})
url = f"https://example.com/unsubscribe/{token}"

text = (
    "Three new things this month.\n"
    "\n"
    f"Leave this list: {url}"
)
html = (
    "<p>Three new things this month.</p>\n"
    f'<a href="{url}">Leave this list</a>'
)
headers = {
    "List-Unsubscribe": f"<{url}>",
    "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
}
import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"log"
	"strings"

	mailset "mailset.app/go"
)

// A random token, kept with the address and the list:
// the URL says nothing about the person.
random := make([]byte, 16)
if _, err := rand.Read(random); err != nil {
	log.Fatal(err)
}
token := hex.EncodeToString(random)
saveToken(token, entry{address: address, list: "news"})
url := "https://example.com/unsubscribe/" + token
# A random token, kept with the address and the list:
# the URL says nothing about the person.
token = SecureRandom.uuid
save_token(token, address: address, list: 'news')
url = "https://example.com/unsubscribe/#{token}"
one_click = 'List-Unsubscribe=One-Click'

text = <<~TEXT
  Three new things this month.

  Leave this list: #{url}
TEXT

html = <<~HTML
  <p>Three new things this month.</p>
  <a href="#{url}">Leave this list</a>
HTML
// A random token, kept with the address and the list:
// the URL says nothing about the person.
$token = bin2hex(random_bytes(16));
saveToken($token, $address, 'news');
$url = "https://example.com/unsubscribe/{$token}";
$oneClick = 'List-Unsubscribe=One-Click';

$text = <<<TEXT
    Three new things this month.

    Leave this list: {$url}
    TEXT;

$html = <<<HTML
    <p>Three new things this month.</p>
    <a href="{$url}">Leave this list</a>
    HTML;
// A random token, kept with the address and the
// list: the URL says nothing about the person.
String token = UUID.randomUUID().toString();
saveToken(token, new Entry(address, "news"));
String url = "https://example.com/unsubscribe/"
        + token;

String text = String.join("\n",
        "Three new things this month.",
        "",
        "Leave this list: " + url);

String html = String.join("\n",
        "<p>Three new things this month.</p>",
        "<a href=\"" + url + "\">Leave this list</a>");

mailset.send(Message.builder()
        .from("Acme News <moc.elpmaxe.swen@swen>")
        .to(address)
        .subject("What shipped in March")
        .text(text)
        .html(html)
        .header("List-Unsubscribe", "<" + url + ">")
        .header("List-Unsubscribe-Post",
                "List-Unsubscribe=One-Click")
        .mode(Message.Mode.PROMOTIONAL)
        .build());
// A random token, kept with the address and the list:
// the URL says nothing about the person.
let token = random_token();
save_token(&token, address, "news").await;
let url = format!(
    "https://example.com/unsubscribe/{token}"
);

let text = [
    "Three new things this month.",
    "",
    &format!("Leave this list: {url}"),
]
.join("\n");

let html = [
    "<p>Three new things this month.</p>",
    &format!("<a href=\"{url}\">Leave this list</a>"),
]
.join("\n");

Host the endpoint

const tokenOf = (request: Request) =>
	new URL(request.url).pathname.split('/').pop() ?? '';

const page = (body: string, status = 200) =>
	new Response(`<!doctype html><body>${body}</body>`, {
		status,
		headers: { 'content-type': 'text/html' },
	});

// The link in the message: a page, never the opt-out.
export async function GET(request: Request) {
	if (!(await findToken(tokenOf(request))))
		return page('This link has expired.', 400);
	return page(
		'<form method="post">' +
			'<input type="hidden" name="List-Unsubscribe"' +
			' value="One-Click">' +
			'<button>Unsubscribe</button></form>',
	);
}
def page(body: str, status: int = 200) -> HTMLResponse:
    html = f"<!doctype html><body>{body}</body>"
    return HTMLResponse(html, status_code=status)


FORM = (
    '<form method="post">'
    '<input type="hidden" name="List-Unsubscribe"'
    ' value="One-Click">'
    "<button>Unsubscribe</button></form>"
)


# The link in the message: a page, never the opt-out.
@app.get("/unsubscribe/{token}")
async def show(token: str) -> HTMLResponse:
    if not find_token(token):
        return page("This link has expired.", 400)
    return page(FORM)
import (
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"
)

func page(w http.ResponseWriter, html string, code int) {
	w.Header().Set("Content-Type", "text/html")
	w.WriteHeader(code)
	fmt.Fprint(w, "<!doctype html><body>"+html+"</body>")
}

// The link in the message: a page, never the opt-out.
func show(w http.ResponseWriter, r *http.Request) {
	if _, ok := findToken(r.PathValue("token")); !ok {
		page(w, "This link has expired.", 400)
class UnsubscribesController < ApplicationController
  # A mail provider's POST carries no CSRF token.
  skip_forgery_protection

  # The link in the message: a page, never the opt-out.
  def show
    unless OptOuts.find_token(params[:token])
      return page('This link has expired.', :bad_request)
    end

    page('<form method="post">' \
         '<input type="hidden" name="List-Unsubscribe"' \
         ' value="One-Click">' \
         '<button>Unsubscribe</button></form>')
  end
// The link in the message: a page, never the opt-out.
Route::get('/unsubscribe/{token}', function (
    string $token,
) {
    if (findToken($token) === null) {
        return response('This link has expired.', 400);
    }

    return response(
        '<form method="post">'
        . '<input type="hidden" name="List-Unsubscribe"'
        . ' value="One-Click">'
        . '<button>Unsubscribe</button></form>',
    );
});
static ResponseEntity<String> page(
        int status, String body) {
    return ResponseEntity.status(status)
            .contentType(MediaType.TEXT_HTML)
            .body("<!doctype html><body>"
                    + body + "</body>");
}

// The link in the message: a page, never the opt-out.
@GetMapping("/{token}")
public ResponseEntity<String> show(
        @PathVariable String token) {
    if (findToken(token) == null)
        return page(400, "This link has expired.");
    return page(200, "<form method=\"post\">"
            + "<input type=\"hidden\""
            + " name=\"List-Unsubscribe\""
            + " value=\"One-Click\">"
            + "<button>Unsubscribe</button></form>");
}
type Page = (StatusCode, Html<String>);

fn page(status: StatusCode, body: &str) -> Page {
    let html =
        format!("<!doctype html><body>{body}</body>");
    (status, Html(html))
}

const FORM: &str = concat!(
    r#"<form method="post">"#,
    r#"<input type="hidden" name="List-Unsubscribe""#,
    r#" value="One-Click">"#,
    "<button>Unsubscribe</button></form>",
);

// The link in the message: a page, never the opt-out.
async fn show(
    State(store): State<Store>,

Check your list before each send

for (const address of await subscribers('news')) {
	if (await isOptedOut(address, 'news')) continue;
	await mailset.send({
		...newsletter,
		to: address,
		mode: 'promotional',
	});
}
for address in subscribers("news"):
    if is_opted_out(address, "news"):
        continue
    mailset.send(
        {
            "from": "Acme News <moc.elpmaxe.swen@swen>",
            "to": address,
            "subject": "What shipped in March",
            "text": "Three new things this month.",
            "mode": "promotional",
        }
    )
import (
	"context"
	"log"

	mailset "mailset.app/go"
)

for _, address := range subscribers("news") {
	if isOptedOut(address, "news") {
		continue
	}
	message := newsletter
	message.To = []string{address}
	message.Mode = mailset.ModePromotional
	if _, err := client.Send(ctx, message); err != nil {
		log.Println(address, err)
	}
}
subscribers('news').each do |address|
  next if opted_out?(address, 'news')

  mailset.send_email(
    **newsletter, to: address, mode: 'promotional'
  )
end
foreach (subscribers('news') as $address) {
    if (isOptedOut($address, 'news')) {
        continue;
    }
    $mailset->send([
        ...$newsletter,
        'to' => $address,
        'mode' => 'promotional',
    ]);
}
for (String address : subscribers("news")) {
    if (isOptedOut(address, "news")) continue;
    mailset.send(newsletter()
            .to(address)
            .mode(Message.Mode.PROMOTIONAL)
            .build());
}
for address in subscribers("news").await {
    if is_opted_out(&address, "news").await {
        continue;
    }
    let message = newsletter()
        .to(address)
        .mode(Mode::Promotional);
    mailset.send(message).await?;
}

Complaints

A complained event means the person pressed "Report spam". It is a stronger signal than an unsubscribe.

  • Stop all promotional email to them, on every list.
  • Mailset stops sending to that address from that sending domain, so send announcements from their own subdomain (news.example.com). A complaint there never costs anyone a sign-in code from example.com.
  • When complaints run high, Mailset pauses the key that sent them. mailset guide brakes says what to fix first.

Watch out

  • Use one key for sign-in codes and receipts and another for announcements.
  • Honor an opt-out at once, not at the next batch.
  • Send only to people who asked. An unsubscribe link doesn't make unwanted email welcome.