# Bulk mail

Most of an app's mail is transactional: it tells one person about their own
account, order or request, and they need it whether or not they want
newsletters. Bulk mail is the same news sent to many people: a newsletter,
an announcement, a product update. Mail providers treat the two apart, and
so does Jadpo:

- A bulk email is `type X = BulkEmailMessage { ... }`. Everything this page
  says of an email holds for it: its folder, its templates, its subject and
  `emit`.
- It goes through a connection of its own, which `email: { bulk: }` names,
  so complaints about a newsletter never hold up a sign-in link.
- It carries a one-click unsubscribe, and it isn't sent to an address that
  used one.

Jadpo's own emails, the sign-in and privacy emails, are always
transactional, and so is your own version of one
([Built-in emails](/docs/built-in-emails.md), level 4).

## Sending a newsletter

Here members of a notes app say whether they want the monthly news, and an
action sends it to each one who does. The email is declared on
`BulkEmailMessage`.

`domains/notes/emails/news_issue.jadpo`:

```jadpo
use notes/types { Headline }

/// This month's news, sent to every member who asked for it.
type NewsIssue = BulkEmailMessage {
    headline: Headline
}
```

Each of its templates writes `{{ unsubscribe_link }}`, a `Url` every bulk
email's templates are given beside its fields.

`domains/notes/emails/news_issue.html`:

```jadpo
<h1>{{ headline }}</h1>
<p><a href="{{ unsubscribe_link }}">Unsubscribe</a></p>
```

`domains/notes/emails/news_issue.txt`:

```jadpo
{{ headline }}

Unsubscribe: {{ unsubscribe_link }}
```

Whether someone asked for bulk mail is your app's own data, as consent is
([What this does not cover](/docs/what-this-does-not-cover.md)).
Here it is a field on the member, and the query that picks the readers
honours it.

`domains/notes/entities/member.jadpo`:

```jadpo
/// Someone who reads the notes, and whether they asked for the news.
entity Member {
    id: Uuid
    email: Email {
        unique: true
    }
    wants_news: Bool

    policy: {
        create: [Access.public]
        read: [Access.public, Access.system]
    }
}
```

`domains/notes/queries/news_readers.jadpo`:

```jadpo
use notes/entities { Member }

/// Every member who asked for the news.
query news_readers() -> List<Member> {
    from: Member
    where: Member.wants_news == true
    order: [Member.email asc]
    limit: every
}
```

The action emits one email for each reader. Each goes once the action
commits, as any email does ([Sending](/docs/email.md#sending)).

`domains/notes/actions/send_news.jadpo`:

```jadpo
use notes/types { Headline }
use notes/queries { news_readers }
use notes/emails { NewsIssue }

/// Sends this month's news to every member who asked for it.
action send_news(headline: Headline) -> Unit {
    for reader in news_readers() {
        emit NewsIssue {
            to: reader.email
            locale: Locale.en_gb
            headline: headline
        }
    }
}
```

`app.jadpo` names a second connection for bulk mail, and the `SigningKey`
setting its unsubscribe links are signed with:

```jadpo
use notes/entities { Member }

application {
    display_name: "Notes"
    connections: {
        mail: {
            driver: Driver.smtp
            host: config.smtp_host
        }
        news: {
            driver: Driver.smtp
            host: config.news_host
        }
    }
    email: {
        connection: mail
        from: config.mail_sender
        bulk: {
            connection: news
            from: config.news_sender
            signing_key: config.unsubscribe_key
        }
    }
    events: {
        store: main
    }
}

principal {
    user: {
        subject: Member.email
    }
}

locales {
    default: Locale.en_gb
    supported: [Locale.en_gb]
}
```

```jadpo
config {
    mail_sender: Email {
        default: "hello@notes.example"
    }
    news_host: Hostname {
        default: "localhost"
    }
    news_sender: Email {
        default: "news@notes.example"
    }
    site: Url {
        default: "https://notes.example"
    }
    smtp_host: Hostname {
        default: "localhost"
    }
    unsubscribe_key: SigningKey
}
```

The links point at the browser session's `origin:`, as the privacy links do
([Data requests](/docs/data-requests.md)).

`authentication.jadpo`:

```jadpo
authentication {
    browser_session: {
        cookie: "notes_session"
        origin: config.site
    }
}
```

A test reads the news it sent from `email.sent`, and unsubscribes with the
token each one carries, `unsubscribe_token`, as a mail reader's one-click
unsubscribe would. The next issue isn't sent to that reader.

`domains/notes/actions/send_news.test.jadpo`:

```jadpo
use notes/entities { Member }
use notes/actions { become_member }

test "the news goes to each reader who asked, with a way to stop it" {
    var ada: Member = attempt become_member("ada@notes.example", true)
    var bob: Member = attempt become_member("bob@notes.example", false)
    assert bob.wants_news == false
    send_news("Notes can be shared")
    var sent: List<SentEmail> = email.sent
    assert list.count(sent) == 1
    assert list.all(sent, item -> item.to == ada.email and item.from == "news@notes.example")
    assert list.all(sent, item -> item.unsubscribe_token != none)
}

test "a reader who unsubscribes gets no more news" {
    var ada: Member = attempt become_member("ada@notes.example", true)
    send_news("Notes can be shared")
    match list.first(email.sent) {
        none -> {
            assert list.count(email.sent) == 1
        }
        some(sent) -> {
            assert sent.to == ada.email
            var opted_out: Response = request {
                method: HttpMethod.post
                path: "/email/unsubscribe"
                input: EmailUnsubscribe {
                    token: sent.unsubscribe_token
                }
            }
            assert opted_out.status == 204
        }
    }
    send_news("Notes in folders")
    assert list.count(email.sent) == 1
}

test "a link this app didn't send is refused" {
    var opted_out: Response = request {
        method: HttpMethod.post
        path: "/email/unsubscribe"
        input: EmailUnsubscribe {
            token: "AAAA"
        }
    }
    assert opted_out.status == 404
    assert opted_out.code == "unsubscribe_link_invalid"
}
```

## `bulk:`

`email: { bulk: }` in `application { }` says how bulk mail is sent:

| Setting | Required | What it is |
|---|---|---|
| `connection:` | Yes | The connection bulk mail goes through: one with `driver: Driver.smtp`, or a mail package's that can send the unsubscribe headers ([Through a mail package](/docs/bulk-mail.md#through-a-mail-package)). It can't be the one `email: { connection: }` names. |
| `signing_key:` | Yes | A `SigningKey` setting, which signs each unsubscribe link. Its `_PREVIOUS` value still checks a link while the key is rotated ([Signing keys](/docs/signing-keys.md)). |
| `from:` | No | Who bulk mail is from, as `email: { from: }` is written. Without it, `email:`'s address. |
| `store:` | No | The database the addresses that unsubscribed are kept in. Without it, the app's only database. |
| `link:` | No | The frontend's page the visible unsubscribe link opens: `"/unsubscribe"` unless it says. |

A mistake in any of them is
[`email.settings_invalid`](/docs/errors/email.settings_invalid.md). Emitting
a bulk email when `email:` has no `bulk:` is
[`email.connection_required`](/docs/errors/email.connection_required.md),
and `bulk:` needs `browser_session:` with its `origin:`
(`semantic.auth_setting_required`).

Two connections can be one provider. For a Postmark account they are two
connections to the same package, each with its own message stream, since
Postmark keeps transactional and broadcast mail on separate streams.

## The unsubscribe

Every bulk email carries a one-click unsubscribe, as Gmail and Yahoo ask of
bulk senders, written as RFC 8058 says:

```text
List-Unsubscribe: <https://notes.example/email/unsubscribe?token=…>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
```

- **The mail reader's button** posts that address, and the runtime answers
  `POST /email/unsubscribe` itself, in the first API that accepts browser
  sessions. It needs no cookie and no sign-in, since the reader's provider
  posts it from its own servers. It answers `204` however often it is asked,
  and `404` with `unsubscribe_link_invalid` for a token the app didn't send.
- **The visible link**, `{{ unsubscribe_link }}`, opens your frontend's page
  at the same origin, `bulk: { link: }`, with `?token=`. Loading the page
  unsubscribes nothing, so a mail scanner that follows links changes
  nothing. The page posts the token to `POST /email/unsubscribe`, in its
  query or as `{ "token": "…" }`.
- **The token** names the address by a digest of it, never the address
  itself, with a signature made with `signing_key:`, so a link can't be made
  for someone else's address. It never expires.
- **An unsubscribe is honoured as each email is sent.** A bulk email to an
  address that unsubscribed is sent to nobody, and its delivery is done.
  One unsubscribe stops all of the app's bulk mail to that address, and
  none of its transactional mail.

A bulk email's template that doesn't write `{{ unsubscribe_link }}` is
[`email.unsubscribe_missing`](/docs/errors/email.unsubscribe_missing.md), and
the health score checks the headers and the link in every bulk mail the dev
inbox catches ([The score's checks](/docs/the-dev-inbox-and-the-health-score.md#the-scores-checks)).

## Bulk mail and personal data

The addresses that unsubscribed are kept in `jadpo_unsubscribes` in
`bulk: { store: }`, each as the digest of its lower-cased text, never as the
address. The list is kept when a person is erased, so an erased person who
said no is never sent bulk mail again. The personal-data report lists the
bulk connection, as it lists the email connection, as receiving every
marked field a mail carries.

Jadpo doesn't decide who may be sent bulk mail. Whether a person consented,
or is a customer you may write to under a soft opt-in, is your app's data,
and the query that picks the readers is where you honour it. The
unsubscribe is the one rule Jadpo keeps for you.

## Through a mail package

A mail package's `provides/email.jadpo` gives the two headers as two more
parts of the message, `message.list_unsubscribe` and
`message.list_unsubscribe_post`, both `none` on transactional mail. A
package that maps both can be the bulk connection, and one that doesn't
can't, which is `email.settings_invalid`. Resend's package doesn't map
them yet.

For a provider that takes its headers as an object, as Resend's API does,
the mapping gives them to an object of the package's own:

```jadpo
// in provides/email.jadpo's send: { input: { } }
headers: {
    list_unsubscribe: message.list_unsubscribe
    list_unsubscribe_post: message.list_unsubscribe_post
}
```

The object's fields take their wire names from the package's type,
`List-Unsubscribe` and `List-Unsubscribe-Post`, as every mapping's do, and
both may be `none`, which leaves them out of what is sent.

## Transactional mail sent as bulk mail

Declaring a newsletter as `EmailMessage` would send it without an
unsubscribe. The compiler can't tell what an email means, but it can see
one sent the way bulk mail is: emitted for each item of a `for` loop, or by
the action a batch's `each:` calls, with every field but `to:` and
`locale:` the same for every item. That is
[`email.sent_in_bulk`](/docs/errors/email.sent_in_bulk.md), an error you can
decline with a reason, since a notice can rightly tell everyone the same
thing, such as a service outage. A reminder that names each person's own
book, or an invoice with their own total, is never reported.
