# Moving an app's email from Postmark to AcornDispatch

This guide is for an agent or developer who moves an app's sending from Postmark to AcornDispatch. It
explains how AcornDispatch works and where each Postmark idea fits in it. AcornDispatch is its own API:
its send request uses the same field names as Postmark's for the fields it supports, but it makes no
promise to follow Postmark's API. The full reference is
[sending.md](https://api.acorndispatch.com/docs/sending.md); this page gives the steps and the differences.

## 1. The model in short

- **Base URL and path.** Every route is under `https://api.acorndispatch.com/api/v1`.
- **Auth.** `Authorization: Bearer adn_...` with an API key that has the scopes you need. There is no
  server token. `X-Postmark-Server-Token` is not accepted: a request with only that header gets 401
  `unauthorized`.
- **Streams.** A message goes to a stream. A stream is `transactional` (mail a person needs) or
  `broadcast` (newsletters, announcements). `MessageStream` takes the stream's key. The import (section
  2) creates one stream per Postmark message stream, with the Postmark stream ID as its key, so your
  `MessageStream` values keep working. As in Postmark, a stream's key never changes after it is created.
- **One recipient per message.** `To` takes exactly one address. `Cc` and `Bcc` are refused. Send a
  separate message per recipient; a batch takes up to 500.
- **Errors.** One format on every route: `{ "error": { "code", "message" } }` with a matching HTTP
  status. Branch on `error.code` (section 4).
- **Idempotency.** An `Idempotency-Key` header makes a retry safe: the same key and request answer the
  first `MessageID` again ([sending.md#idempotency](sending.md#idempotency)).
- **Webhooks.** You create them through the API. Each request is signed with an HMAC signature that your
  receiver checks (section 6).

## 2. The steps

1. **Import (a workspace Admin does it in AcornDispatch).** In Settings, Import, pick Postmark, paste
   your Postmark server's Server API token and click Connect. The page shows the server's name and ID:
   check that it is the server you are moving. Then run Streams, then Suppressions. AcornDispatch only
   reads with the token and never shows it again. It never deletes the token on its own: a workspace Admin
   removes it (step 6). Never paste the token into a chat or an email. The import copies:
   - Each Postmark message stream (not Inbound, not archived) as an AcornDispatch stream with the same
     ID as its key. Each stream's `track_opens` and `track_links` copy the Postmark server's settings.
     Imported broadcast streams are hidden from the preference page. Each imported stream also keeps
     its own unsubscribe list, so an unsubscribe on one stream stops that stream only.
   - The defaults: Postmark's `outbound` and `broadcast` merge into the workspace's default
     transactional and default broadcast stream. A default that has never sent mail takes the Postmark
     ID as its key and the server's tracking settings (the default broadcast stream is also hidden), so
     a single send with no `MessageStream` still lands on `outbound` (a batch needs `MessageStream` on
     every message, section 3). A default that has sent mail keeps its key, and the import says
     `Postmark stream "outbound" maps to "<key>"`. Then send that key as `MessageStream`, or leave
     `MessageStream` out of a single send: `MessageStream: "outbound"` answers `stream_not_found`. Either way, suppressions from `outbound` and `broadcast` land on the default.
   - The suppressions: a hard bounce or a spam complaint blocks the address for all mail, and a manual
     suppression opts the address out of the stream with the same key.
   - Webhooks are not imported. Create them yourself (section 6).

   From the first finished Suppressions import, AcornDispatch reads new Postmark suppressions once a day
   for 30 days (the unsubscribe sync). So an unsubscribe from an email that Postmark sent still reaches
   AcornDispatch. The sync ends early when Postmark rejects the token, or when three daily runs in a row
   fail; the Import page says why. Replace the token within the 30 days and the sync starts again. A run
   started by hand on the Import page never ends the sync.
2. **Get an API key.** A workspace Admin creates one in AcornDispatch (Email API, APIs & Keys) with
   `email:send`, plus `webhooks:write`, `streams:write` or `suppressions:write` if your app uses those
   routes.
3. **Change the calls** (section 3).
4. **Create the webhooks** your app needs and check their signature (section 6).
5. **Deploy**, then send one message and read it back
   ([sending.md#check-your-integration](sending.md#check-your-integration)).
6. **Remove the token.** When you no longer need to import, a workspace Admin clicks Remove key in
   Settings, Import. AcornDispatch never deletes the token itself, so until then the page shows a reminder.
   Removing it ends the unsubscribe sync if it still runs. To import again later, paste a token of the same
   Postmark server.
7. **After the sync ends,** remove the Postmark DNS records (its DKIM and Return-Path records) from your
   domain, once nothing sends through Postmark any more.

## 3. Change the calls

| Postmark | AcornDispatch |
|---|---|
| `https://api.postmarkapp.com/email` | `https://api.acorndispatch.com/api/v1/email` |
| `https://api.postmarkapp.com/email/batch` | `https://api.acorndispatch.com/api/v1/email/batch` |
| `X-Postmark-Server-Token: <token>` | `Authorization: Bearer adn_...` |

**Client libraries.** Some client libraries build paths that drop a base-path prefix, so a custom base
URL can lose its `/api/v1` part. Use a small client subclass that puts `/api/v1` in front of every path,
or call the API with plain HTTP:

```python
import requests

def send_email(api_key: str, message: dict, idempotency_key: str) -> dict:
    r = requests.post(
        "https://api.acorndispatch.com/api/v1/email",
        headers={"Authorization": f"Bearer {api_key}", "Idempotency-Key": idempotency_key},
        json=message,
        timeout=30,
    )
    body = r.json()
    if r.status_code != 200:
        raise RuntimeError(f"{body['error']['code']}: {body['error']['message']}")
    return body  # { "To", "SubmittedAt", "MessageID", "ErrorCode": 0, "Message": "OK" }
```

### Request fields

| Field | Postmark | AcornDispatch |
|---|---|---|
| `From` | A confirmed sender signature or domain | The workspace sending domain or a subdomain of it. Quote a display name that holds a special character; in Python use `email.utils.formataddr`. See [sending.md#from-address](sending.md#from-address). |
| `To` | A comma-separated list | Exactly one address. A list gets 422 `unsupported_field`. |
| `Cc`, `Bcc` | Supported | Refused with 422 `unsupported_field`. Send a separate message per recipient. |
| `Subject` | Required | At most 2,000 characters, one line. |
| `HtmlBody`, `TextBody` | The bodies | Sent as written. No template language runs on them. |
| `ReplyTo` | Reply address | One address. |
| `Headers` | Custom headers | At most 20. `Feedback-ID` takes one identifier: the header's first field ([sending.md#feedback-id](sending.md#feedback-id)). `List-Unsubscribe` and `List-Unsubscribe-Post` on a transactional stream only (see below). |
| `Tag` | One tag | One string, at most 1,000 characters. |
| `Metadata` | Key and value pairs | At most 20 keys; key 1 to 80 characters; string values of at most 1,000 characters. |
| `MessageStream` | Stream ID | The stream key; the import keeps the Postmark IDs. Not sent: the default transactional stream on a single send, 422 `stream_required` on a batch message. |
| `TrackOpens` | Open tracking | `true` or `false`. Not sent: the stream's default. |
| `TrackLinks` | `None`, `HtmlAndText`, `HtmlOnly`, `TextOnly` | Same values, but links are rewritten in the HTML part only. `HtmlAndText` and `TextOnly` act as `HtmlOnly`: links in `TextBody` are not tracked. |
| `Attachments` | Files | At most 20 files and 10 MB in all, base64 `Content`. |
| `TemplateId`, `TemplateAlias`, `TemplateModel` | Template sends | Not available. Build the HTML in your app. |

Any field AcornDispatch does not know is refused with 400 `invalid_request`, so an unsupported field
fails at once instead of being ignored.

**Unsubscribe headers.** On a transactional stream your app may set `List-Unsubscribe` and
`List-Unsubscribe-Post` in `Headers`. On a broadcast stream AcornDispatch sets them itself, and a message
that sets either one gets 422 `list_unsubscribe_not_allowed`. There, remove them and put
`{{{ unsubscribe_url }}}` in the body (section 5). The value rules are in
[sending.md#list-unsubscribe](sending.md#list-unsubscribe).

**Feedback-ID.** Send one identifier (1 to 32 characters from `A-Z`, `a-z`, `0-9`, `.`, `_` and `-`, no
colon). It becomes the first field of the header, with each `.` changed to `-`; the stream key is the
second field (the sending servers can write their own value there instead), and they fill the last two. A value with a colon, such as a full
Feedback-ID your app built for Postmark, gets 400 `invalid_request`.

**From.** The check is strict (RFC 5322). A display name with a special character (such as `,`, `@` or
`<`) outside double quotes gets 422 `from_invalid`. `Smith, Jane <jane@mail.acme.example>` is refused;
send `"Smith, Jane" <jane@mail.acme.example>`.

Other differences:

- **Body size.** 10 MB for one message. 16 MB for a batch, where Postmark takes 50 MB: split a large
  batch. Above the limit: 413 `payload_too_large`.
- **Batch.** Up to 500 messages. The answer is HTTP 200 with one result per message in request order.
  A refused entry has `ErrorCode` set to an HTTP status (for example 422) and an `error` object.
  Every message needs `MessageStream`: where Postmark falls back to `outbound`, a message without it gets
  422 `stream_required` and the other messages go on.
- **Success answer.** `To`, `SubmittedAt`, `MessageID` (a UUID), `ErrorCode` (0) and `Message` (`OK`).
- **No `/email/bulk`.** Use `POST /api/v1/email/batch`.
- **No SMTP.** Send through the REST API only.

## 4. Errors

```json
{ "error": { "code": "recipient_inactive", "message": "The recipient cannot receive this message: suppressed.", "reason": "suppressed" } }
```

Where your code handles a Postmark `ErrorCode`, handle the AcornDispatch `error.code`:

| Postmark `ErrorCode` | AcornDispatch `error.code` |
|---|---|
| 10 (bad or missing API token) | `unauthorized` (401) |
| 300 (invalid email request) | `invalid_request` (400), or `unsupported_field` (422) for `Cc`, `Bcc` or a list in `To` |
| 400 (sender signature not found) | `from_domain_not_allowed` (422) or `from_invalid` (422) |
| 406 (inactive recipient) | `recipient_inactive` (422), with `error.reason` (`suppressed`, `address_not_found` or `unsubscribed`) and the stored `MessageID` |

Every code is listed in [sending.md#errors](sending.md#errors).

## 5. Unsubscribe links

- Use `{{{ unsubscribe_url }}}`. `{{{ pm:unsubscribe }}}` still works on every stream kind; change it
  when you touch the template.
- On a broadcast stream, a body without a placeholder gets AcornDispatch's footer: an Unsubscribe link
  and the workspace postal address when it is set. Put your postal address in the HTML yourself.
- On a transactional stream the link unsubscribes the recipient from that stream only.

## 6. Webhooks

Create webhooks with `POST /api/v1/webhooks` ([sending.md#webhooks](sending.md#webhooks)). Your Postmark webhooks are not
copied.

- Events: `Delivery`, `Bounce`, `SpamComplaint`, `Open`, `Click` and `SubscriptionChange`. The payload
  field names match Postmark's for the fields AcornDispatch sends. Only the fields listed in
  [sending.md#webhook-events](sending.md#webhook-events) are sent: a Postmark field such as `ServerID` or `Subject` is not there.
- Bounce `Type` and `TypeCode` use Postmark's values for `HardBounce`, `SoftBounce`, `Blocked`,
  `Unknown` and `SpamComplaint`. `ClickLocation` is always `HTML`. `Origin` is `Recipient` or
  `Customer`.
- Every request carries `X-AcornDispatch-Signature`, an HMAC-SHA256 signature of the body. Your
  receiver must check it ([sending.md#webhook-signature](sending.md#webhook-signature) has receivers in
  Node.js, Python and Ruby) and drop duplicates by
  `X-AcornDispatch-Delivery`.
- You can also set `http_auth` (Basic auth) and `headers`, for example to keep your endpoint's existing
  checks.
- Retries run for 24 hours. A webhook whose deliveries all fail for 48 hours is turned off.
- Keep your Postmark webhooks until Postmark sends nothing more for you.

## 7. Other Postmark calls

| Postmark | AcornDispatch |
|---|---|
| `POST /email/withTemplate`, `POST /email/batchWithTemplates` | Not available. Build the HTML in your app and use `POST /api/v1/email`. |
| `POST /email/bulk` | Not available. Use `POST /api/v1/email/batch`. |
| `GET /messages/outbound/{id}/details` | GET /api/v1/messages/{id} |
| `GET /messages/outbound` (search) | GET /api/v1/messages, with the filters `status`, `stream`, `tag`, `since` and `until` and a cursor (see below) |
| `GET /bounces`, `PUT /bounces/{id}/activate` | No bounces endpoint. GET /api/v1/messages with `status=bounced` (bounced messages), GET /api/v1/suppressions (what blocks an address), DELETE /api/v1/suppressions (lift it), and `Bounce` webhooks. A spam complaint cannot be lifted. |
| Suppressions of a message stream (dump, create, delete) | GET /api/v1/suppressions and DELETE /api/v1/suppressions. Adding a suppression is not available in the API. |
| Message streams | GET /api/v1/streams, POST /api/v1/streams, PATCH /api/v1/streams/{key}, POST /api/v1/streams/{key}/pause and POST /api/v1/streams/{key}/resume |
| Webhooks | GET /api/v1/webhooks, POST /api/v1/webhooks, PATCH /api/v1/webhooks/{id}, DELETE /api/v1/webhooks/{id} |
| `GET /stats/outbound` and the other stats | GET /api/v1/stats: sent, delivered, bounced, complained, opened and clicked counts per stream and per sending group (`marketing`, `transactional`), with one AcornDispatch rate per stream (`bounce_rate`) and the group's reputation rates (`reputation`) (see below) |
| Templates, servers, domains, sender signatures, inbound | Not available in the API. |

The message list and the stats are described in [sending.md#messages](sending.md#messages) and
[sending.md#stats](sending.md#stats), with examples. Points to check
when you move code over:

- **Message list.** Newest first, at most 100 per page (default 20). Page with the cursor: send
  `next_cursor` back as `cursor`, with the same filters, until it is `null`. `since` and `until` are ISO
  8601 date-times with `Z` or an offset, and filter on `submitted_at`. The list holds every message of
  the workspace, not only those your app sent.
- **Stats.** One window, `since` to `until` (default: the 30 days before now), counted by send time.
  There is no per-day breakdown: ask for each day as its own window. The counts are messages, and
  `opened` and `clicked` leave out machine opens and clicks. `bounce_rate` is a fraction from 0 to 1,
  not a percentage. `complained` is a count. `reputation` uses the window of the mail providers, not `since` and
  `until`.
