---
title: "@octabits-io/mail"
summary: "Mail delivery behind one transport contract: a normalized message, Result-typed sends that return the Message-ID, a sanitizer that refuses smuggled recipients and header injection, in-memory and logger transports for tests and development, a redirect for non-production, SMTP through your own relay — optional auth, STARTTLS required by default, your internal certificate authority trusted — and the APIs of Brevo, Mailjet and Scaleway Transactional Email over fetch, opt-in, for a host that has chosen one as a subprocessor — and a mailbox read over IMAP, read-only, for `@octabits-io/connections` — with each provider's delivery-event webhook (and Brevo's inbound parsing) read into one provider-neutral shape."
install: "pnpm add @octabits-io/mail"
availability: "Available from November 2026"
version: "0.11.0"
license: "MIT"
related:
  - name: "@octabits-io/connections"
    url: "https://octabits.io/platform/connections.md"
  - name: "@octabits-io/result"
    url: "https://octabits.io/platform/result.md"
canonical_url: "https://octabits.io/platform/mail"
---

# `@octabits-io/mail`

Mail behind one transport contract. A normalized message, a `send` that returns the
Message-ID or an error value, a sanitizer that refuses smuggled recipients and header
injection, the transports a test and a laptop need, a redirect for staging, and SMTP through
your own relay — or, opt-in, the API of Brevo, Mailjet or Scaleway for a host that has chosen
one, with that provider's webhooks read into one delivery-event shape. Nothing leaves the house
unless your relay is someone else's, or you picked a provider.

It also reads a mailbox: `./imap` is `@octabits-io/connections`' mailbox contract on IMAP,
read-only, for a process that starts from a mail and an agent that drafts a reply.

```bash
pnpm add @octabits-io/mail          # + nodemailer for ./smtp
                                    # + imapflow and @octabits-io/connections for ./imap
```

| Subpath | Runs on | Deps | Contents |
|---|---|---|---|
| `.` | any runtime | `@octabits-io/result` | the `MailTransport` contract and `MailMessage`, `sanitizeMailMessage`, `isValidRecipientAddress`, `stripHeaderUnsafeChars`, `createMemoryTransport`, `createLoggerTransport`, `createRedirectTransport`, `createFooterTransport`; the webhook shapes `NormalizedDeliveryEvent`, `NormalizedInboundMessage`, `MAIL_DELIVERY_STATUSES`; `isAuthorizedWebhook`, `webhookSecretMatches` |
| `./smtp` | Node | `nodemailer` (optional peer) | `createSmtpTransport`, `verifySmtpConnection` |
| `./imap` | Node | `imapflow`, `@octabits-io/connections` (optional peers) | `createImapMailbox`, `imapMailId`, `htmlToText` |
| `./brevo` | any runtime with `fetch` | none | `createBrevoTransport`, `verifyBrevoConnection`, `parseBrevoEvents`, `parseBrevoInbound`, `fetchBrevoInboundAttachment`, `mapBrevoEventToDeliveryStatus` |
| `./mailjet` | any runtime with `fetch` | none | `createMailjetTransport`, `verifyMailjetConnection`, `parseMailjetEvents`, `parseMailjetInbound`, `mapMailjetEventToDeliveryStatus` |
| `./scaleway` | any runtime with `fetch` | none | `createScalewayTransport`, `verifyScalewayConnection`, `parseScalewayEvents`, `confirmScalewaySubscription`, `mapScalewayEventToDeliveryStatus` |

## Sending

```ts
import { createSmtpTransport, verifySmtpConnection } from '@octabits-io/mail/smtp';

const smtp = {
  host: 'relay.example.internal',
  port: 587,                                   // STARTTLS, required
  ca: readFileSync('/etc/ssl/internal-ca.pem', 'utf8'), // your own authority, trusted beside the system's
  // auth: { user, pass },                     // omit for a relay that accepts by network
  // timeoutMs: 30_000,                        // connect, greeting and each reply (default 30 s)
};

const check = await verifySmtpConnection(smtp);   // at boot or from a settings page
const mail = createSmtpTransport({ smtp, logger });

const sent = await mail.send({
  from: { address: 'approvals@example.com', name: 'Approvals' },
  to: [address],
  subject: 'Your part is ready',
  text, html,
});
if (!sent.ok) return sent;                         // mail_delivery_error | invalid_recipient
await saveMessageId(sent.value.messageId);         // what a reply echoes in In-Reply-To
```

- **TLS.** `secure: true` is implicit TLS (465). Otherwise STARTTLS is **required**: a relay
  that offers none fails the send instead of downgrading to plaintext. `requireTLS: false` is
  for a plaintext test server such as Mailpit and nothing else. Certificate checks are never
  switched off; an internal relay is trusted by passing its authority as `ca`.
- **Sanitized.** Every message goes through `sanitizeMailMessage` before it reaches
  nodemailer, which reads a comma in an address as a list. One bad address — `to`, `bcc`,
  `from`, `replyTo`, `returnPath` — refuses the whole message with `invalid_recipient`;
  CR/LF in the subject and display names becomes a space.
- **A reply in its thread.** `inReplyTo` (the Message-ID answered) and `references` (the
  thread's ids, oldest first) go out as `In-Reply-To` and `References` on every transport —
  SMTP, and as custom headers on Brevo, Mailjet and Scaleway. Each must be one Message-ID
  (`<id@host>`), else the message is refused with `invalid_recipient` like a bad address;
  the newest 50 references are kept. `@octabits-io/connections`' `replyTo(mail)` gives both
  for a mail read from a mailbox.
- **Envelope.** `returnPath` sets `MAIL FROM` without touching the visible `From`, for a
  tagged bounce address; blind copies are in the envelope, never in a header.
- **Failures are values.** A refused login, a timeout, a 550 come back as
  `mail_delivery_error` with the SMTP code, reply code, command and the server's words in
  one line, the reply code as `status`, and `permanent: true` for a 5xx reply — the
  relay's final answer. A 4xx, a timeout or a lost connection is temporary. Retry belongs
  to the caller: send from a durable job ([`@octabits-io/queue`](https://octabits.io/platform/queue.md)), enqueued on
  the transaction that decided to send, and return `permanent` on its `job_failed` so the
  job dead-letters at once instead of retrying what cannot pass. Store and log `key` and
  `status`, not `message`: the server's words may quote the address. The transport's own
  `logger.error` carries the codes and the command, never the server's words.
- **A partial refusal is a failure.** A relay that accepts some recipients and refuses
  others sends to the accepted ones; the send returns `mail_delivery_error` with
  `permanent: true` (sending again would duplicate the mail for the others), the counts in
  `message` and the refused addresses only in `providerError`.
- **Bounded.** `timeoutMs` (default 30 s) bounds the connection, the greeting and each
  wait for a reply, so a hung relay fails the send as temporary instead of holding the job
  for nodemailer's default of minutes.

## Through Brevo

```ts
import { createBrevoTransport, verifyBrevoConnection } from '@octabits-io/mail/brevo';

const brevo = { apiKey: process.env.BREVO_API_KEY! };  // baseUrl, timeoutMs (10 s), fetch: optional

const check = await verifyBrevoConnection(brevo);      // reads the account with the key
const mail = createBrevoTransport({ brevo, logger });
const sent = await mail.send(message);                 // the same MailMessage, the same errors
```

- **A subprocessor.** Brevo sees every recipient and every body: list it in your annex
  (`infra/SUBPROCESSORS.md` has the row). The way out is `./smtp` — same contract, so the
  switch is the wiring.
- **No dependency.** `POST /v3/smtp/email` over `fetch`, the key in the `api-key` header,
  attachments base64-encoded. Runs on Node, Bun, Deno and a Worker alike.
- **Sanitized** as SMTP is. A non-2xx answer comes back as `mail_delivery_error` with the
  HTTP status and Brevo's error `code` (`Brevo send failed: 401 unauthorized`) — never
  Brevo's `message`, which may quote the recipient's address. A 4xx is `permanent` (bad
  parameters or address, a refused key, an IP not authorised, an unverified sender, no
  credits) except 408, 425 and 429; a 5xx, a network failure or a timeout is temporary.
- **What maps differently.** `returnPath` is ignored: Brevo has no per-message envelope
  sender, and its bounces arrive through its event webhook. Attachment `contentType` is
  not sent: Brevo takes the type from the file name's extension, and refuses extensions
  outside its list. The `messageId` returned is the RFC 5322 Message-ID, which Brevo's
  webhook echoes too, so both ids carry it.

## Through Mailjet

```ts
import { createMailjetTransport, verifyMailjetConnection } from '@octabits-io/mail/mailjet';

const mailjet = { apiKey: process.env.MJ_APIKEY_PUBLIC!, apiSecret: process.env.MJ_APIKEY_PRIVATE! };
const mail = createMailjetTransport({ mailjet, logger });   // baseUrl, timeoutMs (10 s), fetch: optional
```

- **A subprocessor**, as Brevo is; `infra/SUBPROCESSORS.md` has the row. Send API v3.1
  (`POST /v3.1/send`) over `fetch` with basic auth, no dependency.
- **No Message-ID.** Mailjet does not return the RFC 5322 id, so `messageId` is `null`:
  thread replies on a tagged reply address. `providerMessageId` is the first recipient's
  `MessageUUID`, which the event webhook echoes as `Message_GUID`. `returnPath` is ignored.
- **Errors** keep the HTTP status and Mailjet's `ErrorCode` (`mj-0013`), never its
  `ErrorMessage`, which may quote an address. Permanence follows the same rule as Brevo's.

## Through Scaleway

```ts
import { createScalewayTransport, verifyScalewayConnection } from '@octabits-io/mail/scaleway';

const scaleway = { secretKey: process.env.SCW_SECRET_KEY!, projectId: process.env.SCW_PROJECT_ID! };
const mail = createScalewayTransport({ scaleway, logger });  // region ('fr-par'), baseUrl, timeoutMs, fetch: optional
```

- **A subprocessor** in Scaleway's Paris region; the annex has the row. Give the IAM key the
  Transactional Email permissions and nothing else. The sender's domain must be verified in
  the Project.
- **Both ids.** A send returns the Message-ID and Scaleway's e-mail id (`providerMessageId`),
  the `email_id` its webhook events carry. Scaleway creates one e-mail per recipient; the
  first is the handle.
- **What maps differently.** `replyTo` goes out as a `Reply-To` header (the API has no field
  for it); `returnPath` is ignored. Errors keep the HTTP status and Scaleway's error `type`
  (`invalid_arguments`); a spent sending quota (`quotas_exceeded`) is temporary.

## Delivery events and inbound mail

Whether a mail was delivered or bounced is known only from a provider's API: its webhook
reports it. Over `./smtp` there is no such report — a relay's bounces come back as mail — so a
host that needs delivery status sends through a provider.

Each provider subpath parses its webhook into one shape, so the handler behind it is written
once:

```ts
import { isAuthorizedWebhook } from '@octabits-io/mail';
import { parseBrevoEvents } from '@octabits-io/mail/brevo';   // or parseMailjetEvents, parseScalewayEvents

const credentials = { token: process.env.BREVO_WEBHOOK_TOKEN! };  // registered as the webhook's `auth`

app.post('/webhooks/mail', async (c) => {
  if (!isAuthorizedWebhook(c.req.header('authorization'), credentials)) return c.body(null, 401);
  const events = parseBrevoEvents(await c.req.json());
  if (!events.ok) return c.body(null, 400);
  for (const e of events.value) {
    if (e.deliveryStatus) await markDelivery(e.externalMessageId, e.deliveryStatus, e.reason);
  }
  return c.body(null, 204);
});
```

- **`externalMessageId`** is what the send returned as `providerMessageId ?? messageId`:
  store that and the events find their message.
- **`deliveryStatus`** is one of `MAIL_DELIVERY_STATUSES` (`delivered`, `bounced` for good,
  `failed` for now; `queued`, `sent` and `discarded` are the host's own), or `null` for an
  open, a click, an unsubscribe. Derive your column's enum from the tuple.
- **`reason`** is often the receiving server's reply verbatim and may quote the address: keep
  it with the message, not in a log line.
- **Inbound.** `parseBrevoInbound` (Brevo's inbound parsing) and `parseMailjetInbound`
  (Mailjet's Parse API) read into `NormalizedInboundMessage`: Message-ID, `In-Reply-To` and
  `References` for threading, the text and HTML, and the attachments. Mailjet sends the bytes
  themselves as `content`; Brevo a `downloadToken`, which `fetchBrevoInboundAttachment` turns
  into the bytes (25 MiB by default, by declared length and by what arrives). Screen them
  before anything opens them. Brevo extracts the reply from its quoted history
  (`strippedText`); Mailjet does not, so there it is the raw text. Mailjet's `to` includes
  the envelope recipient — the Parse address — so a tagged reply address is found even when
  it was in Bcc. Scaleway receives no mail: a Scaleway host reads replies from its own
  mailbox.
- **Authenticate the request.** Brevo and Mailjet sign nothing: what proves a request is
  theirs is a secret you registered. `isAuthorizedWebhook(header, credentials)` checks an
  `Authorization` header in constant time — `{ token }` for Brevo's bearer auth,
  `{ username, password }` for credentials in the webhook URL (both providers), which arrive
  as basic auth; `webhookSecretMatches` checks a secret path segment. Scaleway's events
  arrive in a signed SNS envelope that the parser unwraps but does not verify: guard that
  endpoint with a secret path. Treat every parsed field as untrusted regardless.
- **Scaleway's handshake.** The topic's first request is a `SubscriptionConfirmation`. Pass
  every body to `confirmScalewaySubscription` before parsing: it confirms the subscription
  (`ok(true)`) and fetches the link only when it is HTTPS on `sns.mnq.<region>.scaleway.com`
  and asks for `ConfirmSubscription`, never following a redirect — a forged body cannot make
  the host request anything else.
- **Pure and total.** No network, no database; a body that is no payload at all is an error
  value, an item that cannot be matched is dropped. One event per request and batched arrays
  are both read.

## Reading a mailbox over IMAP

```ts
import { createImapMailbox } from '@octabits-io/mail/imap';
import { isPublicAddress } from '@octabits-io/server/outbound/node';

const { connection, secrets } = (await connections.reveal(id)).value;   // for this one call
const inbox = createImapMailbox({
  host: secrets.host,                     // imap.example.com
  auth: { user: secrets.user, pass: secrets.password },
  allowAddress: isPublicAddress,          // or allowPublicAndListed(operatorRanges)
  // security: 'starttls', port: 143, ca: internalCaPem, timeoutMs: 30_000, maxTextBytes: 1_000_000
});

const arrived = await inbox.watch(cursor);          // ids since the cursor; keep the next cursor
const mail = await inbox.read(arrived.value.ids[0]); // the sender's text: the step is tainted
```

- **The contract.** `folders`, `list`, `read`, `watch` and `attachment` as `@octabits-io/connections`' `Mailbox`
  defines them; every answer is held to its schema. A mail's id is the folder's UIDVALIDITY, the
  UID and the folder (`imapMailId`): a folder renumbered by its server makes the old ids
  `mailbox_not_found` and a watch start again from now (`reset: true`).
- **Read-only.** Every folder is opened read-only, so reading a mail never marks it seen, and
  nothing is ever written, moved or deleted. A reply is a proposal a person approves, sent on your
  transport with `replyTo(mail)`'s threading headers (`inReplyTo`, `references`).
- **Where it connects.** The server's name is resolved here; every address it resolves to must pass
  `allowAddress` (required — public only, unless the operator listed a private one), and the
  connection is pinned to the address checked while the certificate is checked against the name,
  so a name that later resolves elsewhere is not followed. A refused address is `mailbox_refused`.
- **TLS always.** Implicit TLS on 993 by default, or STARTTLS required on 143; the certificate is
  always checked, an internal server's authority passed as `ca`. Never plaintext.
- **The text.** The first plain-text part that is not an attachment, else the first HTML part as
  text (`htmlToText`: no markup, no script or style), cut at `maxTextBytes`. `read` names, types
  and sizes the attachments, never downloads them.
- **An attachment's bytes.** `attachment(mailId, attachmentId)` downloads one, by the part number
  `read` gave it as its id, decoded from its transfer encoding; past `ATTACHMENT_MAX_BYTES`
  (25 MiB) the download stops and the answer is `mailbox_too_large`. Its name and type are the
  sender's: check the bytes before you trust them.
- **One connection per call**, logged out after it. A refused login is `mailbox_refused`; a server
  that does not answer, `mailbox_unreachable`; a missing folder, `mailbox_not_found`. No error
  carries the password.

## Without a server

```ts
import { createLoggerTransport, createMemoryTransport, createRedirectTransport } from '@octabits-io/mail';

const test = createMemoryTransport();               // test.messages(), test.messagesTo(a), test.last()
const dev = createLoggerTransport({ logger });      // logs the message, body included
const staging = createRedirectTransport(createSmtpTransport({ smtp }), 'qa@example.com', { logger });
```

The redirect sends every message to one address and drops the blind copies, so no mail
from a staging system reaches a real person.

## A footer under every message

```ts
import { createFooterTransport } from '@octabits-io/mail';

const mail = createFooterTransport(createSmtpTransport({ smtp }), {
  text: process.env.MAIL_FOOTER,                    // every language without its own
  languages: { en: process.env.MAIL_FOOTER_EN! },   // matched to the message's `language`
});
await mail.send({ ...message, language: 'en' });
```

The operator's company details — a GmbH or UG owes its legal name and form, seat, register court
and number and managing directors in a mail to a named person (§ 35a GmbHG, § 37a HGB) — and the
links to the imprint and the privacy notice. Wrapped once where the transport is made, no send
site can forget it. The text is appended after the signature delimiter (`-- `); in the HTML it is
escaped, its line breaks kept, under a rule, before `</body>`. A message's `language` (`de-AT`)
picks its text exactly, then by the primary subtag (`de`), then `text`; with none, the message is
sent as it is. Keep the texts in configuration, not code: they belong to whoever runs the
deployment.

## A transport of your own

`MailTransport` is `{ type, send(message) }`. A vendor API, a mail-merge service or a queue
is a few lines over it. A transport hands fields to its provider as they are: call
`sanitizeMailMessage` first when the input is not yours.

## What it does not do

- **Templates and routing.** Which template, which locale, who receives what, a
  notifications copy: the host's. The message arrives rendered.
- **Retries.** One `send` is one attempt. Durable delivery is a job.
- **Write to a mailbox.** `./imap` reads; it never marks, moves, deletes or appends — a sent
  reply is not copied to a Sent folder.
- **Delivery status over SMTP.** A relay's bounces and replies arrive as mail at the
  `returnPath` and reply addresses, and nothing here parses them: bounce reports differ from
  server to server, and reading them takes a mailbox. `./smtp` is the way out, not a tracked
  delivery path. A host that sends through its own mail server and needs the status runs one
  that reports events itself (Postal's webhooks, KumoMTA's log hooks) and parses those, as
  the provider subpaths do.
- **Other vendor APIs.** Brevo, Mailjet and Scaleway are the ones shipped, all three
  EU-established. SES, Postmark and the rest are a `MailTransport` of a few lines, or SMTP,
  written where you have chosen one.

## Stability

0.x: a minor may change the surface and says so in its changeset. The bytes on the wire are
nodemailer's over SMTP, and each provider's over its API.