Extending
Send templates from code, ship templates as code, import past sends, mail DMS notifications, report provider events, relay a provider webhook, and plug Mailing into automations.
Other modules call Mailing through the separately published @antelopejs/interface-dms-mailing interface. Add it as a dependency, and AntelopeJS connects your calls to the module that implements it.
pnpm add @antelopejs/interface-dms-mailing
Send from code
First, publish an order-confirmation template with an order.total variable, and pass any other variable it requires. Use an authorized tenant ID and, while you develop, an inbox you control. The example sends a real e-mail.
import {
SendTemplate,
} from "@antelopejs/interface-dms-mailing";
// Render a live template and send it.
const result = await SendTemplate("order-confirmation", {
tenantId,
to: [{ email: "[email protected]", name: "Sofie" }],
locale: "fr",
variables: { order: { total: "48.00" } },
source: "checkout",
});
const outcomes = result.results ?? [result];
Mailing › Sends shows the recipient, template version and locale used. outcomes holds one result per recipient. sent means the provider accepted the e-mail, not that it reached the inbox. Report later events through the webhook contract or RecordEmailEvent.
Read result.results before you retry a recipient. For several recipients, the top-level status is the worst one and error the first error, while sendId and messageId belong to the first recipient. A recipient on the suppression list gets no e-mail and a suppressed result. Do not retry it. The consumer reference defines parameters, aggregation, failures, provider events and template types.
content sends an alternate body for an existing template without saving or publishing it. isTest: true marks a test send. Its subject starts with [TEST] , it uses the template's draft when there is one, and production figures leave it out.
Attach files
attachments sends files with the e-mail, such as the PDF of an invoice. Pass the bytes you already hold:
const pdf = await readInvoicePdf(invoiceId); // a Buffer
await SendTemplate("invoice-sent", {
tenantId,
to: "[email protected]",
variables: { invoice: { number: "2026-001" } },
attachments: [{ filename: "invoice-2026-001.pdf", contentType: "application/pdf", content: pdf }],
});
- Every recipient of the call gets the same files. A file name keeps its last path segment, without line breaks.
- A send carries at most 10 files, adding up to at most 10 MiB. Over that, the call rejects with
codeattachments_too_largebefore anything is sent or logged. - Mailing › Sends lists each file's name and size, and keeps its SHA-256, never its bytes. A send with files cannot be sent again from the dashboard: send it again from your code.
Copy and reply to
cc copies addresses on every message of the call, and replyTo sets where replies go for this send instead of the workspace's reply-to address:
await SendTemplate("invoice-sent", {
tenantId,
to: "[email protected]",
cc: ["[email protected]"],
replyTo: "[email protected]",
});
- A
ccaddress on the suppression list is left out. The send log keeps the copied addresses (json_cc). - There is no
bcc.
Amounts and dates
Pass an amount or a date as a value, and the e-mail writes it in the locale of the send.
await SendTemplate("quote-sent", {
tenantId,
to: "[email protected]",
locale: "fr",
variables: {
// In the minor unit of the currency, like the DMS's money parameters.
quote: { total: { value: 987420, currency: "EUR" }, validUntil: "2026-11-14" },
},
});
// "9 874,20 €" and, with quote.validUntil declared `date`, "14 novembre 2026".
- A money value is
{ value, currency }, the amount in the currency's minor unit (cents forEUR) and an ISO 4217 code. It is written as currency wherever it appears, list rows included. An unknown code writes a plain number. - A
Dateis written as a long date ("14 novembre 2026" infr) wherever it appears, in the server's time zone. - An ISO 8601 string is written as a date at a path the template declares
date. A day (2026-11-14) becomes that calendar day, a moment (2026-11-14T09:30:00Z) its day in the server's time zone. - Any other value is written as given, already formatted strings included, so existing templates keep their output. A
numberis not reformatted, so an order number stays12345. variablesis typedTemplateVariables. It accepts strings, numbers, booleans,null,Dateand money values, and lists and records of the same. A class instance or a function does not compile. A token path reads the keys a record owns, a list's elements by index, and a list'slength.
Formatting happens at render time (sends, previews, the sent e-mail view). The send log keeps the values as passed, and the editor's Data mode shows the test data as written.
Ship templates as code
A project, or a demo, can ship its transactional templates with its code. Once, when the workspace is provisioned, DeclareTemplate creates the template under your slug and publishes it as v1, so SendTemplate can use it at once. From then on the template belongs to the workspace. Nothing writes it again, and declaring a slug the workspace already has leaves it as it is (kept).
DeclareTemplateCategory adds the categories those templates name to the workspace settings, and an id the settings already hold stays as it is. DeclareSender writes the Sender section (from name, address, reply-to), so a fresh workspace sends from the project's address. DeclareWebhookSecret sets the secret the provider sends with its webhook events, and keeps one the workspace owner set or rotated in the settings unless you pass replaceRotated: true.
All three need an explicit, non-blank tenantId, here an authorized workspace. They create nothing for an implicit default tenant, but an explicit DEFAULT_TENANT_ID is valid.
import {
DeclareSender,
DeclareTemplate,
DeclareTemplateCategory,
} from "@antelopejs/interface-dms-mailing";
export async function declareMailingContent(tenantId: string): Promise<void> {
await DeclareSender({ tenantId, name: "Acme", email: "[email protected]" });
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" } },
});
}
A template's name and a category's label hold one text per language, stored as localized fields. Each user reads them in their language, and the templates table searches and sorts that text. The en text is required, and a language without a text shows it. A user who renames the template in the dashboard writes the language they work in.
Template and category declarations validate like the dashboard. Invalid input rejects with a code and the field at fault, and publishes nothing. A category a user removed does not invalidate the declaration of an existing template, which returns kept before the category check.
Call the declarations from a Hook.TENANT_BEING_PROVISIONED handler registered in your module's construct(). The DMS fires it once per tenant, when the tenant is created. For the default tenant, that is on the start that creates it, after every DATABASE_INITIALIZED handler has finished. A SaaS module fires it for each workspace it creates. Never call them from start() or DATABASE_INITIALIZED, which run on every boot. The consumer reference gives the exact rule and outcomes.
A storage failure can reject after publication. The template row keeps the latest version readable, and a later publication repairs its separate history row. Category declarations of one workspace are serialized within one process only.
Import past sends
SendTemplate stamps a send with the current time, and the Overview, template statistics and send log read sends by that date. To bring in another provider's history, or give a demo figures to show, ImportSends writes past sends with their own date and events.
import { ImportSends } from "@antelopejs/interface-dms-mailing";
// This function is called with an authorized, provisioned workspace id.
export async function importHistory(tenantId: string): Promise<void> {
const sentAt = new Date(Date.now() - 3 * 86_400_000);
await ImportSends({
tenantId,
sends: [
{
importId: "brevo-48213", // the old provider's id, so importing again skips it
templateSlug: "subscription-renewed",
to: { email: "[email protected]", name: "Sofie" },
sentAt,
events: [
{ type: "delivered", at: new Date(sentAt.getTime() + 60_000) },
{ type: "opened", at: new Date(sentAt.getTime() + 3_600_000) },
],
},
],
});
}
An import is not a send. Nothing is delivered, and no suppression, realtime update, automation or notification follows. Status and counters follow from the events as if the webhook had reported them, and an entry without events is sent. Repeated events are dropped by details.eventId, or without one by equal type, timestamp and serialized details.
Retry a failed import with the same payload. A batch can be partly committed, and an importId is not an update key. Import IDs are scoped to the tenant, so prefix them by provider when combining histories. Imported sends follow the log retention, so keep a demo data set within it (90 days by default). See the consumer reference.
What a recipient receives
Every e-mail goes out as an HTML part and a plain-text part that the module generates from the same blocks (multipart/alternative). The HTML carries a viewport meta tag.
Header logo
The header logo is the DMS branding's branding.logo.email.light, else branding.logo.default.light, made absolute with the DMS clientBaseUrl. Mail clients in dark mode get branding.logo.email.dark. The logo is left out, rather than shown broken, when:
- The URL is not
httporhttps. - The host is
localhost, a private IP, or ends in.local,.localhostor.internal. - The logo is an SVG, which Gmail and Outlook refuse.
The editor canvas draws the same footer, and a header from branding.logo.default.light only, with the same checks.
Footer links
Footer links are system variables. A filled unsubscribe or preferences label, or a {{unsubscribeUrl}} or {{preferencesUrl}} token anywhere, declares unsubscribeUrl or preferencesUrl as a url variable, required in the marketing category. The editor shows them in the Variables tab, and the template drawer in its contract and its Call it from code snippet.
Pass the URLs in variables at send time:
await SendTemplate("newsletter-october", {
tenantId,
to: "[email protected]",
variables: {
unsubscribeUrl: `https://app.example.com/unsubscribe/${token}`,
preferencesUrl: "https://app.example.com/preferences",
},
});
A link whose URL is missing is dropped, and an empty label removes the link. For a marketing template, a missing required URL has these effects:
- A manual real send is refused.
- When Missing variables is set to refuse, every send is refused, except a test send, which never waits for the URL.
The starters get a footer with a legal line and no unsubscribe or preferences link. So does a new template in a category other than marketing. A new template without a category keeps the links.
DMS notifications by e-mail
Mailing registers the DMS notifications' e-mail channel at start-up. The DMS then hands it every notification it stores in a user's feed when the notification's subject offers e-mail (email on NotificationSubject) and the user has it on under Settings › Account › Notifications. See the DMS page on the e-mail channel for how a subject offers e-mail.
What the recipient gets
Each notification goes through the workspace's Notification template (slug dms-notification), like a SendTemplate call. The send log, the suppression list, the sender settings and the provider webhook apply to it, and its sends are labelled dms-mailing:notification.
| Variable | Value |
|---|---|
notification.title | The notification's title. It is also the subject. |
notification.description | The notification's description. |
notification.url | The notification's link, made absolute with the DMS clientBaseUrl. Empty, and the button hidden, when there is no link or it is not http or https. |
preferencesUrl | The notification preferences page, <clientBaseUrl>/settings/user/notifications, where the recipient turns the e-mail off. |
The first notification mailed in a workspace declares the template with DeclareTemplate, in the workspace's fallback locale (French copy for a French locale, English otherwise). From then on the template is the workspace's: reword it, translate it or restyle it in the editor, and the module never writes it again. An archived template stops the e-mails. A deleted one is declared again by the next notification.
When nothing is mailed
The channel skips a notification, and logs why at debug level, in these cases:
| Case | Why |
|---|---|
The send names no workspace (SendOptions.tenantId) | A workspace is what the sender, the template and the suppression list belong to. Send with toUser(userId, { tenantId }). |
The title or the description is a $ translation key | Only the dashboard translates those keys. The channel logs a warning. Send texts in the recipient's language for a subject that offers e-mail. |
| The user does not exist, has no address, or has not validated it | Mail goes to validated addresses only. |
| The user is not a member of that workspace any more | A platform owner is always mailed. |
A suppressed address gets no e-mail: its send is logged suppressed, as for SendTemplate. The DMS hands each stored notification to the channel once, so each one is mailed at most once. The channel returns to the DMS at once and sends in the background, so a notification send never waits for the provider.
Webhook contract
The module accepts provider events in one generic format. Post them to this URL:
POST <origin>/api/mailing/events/<provider>/<tenantId>
Settings › Provider & webhook shows it, ready to copy. <origin> is the DMS clientBaseUrl, else its apiBaseUrl, else the server's own origin. <provider> is a free label recorded with the event. The settings use the configured provider's name, lower-cased, with each run of other characters than letters and digits replaced by -, or provider without a name. <tenantId> names the workspace.
Every request carries the workspace's secret, shown in the same settings, in the x-mailing-webhook-secret header. Rotating it invalidates the old one at once. The body is JSON:
curl -X POST https://dms.example.com/api/mailing/events/postmark/<tenantId> \
-H "Content-Type: application/json" \
-H "x-mailing-webhook-secret: <secret>" \
-d '{"messageId":"<provider message id>","type":"bounced","at":"2026-09-09T10:00:00.000Z","details":{"reason":"550 5.1.1 No such user","bounceType":"hard","eventId":"<provider event id>"}}'
| Field | Meaning |
|---|---|
messageId | The ID the provider returned for the e-mail (the send's providerMessageId). Required. |
type | queued, sent, delivered, opened, clicked, bounced, spam, failed or unsubscribed. Required. |
at | When it happened, as an ISO date. Now by default. |
details.reason | The provider's words (550 5.1.1 No such user), shown in the log. |
details.bounceType | soft, transient or temporary, or hard or permanent. Without it, the SMTP class of reason decides (4xx is soft). A hard bounce suppresses the address. |
details.eventId | The provider's event ID. A retried webhook with the same ID is ignored. |
details.url, details.userAgent | Shown on the click and open steps. |
The answer is 200 {"recorded": true}, or {"recorded": false} when no send carries the message ID, the event was already recorded, or retention is deleting the send. The settings' test event gets {"recorded": false, "test": true}.
When an event is recorded:
- It is appended to the send's timeline.
- The status moves forward only, in the order
queued,sent,delivered,opened,clicked,unsubscribed,spam, thenbouncedorfailed. Afterfailed, an event fromdeliveredon replaces it, because a provider failure is often a retried deferral. - A hard bounce, a spam report or an unsubscription puts the address on the suppression list. On a test send, only a hard bounce does.
- When at least 3 of a template's real sends in the last hour bounced, failed or were reported as spam, and they make at least 5% of its sends, the tenant owners get one DMS bell notification per template and clock hour.
A refused call gets a readable JSON body for the relay's logs:
| Status | reason | Why |
|---|---|---|
403 | missing_secret | No x-mailing-webhook-secret header. |
403 | bad_secret | The header does not match the workspace's secret, or the workspace has no mailing settings yet (a send, a declaration or opening the settings creates them). |
400 | invalid_event | The secret is right, but the body is not a JSON event. |
{ "error": "webhook_refused", "reason": "bad_secret", "message": "The x-mailing-webhook-secret header does not match …" }
The secret is checked before the body, so a caller without it learns nothing of the format. Settings › Provider & webhook › Webhook status shows the last event received (when, its type, the provider label, whether it matched a send) and the last refused call (when, and why). A refusal for a workspace without mailing settings is not recorded.
Send a test event posts a delivered test event from the backend to the URL shown, with the stored secret, and waits up to 10 seconds. It proves the server reaches the URL and that the secret and format are right. It touches no send, because its message ID is dms-mailing-webhook-test.
Relaying a provider
Providers such as Postmark, SES through SNS, Mailgun, SendGrid and Resend post their own format, and most cannot add a custom header. Put a small relay in between. It authenticates the provider's call by the provider's own means, translates each event and forwards it with the secret. A sketch for Postmark:
const TYPES: Record<string, string> = {
Delivery: "delivered",
Open: "opened",
Click: "clicked",
Bounce: "bounced",
SpamComplaint: "spam",
SubscriptionChange: "unsubscribed",
};
export async function relayPostmark(event: PostmarkEvent): Promise<void> {
const type = TYPES[event.RecordType];
if (!type) return;
await fetch(MAILING_WEBHOOK_URL, {
method: "POST",
headers: {
"content-type": "application/json",
"x-mailing-webhook-secret": MAILING_WEBHOOK_SECRET,
},
body: JSON.stringify({
messageId: event.MessageID,
type,
at: event.ReceivedAt ?? event.DeliveredAt ?? event.BouncedAt,
details: {
reason: event.Details ?? event.Description,
bounceType: event.Type === "SoftBounce" ? "soft" : "hard",
eventId: String(event.ID ?? ""),
url: event.OriginalLink,
userAgent: event.UserAgent,
},
}),
});
}
A module of the same project can skip HTTP and call RecordEmailEvent(tenantId, event). A provider or relay posts through the dashboard's URL, a public endpoint the module declares (AddFrontendModule({ publicEndpoints })) with the x-mailing-webhook-secret header passed on, or straight to the API on apiBaseUrl when reachable. The path and header are the same.
Automation nodes
Registered against the optional @antelopejs/interface-dms-automation. They do nothing when no module implements it.
| Node | Id | Purpose |
|---|---|---|
| Action | mailing.send-template | Renders a live template and sends it. Inputs tenantId, slug, to (required, one address or a list), locale, variables, source (automation:<procedure id> by default). |
| Trigger | mailing.email-event | Fires on provider events. Config types filters the event types, and empty fires on every one. |
Permissions and realtime
| Id | Kind | What it gates |
|---|---|---|
mailing.send | Permission (depends on the Sends page) | Each route that reaches recipients (test send, real send, send again, send the failures again) |
mailing:sends | Realtime topic | Published on every new send and event, to that workspace only. The Overview and Sends pages subscribe to it. |
Module permissions are owner-only. The DMS grants mailing.send and the mailing pages only to the platform owner, who holds every permission. A role that lists them, made in the roles settings or through the roles API, still gets a 403 on the mailing pages and routes, so mailing.send cannot be granted to a member.
The module also adds templates.json, template-versions.json, settings.json and suppressions.json to the workspace data export (RegisterTenantDataExportContributor).
Retention internals
The sweep runs daily at 03:15 server time. It retires a send only when its creation time, latest event time and latest ingestion time all precede the tenant's retention cutoff. Queued sends stay active. Retirement closes a send to provider events for good, then the sweep deletes its events and finally the send. A failed cleanup leaves the retirement marker for a later sweep to resume.
Concurrent sweeps need no shared cron lock. Send writes use the database interface's Table.atomicMutation revision contract. Retirement rechecks the send's age and activity before comparing its revision, and concurrent webhook activity changes that revision, so a stale candidate is not retired. A known webhook conflict rereads the send and recomputes counters, up to 5 attempts. An unknown write outcome fails without retrying or reporting a deletion.
This needs a database interface and adapter that implement Table.atomicMutation. Generic filtered updates and deletes are no substitute. Every send is inserted with a revision, stored in the declared revision column.
Each sweep inspects at most 20,000 send candidates per tenant and reports only actual deletions. It also removes orphan events, left by a writer that inserted an event for a send deleted meanwhile, or by an import interrupted between an entry's events and its send row. That pass scans the event table in keyset pages of 500 rows, with a parent lookup per distinct send in each page. The send limit does not cap it.
A live send gets a new random ID and is written before its events. An imported send's ID derives from the tenant and its importId, so a purged import key comes back under the same ID. Neither pass deletes templates or files. A workspace without mailing settings skips both.