Skip to content

rover ​

@c9up/rover: sending mail for ream, through SMTP, the log mailer or a provider's HTTP API (SES, Mailgun, SendGrid, Resend, Brevo, SparkPost), with templates, retries, queued sending and delivery webhooks. Guide: Mail.

Installation ​

bash
pnpm add @c9up/rover
ream configure @c9up/rover

ream configure @c9up/rover adds the provider, the MAIL_MAILER, MAIL_FROM, SMTP_HOST and SMTP_PORT variables, and writes config/mail.ts. Optional peers: @c9up/ream (provider), @c9up/inker (mail views rendered with inker), ical-generator (icalEvent(callback)), @c9up/helix (the mailFake() test plugin).

Mail templates run in a native engine. It comes as one small package per platform, @c9up/rover-<platform>, for linux x64 and arm64 (glibc), macOS x64 and arm64, and Windows x64. @c9up/rover lists them as optional dependencies, and your package manager installs only the one that matches your machine. No Rust toolchain is needed. Do not install with optional dependencies turned off (--no-optional, --omit=optional): the engine would be left out. Without it, rendering a template throws E_MAIL_TEMPLATE_NAPI_REQUIRED, and its message names the package to install, for example @c9up/rover-linux-x64-gnu.

Entry points ​

ImportContents
@c9up/roverMail, Mailer, MessageBuilder, BaseMail, defineConfig and transports, the transport classes, retry helpers, the provider class and the error class. Importing it registers every bundled transport.
@c9up/rover/providerRoverProvider (default export).
@c9up/rover/services/mainThe application's Mail (default export), usable once the provider booted.
@c9up/rover/configureconfigure(codemods), run by ream configure @c9up/rover.
@c9up/rover/transports/mailgunMailgunTransport.
@c9up/rover/transports/sendgridSendGridTransport.
@c9up/rover/transports/sesSesTransport.
@c9up/rover/transports/resendResendTransport.
@c9up/rover/transports/brevoBrevoTransport.
@c9up/rover/transports/sparkpostSparkPostTransport.
@c9up/rover/testingFakeMail and the mailFake() helix plugin.
@c9up/rover/webhooks/mailguncreateMailgunWebhookHandler and its replay store.
@c9up/rover/webhooks/sendgridcreateSendGridWebhookHandler.
@c9up/rover/webhooks/resendcreateResendWebhookHandler.

Each transports/* entry exports one class, also exported from @c9up/rover; importing the subpath registers that transport under its name.

Exports ​

@c9up/rover ​

ExportKindDescription
MailclassThe mail manager: builds, sends and queues messages through the declared mailers.
MailerclassOne named mailer, from mail.use(name).
MailResponseclassWhat a send resolves to.
MessageBuilderclassThe fluent message a send callback fills.
BaseMailclassBase of a class-based mail.
defineConfigfunctionTypes the mail config.
transportsconstOne descriptor helper per bundled transport.
registerTransportfunctionRegisters a custom transport factory under a name.
SmtpTransportclassSMTP through nodemailer.
LogTransportclassLogs each message instead of sending it.
SesTransport, MailgunTransport, SendGridTransport, ResendTransport, BrevoTransport, SparkPostTransportclassProvider HTTP API transports.
RoverProviderproviderAlso the default export of @c9up/rover/provider.
errorsnamespaceThe package's errors, one class per code, see Errors. Each is a flare Exception with a string code.
DEFAULT_RETRY_CONFIGconst{ maxAttempts: 3, baseDelayMs: 500, factor: 2, maxDelayMs: 10000 }.
isRetryableErrorfunctionWhether a send failure is worth retrying.
RetryConfiginterface{ maxAttempts: number; baseDelayMs: number; factor: number; maxDelayMs?: number }.
attachmentsForfunctionA message's attachments plus its calendar invitation as a text/calendar part.
listHeadersfunctionA message's List-* headers as a plain header map.
headersWithListfunctionA message's headers plus its rendered List-* headers.
headerValuefunctionA header value as a plain string or string array.
MailConfiginterfaceThe mail config.
TransportDescriptorinterfaceOne mailer's settings: { transport: string; retry?: RetryConfig; [key: string]: unknown }.
MailTransportinterfaceWhat a transport implements.
MailTransportFactorytype(config: Record<string, unknown>) => MailTransport.
MailSendResult, MailSendOutcometypeWhat a transport's send returns.
MailMessageinterfaceA built message.
MailAttachmentinterfaceOne attachment.
MailAddresstypestring | { address: string; name?: string }.
Recipient, RecipientInput, RecipientObjecttypeA recipient, as stored and as the builder accepts it.
MailEnvelopeinterfaceThe SMTP envelope: from, to, cc, bcc.
MailResponseEnvelopetypeThe envelope a MailResponse carries.
AttachmentOptions, EmbedImageOptionstypeOptions of the attach* and embed* methods.
ListHeadertypestring | { url: string; comment: string }.
CalendarEvent, CalendarEventMethod, CalendarEventOptionstypeA calendar invitation.
PreparedHeaderinterface{ prepared: true; value: string }: a header passed through unencoded.
TemplateEngineinterfaceWhat renders htmlView, textView and watchView.
MessageBodyTemplatesinterfaceThe templates a message was rendered from.
MailHooksinterfaceonSending, onSent, onFailed, onQueueing, onQueued callbacks.
EmitterLikeinterface{ emit(event: string, data: unknown): unknown }.
MailEventBase, MailSendingEvent, MailSentEvent, MailFailedEvent, MailQueueEventinterfaceThe payloads of the mail:* events.

Mail ​

MemberSignatureDescription
constructornew Mail(config: MailConfig, options?: { queue?: BayQueueLike; hooks?: MailHooks; emitter?: EmitterLike })Throws E_MAIL_UNKNOWN_MAILER when default is not a declared mailer.
sendsend(callback: (message: MessageBuilder) => void, transport?: string): Promise<MailResponse>
send(instance: BaseMail, transport?: string): Promise<MailResponse>
Builds and sends through the named mailer, or the default one.
sendLatersendLater(arg: ((message: MessageBuilder) => void) | BaseMail, options?: { transport?: string; queue?: string }): Promise<string>Queues the send and resolves the job id. Without a wired queue, an in-memory messenger sends it on the next microtask.
sendCompiledsendCompiled(message: MailMessage, transport?: string): Promise<MailResponse>Sends a message already built.
sendLaterCompiledsendLaterCompiled(message: MailMessage, options?: { transport?: string; queue?: string }): Promise<string>Queues a message already built.
dispatchMessagedispatchMessage(message: MailMessage, transportName?: string, overrideRetry?: RetryConfig, views?: MessageBodyTemplates): Promise<MailResponse>The send with retries, events and hooks that the other methods go through.
setMessengersetMessenger(messenger: BayQueueLike): thisHands sendLater a queue after construction.
useuse(name?: string): MailerThe named mailer (the default one without a name), cached per name.
closeclose(name?: string): Promise<void>Closes one transport's connections; an unknown name does nothing.
closeAllcloseAll(): Promise<void>Closes every transport built so far.
fakefake(): FakeMailCaptures every send and sendLater instead of delivering.
restorerestore(): voidLeaves fake mode.

With an emitter, a send emits mail:sending, then mail:sent or mail:failed; sendLater emits mail:queueing and mail:queued.

Mailer ​

MemberSignatureDescription
nameget name(): stringThe mailer's name.
transportget transport(): MailTransportIts transport instance.
sendsend(arg: ((message: MessageBuilder) => void) | BaseMail): Promise<MailResponse>Sends through this mailer.
sendLatersendLater(arg: ((message: MessageBuilder) => void) | BaseMail, options?: { queue?: string }): Promise<string>Queues for this mailer.
sendCompiledsendCompiled(message: MailMessage): Promise<MailResponse>
sendLaterCompiledsendLaterCompiled(message: MailMessage, options?: { queue?: string }): Promise<string>
closeclose(): Promise<void>Closes this mailer's transport connections.

MailResponse ​

MemberSignatureDescription
messageIdmessageId: stringThe id to correlate with provider webhooks.
envelopeenvelope: MailResponseEnvelopeThe envelope used.
originaloriginal: TThe transport's raw result.

MessageBuilder ​

GroupSignatures
Addressesfrom(address: string, name?: string): this
to(address: string, name?: string): this / to(addresses: RecipientInput[]): this
cc(…), bcc(…) (same overloads)
replyTo(address: string, name?: string): this
envelope(envelope: MailEnvelope): this
Contentsubject(text: string): this
html(content: string): this, text(content: string): this
watch(content: string): this, watchHtml(content: string): this
TemplateshtmlView(viewPath: string, data?: Record<string, unknown>): this
textView(path: string, data?: Record<string, unknown>): this
watchView(viewPath: string, data?: Record<string, unknown>): this
Attachmentsattach(file: string | URL, options?: AttachmentOptions): this
attachData(content: Buffer | string, options: AttachmentOptions & { filename: string }): this
embed(file: string | URL, cid: string, options?: AttachmentOptions): this
embedData(content: Buffer | string, cid: string, options?: AttachmentOptions): this
Headersheader(key: string, value: string | string[]): this
preparedHeader(key: string, value: string): this
priority(priority: 'low' | 'normal' | 'high'): this
messageId(messageId: string): this, inReplyTo(messageId: string): this, references(messageIds: string[]): this
encoding(encoding: string): this
List headersaddListHeader(key: string, value: ListHeader | ListHeader[] | ListHeader[][]): this
listUnsubscribe(value, options?: { oneClick?: boolean }): this (a one-click target must be https)
listSubscribe(value): this, listHelp(value): this
CalendaricalEvent(contents: string | CalendarEventCallback, options?: CalendarEventOptions): this
icalEventFromFile(file: string | URL, options?: CalendarEventOptions): this
icalEventFromUrl(url: string, options?: CalendarEventOptions): this
InspectionhasTo, hasCc, hasBcc, hasFrom, hasReplyTo, hasAnyRecipient (address?: string, name?: string): boolean
hasRecipient(property: 'to' | 'cc' | 'bcc' | 'replyTo', address: string, name?: string): boolean
hasSubject(subject?: string), hasContent(needle: string), hasHeader(name: string, value?: string), hasListHeader(key: string, url?: string), hasAttachment(match?: string | URL | ((attachment: MailAttachment) => boolean))
AssertionsassertTo, assertFrom, assertCc, assertBcc, assertReplyTo, assertRecipient (address: string): void
assertSubject(subject: string), assertContent(needle: string), assertHeader(name: string, value?: string), assertAttachment(match)
assertHtmlIncludes(substring: string), assertTextIncludes(substring: string), assertWatchIncludes(substring: string | RegExp); each throws an AssertionError from node:assert
Outputbuild(viewsRoot?: string, globals?: Record<string, unknown>): Promise<MailMessage>
toObject(): Readonly<MailMessage>, toJSON(): Readonly<MailMessage>
get views(): MessageBodyTemplates, get contentViews(): MessageBodyTemplates, get nodeMailerMessage(): MailMessage
Staticstatic templateEngine: TemplateEngine | undefined: the engine views render with; unset, rover's built-in {{ }} engine renders .html files under viewsRoot. The provider sets inker's when the app uses it.

BaseMail ​

An abstract class: a mail written as a class.

MemberSignatureDescription
messagereadonly message: MessageBuilderThe message this mail builds.
from, replyToMailAddressApplied before prepare().
subjectstringApplied before prepare().
builtbooleanWhether build already ran; a second build returns the first message.
prepareabstract prepare(): void | Promise<void>Fills this.message.
sendsend<R>(mailer: MailSender<R>): Promise<R>Sends this mail through mailer.
sendLatersendLater(mailer: MailSender<unknown>): Promise<void>Queues it.
buildbuild(viewsRoot?: string, globals?: Record<string, unknown>): Promise<MailMessage>Builds the message and renders its templates.
buildWithContentsbuildWithContents(viewsRoot?: string, globals?: Record<string, unknown>): Promise<MailMessage>The same as build.

Transports ​

FunctionSignatureDescription
registerTransportregisterTransport(name: string, factory: MailTransportFactory): voidMakes transport: name usable in mailers.
defineConfigdefineConfig(config: MailConfig): MailConfigReturns the config, typed.
isRetryableErrorisRetryableError(err: unknown): booleanTrue for a provider 429 or 5xx, a transient SMTP failure, or a network error such as ETIMEDOUT or ECONNRESET.

MailTransport is { send(message: MailMessage): Promise<MailSendOutcome>; close?(): Promise<void> }; MailSendResult is { providerId?: string; envelope?: MailResponseEnvelope; original?: unknown }.

transports holds smtp, ses, mailgun, sparkpost, resend, brevo, sendgrid and log, each (config?: Record<string, unknown> & { retry?: RetryConfig }) => TransportDescriptor.

TransportSettings it reads
smtphost (required), port, user and pass (both or neither) or auth, requireTLS, ignoreTLS, opportunisticTLS, allowInsecureAuth; other keys go to nodemailer's SMTP options. Credentials are refused with TLS off unless allowInsecureAuth: true. new SmtpTransport(config, options?: { transporter?: SmtpTransporter }).
loglogBody (default false).
sesaccessKeyId, secretAccessKey, region.
mailgunapiKey, domain, region ('us' or 'eu'), baseUrl.
sendgridapiKey, baseUrl.
resendapiKey.
brevoapiKey (or key), baseUrl.
sparkpostapiKey (or key), baseUrl.

Every transport class takes new XTransport(config: Record<string, unknown>) and implements MailTransport.

@c9up/rover/provider ​

ExportKindDescription
RoverProviderprovider (default)register() binds Mail from the mail config, with the QueueManager and Emitter bindings when they exist; boot() renders mail views with inker when the app uses it; shutdown() undoes that.

@c9up/rover/services/main ​

ExportKindDescription
defaultconstThe application's Mail. Any property access before the provider booted throws.
ts
import mail from '@c9up/rover/services/main'

await mail.send((message) => {
  message.to(user.email).subject('Welcome').htmlView('welcome', { user })
})

@c9up/rover/configure ​

ExportKindDescription
configurefunctionconfigure(codemods): Promise<void>: what ream configure @c9up/rover runs.

@c9up/rover/testing ​

ExportKindDescription
FakeMailclassCaptures sent and queued messages; returned by mail.fake().
FakeMailPredicateinterfaceMatches on from, to, cc, bcc, replyTo, subject, or containing.
FakeMailPredicateArgtypeA FakeMailPredicate or (m: MailMessage) => boolean.
MailConstructortypeA BaseMail subclass, for the class form of the assertions.
FakeableMailerinterface{ fake(): FakeMail; restore(): void }: what mailFake takes.
mailFakefunctionmailFake(mailer: FakeableMailer): (api: MailPluginHost) => void: a helix plugin that puts a fresh FakeMail on each test's context as ctx.mail and restores the mailer after the test.
MailPluginHosttypeThe part of helix's plugin API it uses.
FakeMail memberSignatureDescription
getSent, getQueued(): MailMessage[]What was captured.
resetreset(): voidForgets everything captured.
assertSent, assertNotSent, assertQueued, assertNotQueued(predicate: FakeMailPredicateArg): void
<T extends BaseMail>(mailConstructor: MailConstructor<T>, findFn?: (mail: T) => boolean): void
By content, or by the BaseMail class that built it.
assertSentCount, assertQueuedCount(count: number): void
(mailConstructor: MailConstructor<BaseMail>, count: number): void
assertNoneSent, assertNoneQueued(): void

Each assertion of the fake throws an AssertionError from node:assert when it does not hold.

Webhooks ​

Each handler is a WebhookMiddleware, (ctx, next?) => Promise<void>, that you mount as the handler of a Ream route (router.post('/webhooks/mailgun', handler)), with or without the body parser. It reads the signed bytes with ctx.request.rawBuffer(), the body as it came over the wire. It verifies the provider's signature, refuses a stale one (default 300 seconds), answers 401 or 400 on a refusal and 200 otherwise, and emits mail.delivered, mail.bounced or mail.failed on the emitter; an emitter failure never fails the answer.

ImportExportSignature
@c9up/rover/webhooks/mailguncreateMailgunWebhookHandler(options: MailgunWebhookOptions) => WebhookMiddleware; options signingKey, emitter, maxAgeSeconds?, tokenStore?
@c9up/rover/webhooks/mailgunMemoryWebhookTokenStorenew MemoryWebhookTokenStore(options?: { maxEntries?: number }) (default 10000): the in-process store of used signature tokens; claim(token, ttlSeconds): boolean, size
@c9up/rover/webhooks/mailgunWebhookTokenStore{ claim(token: string, ttlSeconds: number): boolean | Promise<boolean> }: pass a shared one behind several instances
@c9up/rover/webhooks/sendgridcreateSendGridWebhookHandler(options: SendGridWebhookOptions) => WebhookMiddleware; options publicKey (the ECDSA P-256 key of the signed event webhook, base64 DER or PEM; any other key is refused with E_ROVER_WEBHOOK_INVALID_KEY), emitter, maxAgeSeconds?; verifies ECDSA over SHA-256
@c9up/rover/webhooks/resendcreateResendWebhookHandler(options: ResendWebhookOptions) => WebhookMiddleware; options secret (whsec_… or raw base64), emitter, maxAgeSeconds?

A Mailgun signature token is accepted once: a replay answers 401.

Configuration ​

config/mail.ts, written by ream configure @c9up/rover:

OptionTypeDefaultDescription
defaultstringrequiredThe mailer used when none is named; must be a key of mailers. The generated config reads MAIL_MAILER with no fallback.
fromMailAddressrequiredDefault sender.
mailersRecord<string, TransportDescriptor>The declared mailers, built with transports.*. transports is an older spelling, merged with mailers.
globalsRecord<string, unknown>{}Shared with every template.
viewsRootstring'resources/views/emails'Root of htmlView lookups for the built-in engine.
queue.namestring'mail.send'The queue job name sendLater dispatches.
queue.maxAttemptsnumber3Attempts of a queued send.
retryPartial<RetryConfig>DEFAULT_RETRY_CONFIGProcess-wide retry; a mailer's own retry overrides it.

Container bindings ​

TokenResolves to
MailThe Mail singleton.
'rover.mail'The same instance.
'mail'The same instance (earlier name, still bound).

The string tokens are declared on ContainerBindings.

Errors ​

Each code is a class of the errors namespace (import { errors } from '@c9up/rover'): a flare Exception with code, status (500 for all of them) and, when the place that raises it knows how to fix it, help. E_INVALID_CONFIG and E_MAIL_TRANSPORT_ERROR are built as new errors.E_INVALID_CONFIG(message, { cause }); E_MAIL_TRANSPORT_ERROR also takes context and help in that object. Four of them also carry context, a Record<string, string>:

Classcontext
E_MAIL_TRANSPORT_ERRORprovider, upstreamStatus (HTTP status or SMTP reply code, "0" when none came back), providerMessage, networkCode (an errno such as ECONNRESET), retryAfter (seconds) and, once the send gave up, attempts.
E_MAIL_FIELD_UNSUPPORTEDprovider, field.
E_MAIL_TEMPLATE_NOT_FOUNDpath, viewsRoot, and paths (the candidates looked at). Empty when the native engine reports a missing partial.
E_MAIL_TEMPLATE_READ_ERRORpath, code (the errno), viewsRoot.
CodeRaised when
E_MAIL_INVALID_MESSAGEA message lacks what sending needs (a from address, a recipient…).
E_MAIL_INVALID_ADDRESSAn address is not a valid mail address.
E_MAIL_HEADER_INJECTIONA header value contains a line break or NUL.
E_INVALID_LIST_HEADERA List-* entry is not one URL (https, http, mailto or ftp) or bare address.
E_MAIL_FIELD_UNSUPPORTEDThe transport cannot set a field the message uses.
E_ATTACHMENT_UNREADABLEAn attachment's file cannot be read.
E_INVALID_CONFIGA transport's config is missing a property or holds an invalid one.
E_MAIL_TRANSPORT_ERRORThe transport failed to send; context carries the status or network code.
E_MAIL_RETRY_CONFIGA retry setting is out of range.
E_MAIL_CONFIG_MISSINGNo mail config is registered.
E_MAIL_UNKNOWN_MAILERA mailer name, or the default mailer, is not declared.
E_MAIL_UNKNOWN_TRANSPORTA mailer names a transport that is not registered.
E_MAIL_JOB_MALFORMEDA queued mail job's payload is missing or not an object.
E_MAIL_TEMPLATE_ENGINEThe app uses inker but rover cannot render mail views with it.
E_MAIL_TEMPLATE_NOT_FOUNDA mail template is not found.
E_MAIL_TEMPLATE_READ_ERRORA mail template cannot be read.
E_MAIL_TEMPLATE_SYNTAXA mail template has a syntax error.
E_MAIL_TEMPLATE_RECURSIONMail templates include each other too deep.
E_MAIL_TEMPLATE_NAPI_REQUIREDThe native rover template engine is missing or failed to load. The message names the package to install.
E_ROVER_ICAL_UNAVAILABLEicalEvent(callback) needs ical-generator, which is not installed or does not build a calendar.
E_ROVER_UNKNOWNA send failed with an error that carries no code of its own. Only the error.code of a mail:failed event: there is no class.
E_ROVER_NOT_BOOTEDThe services/main mail singleton was used before RoverProvider booted.
E_ROVER_FAKE_ACTIVEmail.fake() was called while a fake is already active; call restore() first.
E_ROVER_INVALID_PREDICATEA fake-mailer assertion got an empty containing needle, which would match every message.
E_ROVER_ABSTRACT_MAILBaseMail was instantiated directly instead of through a subclass.
E_ROVER_WEBHOOK_KEY_MISSINGA webhook handler was created without its secret, public key or signing key.
E_ROVER_WEBHOOK_INVALID_SECRETThe Resend webhook secret is not valid base64, or decodes to fewer than 16 bytes.
E_ROVER_WEBHOOK_INVALID_KEYThe SendGrid webhook publicKey is not a public key, or not an ECDSA key on P-256.
E_ROVER_INTERNALAn internal invariant broke (nodemailer composed no message); report it as a bug.

Migration ​

  • RoverError is gone. Replace instanceof RoverError with a test on error.code, or with instanceof errors.E_MAIL_TRANSPORT_ERROR (or the class of the code you expect), errors coming from @c9up/rover.
  • error.hint is now error.help.
  • context stays on the four classes listed under Errors only; the other errors have none. context.attempts is set on an E_MAIL_TRANSPORT_ERROR only.
  • E_MAIL_PROVIDER_ERROR is now E_MAIL_TRANSPORT_ERROR. It is built as new errors.E_MAIL_TRANSPORT_ERROR(message, { context, cause, help }): context moved from the second argument into the options.
  • E_MAIL_PROVIDER_CONFIG is now E_INVALID_CONFIG for a transport config that is missing or invalid; a missing key reads Invalid config for "resend" transport. The "apiKey" property is missing. A message without recipients now raises E_MAIL_INVALID_MESSAGE, and icalEvent(callback) without a usable ical-generator raises E_ROVER_ICAL_UNAVAILABLE.
  • E_ASSERTION_FAILED is gone: the message assertions and the fake mailer's assertions throw an AssertionError from node:assert.
  • docsUrl, sourceFile, sourceLine and pipelineStage are gone: nothing set them.
  • The name of an error is no longer "RoverError".
  • The webhook handlers read the signed body with ctx.request.rawBuffer(), Ream's own method, instead of ctx.request.rawBody(). Mount them directly on a Ream route. A context you build yourself (another framework, a test) must now provide request.rawBuffer() returning the wire bytes as a Buffer; response.header() is no longer needed.
  • createSendGridWebhookHandler() now refuses a publicKey that is not an ECDSA key on P-256 with E_ROVER_WEBHOOK_INVALID_KEY, and a string that is not a key with the same code. Use the verification key from the SendGrid dashboard.

See also ​