@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.
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
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: trueis implicit TLS (465). Otherwise STARTTLS is required: a relay that offers none fails the send instead of downgrading to plaintext.requireTLS: falseis 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 asca. - Sanitized. Every message goes through
sanitizeMailMessagebefore 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 withinvalid_recipient; CR/LF in the subject and display names becomes a space. - A reply in its thread.
inReplyTo(the Message-ID answered) andreferences(the thread’s ids, oldest first) go out asIn-Reply-ToandReferenceson 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 withinvalid_recipientlike a bad address; the newest 50 references are kept.@octabits-io/connections’replyTo(mail)gives both for a mail read from a mailbox. - Envelope.
returnPathsetsMAIL FROMwithout touching the visibleFrom, 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_errorwith the SMTP code, reply code, command and the server’s words in one line, the reply code asstatus, andpermanent: truefor 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), enqueued on the transaction that decided to send, and returnpermanenton itsjob_failedso the job dead-letters at once instead of retrying what cannot pass. Store and logkeyandstatus, notmessage: the server’s words may quote the address. The transport’s ownlogger.errorcarries 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_errorwithpermanent: true(sending again would duplicate the mail for the others), the counts inmessageand the refused addresses only inproviderError. - 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
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.mdhas the row). The way out is./smtp— same contract, so the switch is the wiring. - No dependency.
POST /v3/smtp/emailoverfetch, the key in theapi-keyheader, 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_errorwith the HTTP status and Brevo’s errorcode(Brevo send failed: 401 unauthorized) — never Brevo’smessage, which may quote the recipient’s address. A 4xx ispermanent(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.
returnPathis ignored: Brevo has no per-message envelope sender, and its bounces arrive through its event webhook. AttachmentcontentTypeis not sent: Brevo takes the type from the file name’s extension, and refuses extensions outside its list. ThemessageIdreturned is the RFC 5322 Message-ID, which Brevo’s webhook echoes too, so both ids carry it.
Through Mailjet
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.mdhas the row. Send API v3.1 (POST /v3.1/send) overfetchwith basic auth, no dependency. - No Message-ID. Mailjet does not return the RFC 5322 id, so
messageIdisnull: thread replies on a tagged reply address.providerMessageIdis the first recipient’sMessageUUID, which the event webhook echoes asMessage_GUID.returnPathis ignored. - Errors keep the HTTP status and Mailjet’s
ErrorCode(mj-0013), never itsErrorMessage, which may quote an address. Permanence follows the same rule as Brevo’s.
Through Scaleway
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), theemail_idits webhook events carry. Scaleway creates one e-mail per recipient; the first is the handle. - What maps differently.
replyTogoes out as aReply-Toheader (the API has no field for it);returnPathis ignored. Errors keep the HTTP status and Scaleway’s errortype(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:
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);
});
externalMessageIdis what the send returned asproviderMessageId ?? messageId: store that and the events find their message.deliveryStatusis one ofMAIL_DELIVERY_STATUSES(delivered,bouncedfor good,failedfor now;queued,sentanddiscardedare the host’s own), ornullfor an open, a click, an unsubscribe. Derive your column’s enum from the tuple.reasonis 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) andparseMailjetInbound(Mailjet’s Parse API) read intoNormalizedInboundMessage: Message-ID,In-Reply-ToandReferencesfor threading, the text and HTML, and the attachments. Mailjet sends the bytes themselves ascontent; Brevo adownloadToken, whichfetchBrevoInboundAttachmentturns 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’stoincludes 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 anAuthorizationheader in constant time —{ token }for Brevo’s bearer auth,{ username, password }for credentials in the webhook URL (both providers), which arrive as basic auth;webhookSecretMatcheschecks 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 toconfirmScalewaySubscriptionbefore parsing: it confirms the subscription (ok(true)) and fetches the link only when it is HTTPS onsns.mnq.<region>.scaleway.comand asks forConfirmSubscription, 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
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,watchandattachmentas@octabits-io/connections’Mailboxdefines 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 idsmailbox_not_foundand 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 ismailbox_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 atmaxTextBytes.readnames, types and sizes the attachments, never downloads them. - An attachment’s bytes.
attachment(mailId, attachmentId)downloads one, by the part numberreadgave it as its id, decoded from its transfer encoding; pastATTACHMENT_MAX_BYTES(25 MiB) the download stops and the answer ismailbox_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
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
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
sendis one attempt. Durable delivery is a job. - Write to a mailbox.
./imapreads; 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
returnPathand reply addresses, and nothing here parses them: bounce reports differ from server to server, and reading them takes a mailbox../smtpis 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
MailTransportof 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.
From @octabits-io/mail@0.11.0 in the platform repository.