# Honor unsubscribes and complaints

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.

```typescript
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 <news@news.example.com>',
	to: 'ana@example.org',
	subject: 'What shipped in March',
	text,
	html,
	mode: 'promotional',
});

console.log(sent.id, sent.skipped);
```

```python
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>"
)

sent = mailset.send(
    {
        "from": "Acme News <news@news.example.com>",
        "to": "ana@example.org",
        "subject": "What shipped in March",
        "text": text,
        "html": html,
        "mode": "promotional",
    }
)

print(sent["id"], sent.get("skipped"))
```

```go
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")

html := strings.Join([]string{
	"<p>Three new things this month.</p>",
	`<a href="{{mailset_unsubscribe}}">Leave this list</a>`,
}, "\n")

sent, err := client.Send(ctx, mailset.Message{
	From:    "Acme News <news@news.example.com>",
	To:      []string{"ana@example.org"},
	Subject: "What shipped in March",
	Text:    text,
	HTML:    html,
	Mode:    mailset.ModePromotional,
})
if err != nil {
	log.Fatal(err)
}

fmt.Println(sent.ID, sent.Skipped)
```

```ruby
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 <news@news.example.com>',
  to: 'ana@example.org',
  subject: 'What shipped in March',
  text: text,
  html: html,
  mode: 'promotional'
)

p sent.id, sent.skipped
```

```php
<?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;

$sent = $mailset->send([
    'from' => 'Acme News <news@news.example.com>',
    'to' => 'ana@example.org',
    'subject' => 'What shipped in March',
    'text' => $text,
    'html' => $html,
    'mode' => 'promotional',
]);

echo $sent->id, ' ', count($sent->skipped), PHP_EOL;
```

```java
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 <news@news.example.com>")
        .to("ana@example.org")
        .subject("What shipped in March")
        .text(text)
        .html(html)
        .mode(Message.Mode.PROMOTIONAL)
        .build());

System.out.println(sent.id() + " " + sent.skipped());
```

```rust
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");

let message = Message::builder()
    .from("Acme News <news@news.example.com>")
    .to("ana@example.org")
    .subject("What shipped in March")
    .text(text)
    .html(html)
    .mode(Mode::Promotional);
let sent = mailset.send(message).await?;

println!("{} {:?}", sent.id, sent.skipped);
```

### What Ana receives

Headers Mailset adds:

```text
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
```

The text part:

```text
Three new things this month.

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

The HTML part:

```html
<p>Three new things this month.</p>
<a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Leave this list</a>
```

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

The text part:

```text
Three new things this month.

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

The HTML part:

```html
<p>Three new things this month.</p><p><a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Unsubscribe</a></p>
```

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](https://mailset.app/docs/webhooks).
- 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 news@example.com's newsletter gets no offers@example.com 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

```typescript
for (const event of events) {
	if (event.type === 'unsubscribed') {
		await stopNewsletter(event.recipient);
	}
	if (event.type === 'complained') {
		await stopAllMarketing(event.recipient);
	}
}
```

```python
for event in events:
    if event["type"] == "unsubscribed":
        stop_newsletter(event["recipient"])
    if event["type"] == "complained":
        stop_all_marketing(event["recipient"])
```

```go
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)
	}
}
```

```ruby
events.each do |event|
  case event.type
  when 'unsubscribed'
    Marketing.stop_newsletter(event.recipient)
  when 'complained'
    Marketing.stop_all(event.recipient)
  end
end
```

```php
foreach ($events as $event) {
    if ($event instanceof UnsubscribedEvent) {
        stopNewsletter($event->recipient);
    }
    if ($event instanceof ComplainedEvent) {
        stopAllMarketing($event->recipient);
    }
}
```

```java
for (MailEvent event : events) {
    if (event instanceof MailEvent.Unsubscribed u) {
        stopNewsletter(u.recipient());
    }
    if (event instanceof MailEvent.Complained c) {
        stopAllMarketing(c.recipient());
    }
}
```

```rust
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 news@news.example.com` shows who opted out, and an app key can ask the same over HTTP with [`unsubscribes.list`](https://mailset.app/docs/api/unsubscribes). 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 ana@example.org`.

## 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.

```typescript
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 <news@news.example.com>',
	to: 'ana@example.org',
	subject: 'What shipped in March',
	text,
	html,
	headers: {
		'List-Unsubscribe': `<${url}>`,
		'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
	},
	mode: 'promotional',
});
```

```python
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 <news@news.example.com>",
        "to": "ana@example.org",
        "subject": "What shipped in March",
        "text": text,
        "html": html,
        "headers": headers,
        "mode": "promotional",
    }
)
```

```go
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")

_, err = client.Send(ctx, mailset.Message{
	From:    "Acme News <news@news.example.com>",
	To:      []string{"ana@example.org"},
	Subject: "What shipped in March",
	Text:    text,
	HTML:    html,
	Headers: map[string]string{
		"List-Unsubscribe":      "<" + url + ">",
		"List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
	},
	Mode: mailset.ModePromotional,
})
```

```ruby
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 <news@news.example.com>',
  to: 'ana@example.org',
  subject: 'What shipped in March',
  text: text,
  html: html,
  headers: {
    'List-Unsubscribe' => "<#{url}>",
    'List-Unsubscribe-Post' => one_click
  },
  mode: 'promotional'
)
```

```php
$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 <news@news.example.com>',
    'to' => 'ana@example.org',
    'subject' => 'What shipped in March',
    'text' => $text,
    'html' => $html,
    'headers' => [
        'List-Unsubscribe' => "<{$url}>",
        'List-Unsubscribe-Post' => $oneClick,
    ],
    'mode' => 'promotional',
]);
```

```java
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 <news@news.example.com>")
        .to("ana@example.org")
        .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());
```

```rust
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");

let message = Message::builder()
    .from("Acme News <news@news.example.com>")
    .to("ana@example.org")
    .subject("What shipped in March")
    .text(text)
    .html(html)
    .header("List-Unsubscribe", format!("<{url}>"))
    .header(
        "List-Unsubscribe-Post",
        "List-Unsubscribe=One-Click",
    )
    .mode(Mode::Promotional);
mailset.send(message).await?;
```

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.

### Make the link

```typescript
// 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');

await mailset.send({
	from: 'Acme News <news@news.example.com>',
	to: address,
	subject: 'What shipped in March',
	text,
	html,
	headers: {
		'List-Unsubscribe': `<${url}>`,
		'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
	},
	mode: 'promotional',
});
```

```python
# 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",
}

mailset.send(
    {
        "from": "Acme News <news@news.example.com>",
        "to": address,
        "subject": "What shipped in March",
        "text": text,
        "html": html,
        "headers": headers,
        "mode": "promotional",
    }
)
```

```go
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

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")

_, err = client.Send(ctx, mailset.Message{
	From:    "Acme News <news@news.example.com>",
	To:      []string{address},
	Subject: "What shipped in March",
	Text:    text,
	HTML:    html,
	Headers: map[string]string{
		"List-Unsubscribe":      "<" + url + ">",
		"List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
	},
	Mode: mailset.ModePromotional,
})
```

```ruby
# 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

mailset.send_email(
  from: 'Acme News <news@news.example.com>',
  to: address,
  subject: 'What shipped in March',
  text: text,
  html: html,
  headers: {
    'List-Unsubscribe' => "<#{url}>",
    'List-Unsubscribe-Post' => one_click
  },
  mode: 'promotional'
)
```

```php
// 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;

$mailset->send([
    'from' => 'Acme News <news@news.example.com>',
    'to' => $address,
    'subject' => 'What shipped in March',
    'text' => $text,
    'html' => $html,
    'headers' => [
        'List-Unsubscribe' => "<{$url}>",
        'List-Unsubscribe-Post' => $oneClick,
    ],
    'mode' => 'promotional',
]);
```

```java
// 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 <news@news.example.com>")
        .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());
```

```rust
// 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");

let message = Message::builder()
    .from("Acme News <news@news.example.com>")
    .to(address)
    .subject("What shipped in March")
    .text(text)
    .html(html)
    .header("List-Unsubscribe", format!("<{url}>"))
    .header(
        "List-Unsubscribe-Post",
        "List-Unsubscribe=One-Click",
    )
    .mode(Mode::Promotional);
mailset.send(message).await?;
```

### Host the endpoint

```typescript
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>',
	);
}

// A mail provider's one click, or the page's button.
// The token says who leaves, so any body will do:
// multipart, form-encoded or empty.
export async function POST(request: Request) {
	const entry = await findToken(tokenOf(request));
	if (!entry) {
		return new Response('Bad request', { status: 400 });
	}
	await recordOptOut(entry.address, entry.list);
	return page('You’re unsubscribed.');
}
```

```python
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)


# A mail provider's one click, or the page's button.
# The token says who leaves, so any body will do:
# multipart, form-encoded or empty.
@app.post("/unsubscribe/{token}")
async def unsubscribe(token: str) -> Response:
    entry = find_token(token)
    if not entry:
        return Response("Bad request", status_code=400)
    record_opt_out(entry["address"], entry["list"])
    return page("You’re unsubscribed.")
```

```go
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)
		return
	}
	page(w, `<form method="post">`+
		`<input type="hidden" name="List-Unsubscribe"`+
		` value="One-Click">`+
		`<button>Unsubscribe</button></form>`, 200)
}

// A mail provider's one click, or the page's button.
// The token says who leaves, so any body will do:
// multipart, form-encoded or empty.
func unsubscribe(w http.ResponseWriter, r *http.Request) {
	kept, ok := findToken(r.PathValue("token"))
	if !ok {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}
	recordOptOut(kept.address, kept.list)
	page(w, "You’re unsubscribed.", 200)
}

func routes() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /unsubscribe/{token}", show)
	mux.HandleFunc("POST /unsubscribe/{token}", unsubscribe)
	return mux
}
```

```ruby
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

  # A mail provider's one click, or the page's button.
  # The token says who leaves, so any body will do:
  # multipart, form-encoded or empty.
  def create
    entry = OptOuts.find_token(params[:token])
    return head :bad_request unless entry

    OptOuts.record(entry[:address], entry[:list])
    page('You’re unsubscribed.')
  end

  private

  def page(body, status = :ok)
    render body: "<!doctype html><body>#{body}</body>",
           content_type: 'text/html', status: status
  end
end
```

```php
// 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>',
    );
});

// A mail provider's one click, or the page's button.
// The token says who leaves, so any body will do:
// multipart, form-encoded or empty.
Route::post('/unsubscribe/{token}', function (
    string $token,
) {
    $entry = findToken($token);
    if ($entry === null) {
        return response('Bad request', 400);
    }
    recordOptOut($entry['address'], $entry['list']);

    return response('You’re unsubscribed.');
});
```

```java
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>");
}

// A mail provider's one click, or the page's button.
// The token says who leaves, so any body will do:
// multipart, form-encoded or empty.
@PostMapping("/{token}")
public ResponseEntity<String> unsubscribe(
        @PathVariable String token) {
    Entry entry = findToken(token);
    if (entry == null)
        return ResponseEntity.badRequest()
                .body("Bad request");
    recordOptOut(entry.address(), entry.list());
    return page(200, "You're unsubscribed.");
}
```

```rust
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>,
    Path(token): Path<String>,
) -> Page {
    if find_token(&store, &token).await.is_none() {
        let gone = "This link has expired.";
        return page(StatusCode::BAD_REQUEST, gone);
    }
    page(StatusCode::OK, FORM)
}

// A mail provider's one click, or the page's button.
// The token says who leaves, so any body will do:
// multipart, form-encoded or empty.
async fn unsubscribe(
    State(store): State<Store>,
    Path(token): Path<String>,
) -> Page {
    let entry = find_token(&store, &token).await;
    let Some(entry) = entry else {
        let bad = StatusCode::BAD_REQUEST;
        return page(bad, "Bad request");
    };
    let (address, list) = (&entry.address, &entry.list);
    record_opt_out(&store, address, list).await;
    page(StatusCode::OK, "You’re unsubscribed.")
}

pub fn router(store: Store) -> Router {
    let route = get(show).post(unsubscribe);
    Router::new()
        .route("/unsubscribe/{token}", route)
        .with_state(store)
}
```

### Check your list before each send

```typescript
for (const address of await subscribers('news')) {
	if (await isOptedOut(address, 'news')) continue;
	await mailset.send({
		...newsletter,
		to: address,
		mode: 'promotional',
	});
}
```

```python
for address in subscribers("news"):
    if is_opted_out(address, "news"):
        continue
    mailset.send(
        {
            "from": "Acme News <news@news.example.com>",
            "to": address,
            "subject": "What shipped in March",
            "text": "Three new things this month.",
            "mode": "promotional",
        }
    )
```

```go
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)
	}
}
```

```ruby
subscribers('news').each do |address|
  next if opted_out?(address, 'news')

  mailset.send_email(
    **newsletter, to: address, mode: 'promotional'
  )
end
```

```php
foreach (subscribers('news') as $address) {
    if (isOptedOut($address, 'news')) {
        continue;
    }
    $mailset->send([
        ...$newsletter,
        'to' => $address,
        'mode' => 'promotional',
    ]);
}
```

```java
for (String address : subscribers("news")) {
    if (isOptedOut(address, "news")) continue;
    mailset.send(newsletter()
            .to(address)
            .mode(Message.Mode.PROMOTIONAL)
            .build());
}
```

```rust
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.

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content