Packages
ajo-kit-mail: validated messages, transports and delivery outcomes.
ajo-kit-mail gives an Ajo Kit application one careful path for email. Every message is validated and frozen before a transport sees it, delivery makes a single attempt under a hard deadline, and failures come back as a small set of codes with a retry verdict instead of provider text. It is meant for the mail an application sends on its own behalf: verification links, password resets, invitations, a copy of someone’s notes.
Install
pnpm add ajo-kit-mail@0.4.1ajo-kit is a peer dependency. nodemailer (^10.0.10) is an optional peer used only by the SMTP transport; applications that use the HTTP or capture transports do not install it.
pnpm add nodemailer # only when using smtp()Configure a transport
Call configure() once while the server boots. The official starter keeps this in src/mail.ts and imports it from the root wares.ts. It captures mail in memory during development and posts to an HTTP provider in production:
import { configure } from 'ajo-kit-mail'
import { capture } from 'ajo-kit-mail/capture'
import { http } from 'ajo-kit-mail/http'
import { env } from 'ajo-kit/platform'
export const mailbox = env('NODE_ENV') === 'production' ? null : capture({ keep: 20 })
configure({
from: { address: 'notes@example.com', name: 'Ajo Notes' },
transport: mailbox ?? http({
url: 'https://api.provider.example/send',
headers: () => ({ Authorization: `Bearer ${env('MAIL_TOKEN')}` }),
body: mail => ({
from: mail.from.address,
to: mail.to.address,
subject: mail.subject,
text: mail.text,
}),
}),
})import './mail'configure() is plain assignment: it opens no socket and starts no timer, so it is safe to run again on every development reload. It throws a Refused error with code invalid-config only for a development transport such as capture() when NODE_ENV is production. Besides transport and from, it takes an optional default replyTo and a timeout in milliseconds for one attempt (10,000 by default). The sender and timeout are checked each time a message is sealed.
The package is marked server-only, so Kit blocks importing it from client code. Keep your own src/mail.ts on the server too, for example by adding it to the guard patterns of kit() in vite.config.ts.
Deliver a message
deliver() is the one way to send. It never throws: it resolves to an Outcome to branch on. Without a configured transport, every delivery is refused with no-transport.
import { deliver } from 'ajo-kit-mail'
const outcome = await deliver({
to: { address: 'ana@example.com', name: 'Ana' },
subject: 'Reset your password',
text: `Choose a new password: ${link}`,
kind: 'reset',
key: resetId,
expires: Date.now() + 60 * 60 * 1000,
})
if (!outcome.ok && outcome.kind === 'undelivered' && outcome.retryable) scheduleRetry()type Outcome =
| { ok: true; id: string }
| { ok: false; kind: 'refused'; code: RefusalCode; error: Refused }
| { ok: false; kind: 'undelivered'; code: DeliveryCode; retryable: boolean; error: Undelivered }The id is the provider’s id when the transport returns one, otherwise the envelope’s own UUID. There are no automatic retries; the package makes one attempt and tells you whether another one makes sense. In a route action, turn a failed outcome into a message the person can act on:
import { Failure, type Request } from 'ajo-kit'
import { authorize } from 'ajo-kit-auth'
import { deliver } from 'ajo-kit-mail'
export const actions = {
email: async (req: Request) => {
authorize(req)
const outcome = await deliver({
to: req.user!.email,
subject: 'Your notes',
text: await summary(req.user!.id),
})
if (!outcome.ok) throw new Failure(503, 'The message could not be delivered. Try again later.')
return { message: 'Your notes were sent.' }
},
}Code that should fail the request with the package’s own error throws it: if (!outcome.ok) throw outcome.error.
Messages
A message has exactly one recipient, because credential mail must not fan out, and a subject with a text or HTML body. kind labels it in logs, key is an idempotency key forwarded to providers that accept one, and expires is a hard deadline: pass the expiry of the credential the message carries. A message may also override from and replyTo.
An address is a single mailbox of 3 to 254 characters, as a string or { address, name }; a name is at most 128 bytes without " < > , ; : \. kind is a lowercase letter followed by up to 31 lowercase letters, digits or hyphens (default mail), and key is up to 128 characters from A-Z a-z 0-9 . _ : -, never deduplicated locally.
Sealing rejects control characters in addresses, names, subject, kind and key. That is the boundary that stops header injection; bodies may contain line breaks. The transport receives an AbortSignal that fires at the earlier of timeout and expires, and a message whose deadline has already passed is never attempted.
Transports
http()
A JSON provider over the global fetch, available on Node and on Ajo Engine. The body mapping is the only provider-specific code you write.
import { http } from 'ajo-kit-mail/http'
import { env } from 'ajo-kit/platform'
const transport = http({
url: 'https://api.provider.example/send',
headers: () => ({ Authorization: `Bearer ${env('MAIL_TOKEN')}` }), // read on every send
body: mail => ({ from: mail.from.address, to: mail.to.address, subject: mail.subject, text: mail.text }),
id: payload => (payload as { id?: string }).id,
})- It sends a
POSTwithContent-Type: application/jsonunless you set another. A header factory lets a rotated token be read per send instead of captured at boot. - The message
keybecomes theIdempotency-Keyheader. - A success body is read only when
idis set, parsed as JSON up to 64 KiB on the engine; a larger body fails as a retryableconnectionerror, and an empty one is still a success. Failure bodies are cancelled unread, and only the status is classified: 429 isthrottled, 5xx isunavailable, 401 and 403 areauth, 408 istimeout, other 4xx arerejected.
The starter reads the endpoint, token and sender from the environment and declares them in kit.engine.env.required, so a production build states what it needs. The package itself declares kit.engine.net, so an App that depends on it may call fetch on the engine. See Build and configuration.
smtp()
import { smtp } from 'ajo-kit-mail/smtp'
const transport = smtp({ host: 'smtp.example.com', user: 'apikey', pass: process.env.SMTP_PASS })One connection per message through nodemailer, with mandatory verified TLS. STARTTLS is required on the default port 587; use port: 465 with implicit: true for TLS from the first byte. The certificate is verified and TLS 1.2 is the floor. None of that is configurable, and there is no URL form: the connection takes discrete host, user and pass fields, with user and pass given together. name sets the EHLO name and defaults to the sender’s domain.
capture()
A bounded in-memory transport for development and tests. It keeps the newest 50 envelopes unless you pass keep, and with log: true it prints only the id, kind and recipient domain. configure() refuses it in production.
import { configure, deliver } from 'ajo-kit-mail'
import { capture } from 'ajo-kit-mail/capture'
const mailbox = capture()
configure({ transport: mailbox, from: 'notes@example.com' })
await deliver({ to: 'ana@example.com', subject: 'Reset', text: 'Open https://notes.example.com/reset/abc' })
mailbox.link(/\/reset\//) // first matching URL in the last text bodyThe capture also exposes messages, last() and clear().
Custom transports
A transport is an async function that receives a Sealed envelope and may return { id }. The package seals every message before any transport sees it, so a transport can never receive unvalidated input. Honour mail.signal, and pass failures through classify() so they keep the same sanitization:
import { classify, type Transport } from 'ajo-kit-mail'
const transport: Transport = async mail => {
try {
const result = await provider.send(
{ to: mail.to.address, subject: mail.subject, text: mail.text },
{ signal: mail.signal },
)
return { id: result.id }
} catch (error) {
throw classify(error) // reads shape only: name, code and status fields
}
}A transport may also carry dev: true to be refused in production. classify() returns an Undelivered unchanged, so a thrown new Undelivered('throttled', 'status 429') keeps its hint.
Errors
A failed outcome carries one of two errors. Refused means nothing was sent and no provider was contacted: the configuration or the message was rejected. Undelivered means the transport accepted the envelope and the attempt failed; the outcome’s retryable says whether another attempt makes sense, and the error may carry a protocol status hint such as smtp 451 or status 429.
Both extend Kit’s Failure, so an outcome.error thrown inside an action becomes an HTTP error: 500 for the configuration refusals (no-transport, invalid-config and invalid-sender, which are also logged as [mail] refused: code), 422 for every other refusal, which concerns the message, and 502 for Undelivered. Neither ever echoes an address, a subject, a body or provider prose.
- AuthenticationCreate the reset and verification links these messages carry.
- ActionsSend mail from a route action and report the result.
- Build and configurationDeclare the environment a production build requires.
Full reference: ajo-kit packages/ajo-kit-mail/README.md