Mailing interface
Consumer contract for sending templates and recording provider events with the DMS mailing interface.
@antelopejs/interface-dms-mailing exports seven backend functions and the template types below. SendTemplate sends, RecordEmailEvent reports provider events, DeclareTemplate, DeclareTemplateCategory, DeclareSender and DeclareWebhookSecret ship templates, categories, the sender and the webhook secret as code, and ImportSends imports past sends. They need @antelopejs/dms-mailing and an @antelopejs/interface-email provider loaded, and are imported from the interface package, not the runtime module's services.
All seven take an explicit tenantId. They are trusted backend calls, not permission-checked HTTP endpoints, so the calling module authenticates and authorizes the tenant. A missing implementation or a storage failure rejects the promise.
Per-recipient results
The example needs a published order-confirmation template with an order.total variable in an authorized tenant. It sends real e-mails.
import { SendTemplate } from "@antelopejs/interface-dms-mailing";
export async function sendOrderConfirmation(tenantId: string, recipients: string[]) {
const result = await SendTemplate("order-confirmation", {
tenantId,
to: recipients,
variables: { order: { total: "48.00" } },
source: "checkout",
});
return result.results ?? [result];
}
The array holds one result per recipient, such as sent for one address and suppressed for the other. Resending the whole call delivers the first e-mail twice, and the suppressed recipient stays suppressed. The Sends page records each send's template version and locale, and provider events add delivery information later.
SendTemplate
import type { EmailAddress } from "@antelopejs/interface-email";
import type {
SendStatus,
TemplateContent,
TemplateVariables,
} from "@antelopejs/interface-dms-mailing";
interface SendTemplateParams {
tenantId: string;
to: EmailAddress | EmailAddress[];
locale?: string;
variables?: TemplateVariables;
content?: TemplateContent;
source?: string;
isTest?: boolean;
attachments?: SendAttachment[];
cc?: EmailAddress[];
replyTo?: EmailAddress;
}
interface SendAttachment {
filename: string;
contentType?: string;
content: Uint8Array; // a Buffer is one
}
interface SendTemplateResult {
sendId: string;
status: SendStatus;
messageId?: string;
error?: string;
results?: SendTemplateResult[];
}
declare function SendTemplate(
slug: string,
params: SendTemplateParams,
): Promise<SendTemplateResult>;
to accepts an address string, an { email: string, name?: string } object, or an array of either. The slug resolves within tenantId. The template must exist even when content overrides its body. A non-test send needs a live template. content neither saves nor publishes the override. The locale is the requested one (any case, or its base language), else the workspace's fallback locale, else en, else the content's first locale. source labels the send log.
The module renders HTML and plain text, uses batch delivery for several recipients when the provider supports it, and tries to log one row per recipient. With isTest, the subject starts with [TEST] , the draft is used when there is one, a non-live template is accepted, and production metrics leave the send out. It does not bypass the suppression list.
Results and failures
For several recipients, the top-level result describes the whole call, not only the first recipient.
sendIdandmessageIdbelong to the first recipient.statusis the worst outcome. From best to worst, the order isclicked,opened,delivered,sent,queued,unsubscribed,suppressed,spam,bounced,failed.erroris the first non-empty error in recipient order, not necessarily that of the worst status.resultsholds one result per recipient, in input order, without nestedresults. The type makes it optional, and the implementation sets it even for one recipient.
A suppressed address gets no e-mail. Its result has status: "suppressed" and an error key that starts with $dms_mailing.errors.suppressed., followed by hard_bounce, complaint, unsubscribe or manual. A retry of a suppressed recipient delivers nothing and logs another suppressed send.
Provider failures become failed recipient results. If recording a send fails, its result has sendId: "", status: "failed" and an error, and can still carry a provider messageId, because delivery may have happened. A failed result does not prove that no e-mail left, and retrying the whole call can deliver twice.
Validation failures reject the promise instead of returning recipient results. The runtime's errors carry one of these codes: no_recipient, template_not_found, template_not_live, invalid_content, missing_variables or attachments_too_large. The interface does not export the error class. The workspace's Missing variables setting decides whether missing variables refuse a send. Marketing footer URLs are required system variables when the template uses them, never for test sends. Storage or notification failures can reject after side effects started, so the call is neither transactional nor idempotent.
variables is TemplateVariables, a record of strings, numbers, booleans, null, Date values, money values ({ value: 987420, currency: "EUR" }, in the currency's minor unit), and lists and records of the same. Dates and money are written in the send's locale. A class instance or a function does not compile, and a template path reads only the keys a record owns.
attachments sends files with the e-mail, the same for every recipient of the call. content holds the bytes the caller already read. The module keeps the last path segment of filename, without line breaks, and passes the files to the @antelopejs/interface-email provider. A call carries at most 10 files adding up to at most 10 MiB, or it rejects with attachments_too_large before anything is sent or logged. The send log keeps each file's name, type, size and SHA-256 (json_attachments), never its bytes, so the dashboard refuses to send it again (409, no_replay_with_attachments): the caller, which holds the files, sends it again.
cc copies the same addresses on every message of the call. An address on the tenant's suppression list is left out, and the send log keeps the copied ones (json_cc). There is no bcc. replyTo sets where replies go, instead of the workspace's reply-to address.
RecordEmailEvent
import type { JsonObject } from "@antelopejs/interface-dms-mailing";
type SendEventType =
| "queued" | "sent" | "delivered" | "opened" | "clicked"
| "bounced" | "spam" | "failed" | "unsubscribed";
type SendStatus = SendEventType | "suppressed";
interface EmailEvent {
provider: string;
messageId: string;
type: SendEventType;
at?: Date;
details?: JsonObject;
}
declare function RecordEmailEvent(
tenantId: string,
event: EmailEvent,
): Promise<boolean>;
messageId is the provider's message ID, not the mailing sendId. The module matches the event by tenant and message ID. provider is neither an authorization boundary nor a matching key. at defaults to now. In this backend interface it is a Date, whereas the HTTP webhook takes an ISO string.
The call returns true when it records the event. It returns false for an unmatched message, a duplicate event, or a send that retention is retiring. A stable details.eventId deduplicates provider retries. Without it, deduplication needs the same explicit at, event type and serialized details, so an event with neither an event ID nor a timestamp is never deduplicated.
An accepted event updates the send's timeline, status and counters, publishes realtime and automation events, and can notify tenant owners of template problems. A hard bounce, a spam complaint or an unsubscribe suppresses the recipient, a test send only on a hard bounce, and a soft bounce never. A failed suppression write is logged without rejecting. Five activity conflicts in a row, storage failures or publication failures can reject, and a rejection does not prove that nothing was stored.
details.reason holds the provider's error text. details.bounceType is soft, transient or temporary, or hard or permanent, and without it the SMTP class of the reason decides. details.url and details.userAgent annotate engagement events. The call trusts its caller, which authenticates a relayed provider webhook first. The runtime webhook guide defines HTTP authentication and response bodies.
Ship templates as code
A project can declare its transactional templates from backend code instead of creating them in the dashboard. The content is written once, when the tenant is provisioned (see When to call). From then on it belongs to the tenant, and nothing replays it on a later boot. A newly created template claims its slug, is published as v1 with history, and is ready for SendTemplate when the call resolves.
DeclareTemplate, DeclareTemplateCategory, DeclareSender, DeclareWebhookSecret and ImportSends require an explicit tenantId, in TypeScript and at runtime. A missing, empty or blank one rejects before any write with invalid_template, invalid_category, invalid_sender, invalid_webhook_secret or invalid_import respectively, naming tenantId. No default applies, and an explicit DEFAULT_TENANT_ID is valid. It names the target but proves neither authorization nor provisioning, which the calling code enforces. SendTemplate and RecordEmailEvent do not run this check.
Names and labels in several languages
A template's name and a category's label are LocalizedText, one text per language, such as { en: "Welcome", fr: "Bienvenue" }. Each text is non-blank and at most 120 characters. The en text (LOCALIZED_TEXT_FALLBACK_LOCALE) is required, and a reader whose language has no text reads it. The module stores them as localized fields (@Localized). The dashboard shows, searches and sorts each user's own language, which the DMS frontend sends in the x-content-language header. A name is content, not a $ i18n key. A user who renames a template in the dashboard writes the language they work in.
DeclareTemplate
import type {
JsonObject,
LocalizedText, // Record<string, string>
TemplateContent,
VariableDefinition,
} from "@antelopejs/interface-dms-mailing";
interface TemplateDeclaration {
tenantId: string; // explicit authorized workspace, non-blank
slug: string;
name: LocalizedText; // { en: "…", fr: "…" }, en required
category?: string; // a category id of the workspace settings
content: TemplateContent;
variables?: VariableDefinition[];
testData?: JsonObject;
author?: string; // shown as "updated by" / "published by"; "system" when absent
}
type DeclarationOutcome = "created" | "kept";
interface DeclareTemplateResult {
templateId: string;
slug: string;
outcome: DeclarationOutcome;
version: number; // last published version, or 0; not a live-status guarantee
}
declare function DeclareTemplate(
declaration: TemplateDeclaration,
): Promise<DeclareTemplateResult>;
The slug is the caller's key. A slug the tenant does not have is created and published as v1 (created). A slug it has, declared before or made in the dashboard, is left as it is (kept), and nothing is written, so a retried provisioning neither creates a second template nor overwrites a user's work. Of two concurrent creations of one slug, the second returns kept.
The declaration follows the dashboard's rules. The slug matches ^[a-z0-9][a-z0-9-]*$ and has at most 64 characters. The name is non-blank, and the content and variable declarations are valid for the editor. The content has at least one locale and a subject in every locale, as Publish requires. author, when present, is non-blank and at most 120 characters. A creation also needs a category that the workspace settings declare, or no category. The validation codes are invalid_template, unknown_category, nothing_to_publish and empty_subject. Their messages name the invalid input, and none of them publishes a template.
A storage or attention-refresh failure can reject after the publication commits. The template row keeps the complete latest version, so history and version previews stay readable if the history insert fails, and a later publication repairs that row before replacing the snapshot. An indeterminate database mutation rejects without automatic retry or rollback, so a rejection does not prove that nothing changed.
DeclareTemplateCategory
import type { LocalizedText } from "@antelopejs/interface-dms-mailing";
interface TemplateCategoryDeclaration {
tenantId: string;
id: string; // lowercase letters, digits and dashes
label: LocalizedText; // { en: "…", fr: "…" }, en required
icon: string; // a Phosphor icon, such as "i-ph-repeat"
}
interface DeclareTemplateCategoryResult {
id: string;
outcome: "created" | "kept";
}
declare function DeclareTemplateCategory(
declaration: TemplateCategoryDeclaration,
): Promise<DeclareTemplateCategoryResult>;
Adds a category to the workspace settings (created). An id the settings hold, the defaults orders, account, billing, marketing and forms included, is left as it is (kept). The id matches ^[a-z0-9][a-z0-9-]*$, and the icon matches i-ph-<name>. A label that another category already has in the same language, in any letter case, rejects with invalid_category. Declarations of one workspace run one after another within one process. This queue is not a cross-process lock and does not serialize dashboard settings writes, so concurrent category and settings writers need outside coordination. A template declaration that names a category needs that category declared first.
DeclareSender
interface SenderDeclaration {
tenantId: string;
email: string; // the address e-mails are sent from
name?: string; // shown next to it
replyTo?: string; // replies go to the sender address when absent
}
declare function DeclareSender(declaration: SenderDeclaration): Promise<void>;
Writes the Sender section of the workspace settings, so a fresh workspace sends from the project's address instead of the provider's default, and the Overview does not ask for one. It is a plain write. The declared name, address and reply-to replace the stored ones, and an absent name or replyTo clears it. It belongs in Hook.TENANT_BEING_PROVISIONED, not on every boot, because the settings are the user's afterwards and a later call overwrites their changes. The address and reply-to follow the settings form's rules (an internationalized domain is stored in ASCII form), and a missing or invalid address rejects with invalid_sender, naming the field. Like DeclareTemplateCategory, it rewrites the whole settings row, so the two are awaited one after the other for a workspace.
DeclareWebhookSecret
interface WebhookSecretDeclaration {
tenantId: string;
secret: string; // 32 to 120 characters
replaceRotated?: boolean; // replace a secret the workspace owner set or rotated
}
type WebhookSecretOutcome = "set" | "unchanged" | "kept";
declare function DeclareWebhookSecret(
declaration: WebhookSecretDeclaration,
): Promise<{ outcome: WebhookSecretOutcome }>;
Sets the secret a provider sends with each webhook event, for a project that needs a known one, such as a demo whose screenshots show the settings page or a provider configured ahead of the workspace. A new workspace starts with a random secret, which a declaration replaces (set). Declaring the stored secret again changes nothing (unchanged), so the call is safe on every start. A secret the workspace owner typed in the settings or rotated there is theirs: a declaration leaves it in place (kept) unless it passes replaceRotated: true. A secret stored by a module release without DeclareWebhookSecret counts as the owner's.
The secret is never returned, and a refused one rejects with invalid_webhook_secret, naming the rule (secret too short or too long), never the value. The call writes the secret alone, so it does not overwrite settings another writer changes at the same time.
When to call
The declarations belong in a Hook.TENANT_BEING_PROVISIONED handler that the module registers in construct(). The DMS fires that hook once for each tenant, when the tenant is created. For the default tenant, it fires on the DMS start that creates the tenant, after every DATABASE_INITIALIZED handler has finished. A SaaS module fires it for each workspace it creates. The mailing tables are ready by then, so the calls do not wait for anything.
start() and DATABASE_INITIALIZED handlers run on every boot, so they are the wrong place. The content a workspace starts with is written once, then belongs to it.
import { Hook, RegisterHook } from "@antelopejs/interface-dms/hooks";
import {
DeclareTemplate,
DeclareTemplateCategory,
} from "@antelopejs/interface-dms-mailing";
async function declareMailingContent(tenantId: string): Promise<void> {
await DeclareTemplateCategory({ tenantId, id: "subscriptions", label: { en: "Subscriptions", fr: "Abonnements" }, icon: "i-ph-repeat" });
await DeclareTemplate({
tenantId,
slug: "subscription-renewed",
name: { en: "Subscription renewed", fr: "Abonnement renouvelé" },
category: "subscriptions",
content: {
locales: {
en: {
subject: "Your {{plan.name}} plan is renewed",
preheader: "",
blocks: [
{
id: "intro",
type: "paragraph",
text: "Hello {{customer.firstName}}, thank you for staying with us.",
align: "left",
visibleIf: null,
},
],
},
},
},
variables: [
{ path: "customer.firstName", type: "string", required: true },
{ path: "plan.name", type: "string", required: true },
],
testData: { customer: { firstName: "Sofie" }, plan: { name: "Pro" } },
author: "Release script",
});
}
export function construct(): void {
RegisterHook(Hook.TENANT_BEING_PROVISIONED, async ({ tenantId }) => {
await declareMailingContent(tenantId);
});
}
ImportSends
import type { EmailAddress } from "@antelopejs/interface-email";
import type { JsonObject, SendEventType } from "@antelopejs/interface-dms-mailing";
interface ImportedSendEvent {
type: SendEventType;
at: Date;
details?: JsonObject;
}
interface ImportedSend {
importId: string; // stable key chosen by the caller, at most 200 characters
templateSlug: string;
to: EmailAddress;
sentAt: Date;
locale?: string; // the workspace fallback locale when absent
variables?: JsonObject;
provider?: string;
providerMessageId?: string;
source?: string; // "import" when absent
isTest?: boolean;
events?: ImportedSendEvent[];
}
interface SendImport {
tenantId: string;
sends: ImportedSend[];
}
interface ImportSendsResult {
imported: number;
skipped: number;
sendIds: string[]; // one per entry, in the order given
}
declare function ImportSends(params: SendImport): Promise<ImportSendsResult>;
An import, not a send. SendTemplate stamps every send with the current time, and the Overview, the template statistics and the send log read sends by that date. History from another provider, or a demo data set, therefore cannot go through SendTemplate. ImportSends writes past sends with their own sentAt and events instead. Nothing is delivered, and no suppression, realtime update, automation or owner notification follows. An old provider's suppression list needs its own import.
Each entry names a template of the workspace, whose published version is recorded, and is keyed by its importId. An entry imported before is skipped untouched, so a retried provisioning imports nothing twice. The events can come in any order. The send's status, open and click counters, error and soft-bounce flag follow from them as if the webhook had reported them, and an entry without events is sent. An invalid entry rejects the whole call with invalid_import and names the field (sends.3.to). An unknown template rejects it with template_not_found. Both reject before anything is written. The log retention applies to imported sends like to any other. A send older than the workspace's retention (90 days by default) goes at the next nightly run, so a demo data set stays within that window.
Events are sorted by at and deduplicated before storage and counting, by details.eventId, or without it by type, timestamp and serialized details. The earliest sorted occurrence is kept. Import IDs are scoped by tenant, not provider, so IDs from several providers need a prefix.
Imports are not transactional. A storage failure can leave earlier entries committed, or an entry's events written before its send row. A retry with the same immutable payload, event order for equal timestamps included, completes it. Changing an interrupted entry's payload under the same importId is not supported. Retention removes the deduplication record with the send, so an old key can be imported again after a purge. The function records the template's current published version, not a version from the previous provider.
Template types
TemplateContent is { locales: Record<string, LocaleContent> }. Each LocaleContent has subject: string, preheader: string and blocks: Block[].
All blocks share BlockBase, with id: string, the discriminant type: BlockType, and visibleIf: Condition | null. Block is the union of the following exported interfaces. All listed fields are required. TextAlign is "left" | "center" | "right".
Interface / type | Additional fields |
|---|---|
HeroBlock / hero | imageUrl: string, alt: string |
HeadingBlock / heading | text: string, align: TextAlign, size: number |
ParagraphBlock / paragraph | text: string, align: TextAlign |
CodeBlock / code | text: string |
ListBlock / list | source: string, labelPath: string, valuePath: string |
TotalBlock / total | label: string, value: string |
ButtonBlock / button | text: string, href: string, align: TextAlign |
IfBlock / if | condition: Condition, children: Block[], elseChildren: Block[] | null |
DividerBlock / divider | None |
FooterBlock / footer | text: string, unsubscribeLabel: string, preferencesLabel: string |
Condition has path: string, operator: ConditionOperator, and value: string. Operators are truthy, falsy, eq, ne, gt, and lt. VariableDefinition has path: string, type: VariableType, and required: boolean. Variable types are string, text, number, money, date, url, boolean, and array.
Values are written in the render locale. A money value { value, currency } holds the amount in the currency's minor unit and an ISO 4217 code, so { value: 987420, currency: "EUR" } reads "€9,874.20" in English and "9 874,20 €" in French. It and a Date, a long date in the server's time zone, are formatted wherever they appear, list rows included. An ISO 8601 string is written as a date only at a path the template declares date. A day (2026-11-14) becomes that calendar day, and a moment becomes its day in the server's time zone. Other values, numbers and strings the caller already formatted included, are written as given.
The extending guide covers template setup, footer variables and automations. The runtime guide covers installation, configuration and HTTP routes.