ObjectStackObjectStack

Email templates — merge fields and layouts

Author a localizable outbound mail template as metadata, and reach it from a flow's notify node or from services.email.

An email template is a named, localizable subject + body that lives as metadata. Your app declares it; the email service resolves it by (name, locale) at send time and renders its {{placeholders}} against a per-send data payload.

Authoring and sending are two different surfaces. This page covers authoring a template and the ways to reach one. The service that delivers it — send, sendTemplate, renderTemplate and their typed error codes — is documented in services.email.

import { defineEmailTemplateDefinition } from '@objectstack/spec';

export const TaskDoneEmail = defineEmailTemplateDefinition({
  name: 'crm.task_done',
  label: 'Task Done Notification',
  locale: 'en-US',
  subject: 'Task done: {{task.title}}',
  bodyHtml: '<p>The task <strong>{{task.title}}</strong> on {{project.name}} was marked done.</p>',
  bodyText: 'The task {{task.title}} on {{project.name}} was marked done.',
  variables: [
    { name: 'task.title', type: 'string', required: true, description: 'Task title' },
    { name: 'project.name', type: 'string', required: false, description: 'Project name' },
  ],
});

Declare it in the emailTemplates collection of defineStack(), or put it in a *.email-template.ts (or .yml / .json) file anywhere in the package:

export default defineStack({
  // …
  emailTemplates: [TaskDoneEmail],
});

⚠️ The canonical schema is EmailTemplateDefinitionSchema. A legacy EmailTemplateSchema was demoted and then removed outright; consumers historically wired the wrong one. If an example you find elsewhere sets body, html, content, from or title, it is written against the wrong shape — the real slots are bodyHtml, bodyText, fromOverride and subject.

name is a dotted namespace, not a title

name is the identifier sendTemplate({ template }) looks up, and the schema enforces dotted snake_case (auth.password_reset, crm.large_deal_won). Prefix it with your app or domain — the namespace is what keeps a tenant's templates from colliding with the built-in authentication mail.

The namespace is also how you group templates: there is no separate category key. category and isSystem were removed (ADR-0049 enforce-or-remove) because nothing read either one, and the schema now refuses both with a migration note. A built-in template is the email plugin's declaration, which a Studio save overrides for the environment and discarding that save restores.

active: false makes sendTemplate return TEMPLATE_INACTIVE rather than silently sending nothing.

Placeholders

Subject and both bodies are rendered by a deliberately tiny mustache-style renderer. Escaping follows the face: only bodyHtml is markup, so only bodyHtml HTML-escapes its values. subject and bodyText are plain text and render every value verbatim — an & in a link stays &, so the plain-text part never needs triple braces.

  • {{path.to.value}} — dotted-path lookup against the send's data object, HTML-escaped in bodyHtml, verbatim in subject and bodyText.
  • {{{path.to.value}}} — the same value, not escaped even in bodyHtml. It is admitted in exactly one place: a variable declared with type: 'url', written as the whole value of a double-quoted href (<a href="{{{reset_url}}}">).
  • {{ order.total | currency:EUR }} / {{ ts | datetime }} — an optional formatter from the shared formula whitelist, so money and dates render the same way they do in-app. datetime honours the reference timezone the caller passes; calendar-day date values are timezone-naive.

The formatter is one word, optionally followed by : and its argument. {{ due | date-long }} and {{ x | two words }} are refused by the same doors and rule, naming the hole and the shape, where the renderer used to print the hole to the reader as written. Mail reads a formatter part exactly as in-app templates do: {{ amount | currency :EUR }} is currency with EUR, and default:'n/a' and default:"n/a" both supply n/a. Brace text with no path before the | ({{ not a path }}, {{ | upper }}) is not a hole and stays as written. A template stored before this rule fails its render with TEMPLATE_INVALID and sends nothing; republish it with the formatter written in that shape.

The formatter is one the whitelist names. {{ amount | curency:EUR }} is refused by os validate, os build, os lint and the metadata publish door (email-template-hole-grammar, a 422 INVALID_METADATA at the publish door), naming the hole and listing the known formatters (MAIL_TEMPLATE_FORMATTERS, exported from @objectstack/formula). A template stored before this rule fails its render with TEMPLATE_INVALID and sends nothing, rather than print the raw value (1234.5) where a formatted one was meant; republish it with the name corrected.

A default is literal text; to read another variable, compute it in the flow. {{ person_name | default:'Customer' }} prints Customer when the send's person_name is empty. The argument is never read as a path: {{ person_name | default:first_name }} prints the word first_name, not the send's first_name. There is no syntax that falls back to another variable — decide the value in the flow that sends the template and pass it under the hole's own name. An unquoted default argument that reads like a variable path (a dotted or @-marked path, a snake_case name, or a name the template uses as a variable) draws the email-template-default-reads-as-path warning from os validate, os build, os lint and the metadata publish door; quote the argument (default:'first_name') when the text itself is meant.

One formatter per hole. {{ amount | default:0 | number:2 }} is refused by os validate, os build, os lint and the metadata publish door (email-template-hole-grammar): a hole takes one formatter, and there is no chaining. Decide the value in the caller that supplies the data — a default, a second format — and pass the finished value as its own variable.

The currency argument is a literal code or a marked path. A currency argument is either a literal ISO 4217 code in three capital letters (currency:EUR) or, in a mail template only, @ followed by a path into the send's data whose value is such a code (currency:@currency_code). currency with no argument formats in the tenant default currency (below).

The marked path is how one template shows each record's amount in that record's own currency:

subject: 'Instalment overdue: {{ planned_amount | currency:@currency_code }}',

With data holding planned_amount: 1234.5 and currency_code: 'EUR' it renders €1,234.50 in en-US; with currency_code: 'CNY' it renders CN¥1,234.50. The value at the path must be the code in capitals, as stored: a missing or null value, a lowercase code (eur) or anything else makes the render fail with TEMPLATE_INVALID, naming the template, its locale, the hole and the value. The amount is never formatted in a default currency in its place.

A bare argument is never read as a path: currency:currency_code is refused, and so are a lowercase or empty code, a quoted path and an @ with no path after it. os validate, os build, os lint and the metadata publish door refuse these (email-template-hole-grammar, a 422 INVALID_METADATA at the publish door), naming the hole and the rule. When the template declares variables, the same doors also refuse a marked path that none of them declares (a variable contract declares contract.currency_code).

The @ form belongs to mail templates. In-app template text (flow notifications, action and bulk-action copy) takes a literal code only and refuses currency:@path by name.

currency with no argument formats in the tenant default currency. {{ amount | currency }} formats in the organization's default currency, the localization.currency setting (Setup → Localization) that currency fields and dashboards read too. The notification channels hand it to every templated send; code that calls sendTemplate or renderTemplate itself passes it as currency. When no default currency reaches the render, the render fails with TEMPLATE_INVALID, naming the template, its locale and the hole, and nothing is sent: the amount is never formatted in US dollars or any other guess. Set the organization's default currency, or name the currency in the hole: a literal code (currency:EUR) or a marked path to it (currency:@currency_code).

option prints a select value as its option's label. A flow notice is filled once per run and then sent to each recipient in their own locale, so a select field's value reaches the template as it is stored (needs_analysis). option names the object and field the value belongs to, written bare as object.field, and the hole prints that option's label in the recipient's language:

subject: 'Deal stalled at {{ stage | option:opportunity.stage }}',

The renderer builds the label table for each object.field the template names, in the locale it renders that recipient's copy in. A multi-select value prints the label of each of its values, joined with , , and a value that is not one of the field's options prints as stored. A render that reaches an option hole with no label table for its field is refused and nothing is sent: the stored value is never printed where the label was promised. os validate, os build, os lint and the metadata publish door refuse an option hole whose object resolves to nothing (the app's own objects, those another package of the same artifact provides, and the platform's objects all resolve), whose field that object does not have, or whose field declares no options (email-template-hole-grammar, a 422 INVALID_METADATA at the publish door), and an argument that is not a bare object.field: a quoted one (option:'opportunity.stage'), a field with no object (option:stage) or a marked path (option:@stage_ref). An object none of those carries whose name has a platform prefix (sys_, cloud_, ai_) gets a warning at os validate, os build and os lint, its field not judged, because a package outside the app may register it; the publish door judges against every object the deployment serves and refuses it there if none of them is that object. A template saved into a package is judged against that package's closure (its own objects, the objects of the packages its manifest declares in dependencies, and platform objects): an object outside it is refused, and the fix is to declare the dependency. option belongs to mail templates: in-app template text (flow notifications, action and bulk-action copy) refuses it as a formatter it does not know.

Where a hole may sit in bodyHtml. The renderer's escaping is right for element text and for a quoted attribute value that holds plain text, so those are the supported placements for {{path}}. A hole anywhere else — inside a script or style element, a comment, a tag outside any attribute value, an unquoted attribute value, an attribute read as a URL (href, src, …), an event handler, a style or markup, or SVG or MathML content — is refused by os validate, os build, os lint and the metadata publish door, and so is a {{{path}}} hole outside the href shape above. The refusal (email-template-hole-placement, a 422 INVALID_METADATA at the publish door) names the placement and the supported ones. A template already stored keeps sending; it is judged the next time it is published.

Three properties of the renderer to author around:

  • A missing placeholder renders as an empty string. Declare a variable required (below) if absence should be an error instead, or give the hole a literal default ({{ name | default:'there' }}). A default is literal text; to read another variable, compute it in the flow.
  • A hole the authoring rules refuse is refused at render too. A template stored before a rule existed is judged at its next publish; until then sendTemplate and renderTemplate fail with TEMPLATE_INVALID, naming the template and the hole, rather than send a wrong value.
  • There are no loops, conditionals or partials. A template is a data-only rendering by design; branching belongs in the caller, which passes in the already-decided values.

What every template can read: appName and baseUrl

Every send's data is laid over a default context the deployment supplies, so two keys are always there unless the send passes its own:

  • {{appName}} — the product name (OS_APP_NAME, then config.email.appName, then config.email.defaultTemplateContext.appName, then the stack's appName, then ObjectStack).
  • {{baseUrl}} — the address this deployment is reached at, never ending in a slash: OS_AUTH_URL, then OS_BASE_URL, then config.email.defaultTemplateContext.baseUrl, then the local http://localhost:<port>. It is the same address os serve resolves for the deployment, so set OS_AUTH_URL (or OS_BASE_URL) to the public origin and the mail's links follow it.

baseUrl is only the prefix: the path after it is your application's own — a record page or an app route, whatever your Console or front end serves:

bodyText: 'Deal {{deal.name}} is yours: {{baseUrl}}/crm_deal/{{deal.id}}',

That renders https://crm.example.com/crm_deal/42, which mail clients show as a link. In bodyHtml the same text may sit in element text, but not inside an href: a hole in a URL attribute is refused by the placement rule above, and {{{baseUrl}}}/… is not the whole-value url shape either. For an <a> link in bodyHtml, pass the whole URL as a variable declared type: 'url' (<a href="{{{deal_url}}}">). A send that passes its own baseUrl in data overrides the default.

Declared variables

variables documents the holes: each entry has a name (the path as written in the placeholder), a type (string | number | boolean | date | url | user | record, default string), an optional description shown as an authoring hint in Studio, and required (default false).

required is enforced at send time: if a declared-required variable is absent from data, the send fails with MISSING_VARIABLES instead of mailing a sentence with a hole in it. The other fields are authoring metadata — the renderer does not coerce by type.

required is also read at authoring time. A flow's notify node that names a template the app declares, and whose templateData provably does not supply one of the variables a locale member of it declares required, draws the notify-template-variable-missing warning from os validate, os build and os lint. A value computed per run (a CEL value envelope) counts as supplied, and so do appName, baseUrl and the keys of the stack's own email.defaultTemplateContext. A variable a host supplies through a default template context set in code is outside what the check can see, which is why it warns rather than refuses.

Locale resolution

Rows sharing a name and differing in locale form one bundle. locale is a BCP-47 tag and defaults to en-US.

import { defineEmailTemplateDefinition } from '@objectstack/spec';

export const passwordResetEn = defineEmailTemplateDefinition({
  name: 'auth.password_reset',
  label: 'Password Reset',
  locale: 'en-US',
  subject: 'Reset your password',
  bodyHtml: '<p>Use <a href="{{{reset_url}}}">this link</a> within {{ttl_minutes}} minutes.</p>',
  variables: [{ name: 'reset_url', type: 'url', required: true }],
});

export const passwordResetZh = defineEmailTemplateDefinition({
  name: 'auth.password_reset',
  label: 'Password Reset',
  locale: 'zh-CN',
  subject: '重置您的密码',
  bodyHtml: '<p>请在 {{ttl_minutes}} 分钟内使用<a href="{{{reset_url}}}">此链接</a>。</p>',
  variables: [{ name: 'reset_url', type: 'url', required: true }],
});

The template name is matched exactly; only the locale member is resolved, by the ladder below. Every rung of it loads one row at one tag exactly, so en and en-US stay two distinct rows of the bundle: folding chooses which row is read, it never merges two. Resolution is deterministic, never "whichever row the store yields first". The ladder of record is SendTemplateInput.locale in packages/spec/src/contracts/email-service.ts; this section copies it.

A call that names a locale, over the built-in registry template loader (the one EmailServicePlugin wires), walks:

  1. this locale, folded against the locale tags the template's bundle carries by resolveBundleLocale (@objectstack/spec/system, the BCP-47 fold plugin-email imports rather than copying): exact, then case-insensitive (zh-cn → zh-CN), then the same platform locale table language (zh-TW → a zh-Hant row, zh → a zh-CN row, in any tag order), then base language (en-GB → en), then variant expansion (zh-TW → zh-CN when the bundle has no Traditional row), the first match in ascending tag order;
  2. the stack's declared fallback locale, as II18nService.getFallbackLocale() answers it (i18n.fallbackLocale, else defaultLocale), folded the same way. A host whose i18n service declares none, or that has no i18n service, skips this rung;
  3. en-US, exactly;
  4. none of them lands on a row: TEMPLATE_NOT_FOUND, which is permanent.

A rung that resolves to a tag already tried is skipped. A replacement TemplateLoader keeps the exact ladder: this locale matched exactly, then en-US, then TEMPLATE_NOT_FOUND, with no fold and no declared fallback.

A call that omits locale keeps its own ladder. The service's part of it holds over any loader: no fold, no declared fallback, and en-US first, exactly, so "no locale" means the default rather than an arbitrary member. When that misses, the service asks the loader for its own no-locale answer. The built-in registry loader answers the bundle's en-US member, else its lowest locale tag, so a single-locale bundle keeps rendering and does so identically on every boot; a replacement TemplateLoader gives its own deterministic best answer for the name.

Reaching a template

From a flow's notify node

A notify node has two mutually exclusive content paths, and the template one is the localizable path:

{
  id: 'tell_owner',
  type: 'notify',
  label: 'Notify Owner',
  config: {
    recipients: { dialect: 'cel', source: 'record.owner_id' },
    template: 'crm.task_done',
    templateData: { task: { dialect: 'cel', source: 'record' } },
  },
}
  • template names the bundle. The delivery path resolves (name, locale) among the email templates at delivery time and renders subject/body from that member. The locale is resolved per recipient, after fan-out: the recipient's own sys_user.locale when set, else the deployment default (II18nService.getDefaultLocale()) — so two recipients of one notification whose locale columns differ receive different members of the same bundle (maintainer ruling, 2026-09-01). A recipient whose column is empty or unset always falls back to the deployment default; no value ever dead-letters a delivery. A payload.locale set by the producer — the pre-ruling single value for the whole notification — is not consulted. The same chain serves the inbox channel's template path and the sys_notification_template rows the email and SMS channels render, so one notification cannot arrive in two languages across channels.
  • Inline title / message are the non-localizable path: raw strings sent to every recipient verbatim. The two paths cannot be combined on one node — the schema refuses the ambiguous shape rather than letting a runtime precedence rule silently drop one.
  • templateData keys are the root names the template's holes read, never paths: {{task.title}} reads title under the key task, so the example passes the triggering record as task. A key written 'task.title' is one name that no hole reads, and a template that requires task.title refuses the send with MISSING_VARIABLES.
  • templateData values are value slots: a CEL value envelope — { dialect: 'cel', source: 'record.title' } — is evaluated per run and its value handed to the template, and any other value is handed on as written. A single-brace {record.x} token is refused there. template itself is read raw — it is a static metadata cross-reference, and a {token} there is forwarded verbatim, never resolved.

From code

Resolve the service and call it:

const email = ctx.getService('email');

await email.sendTemplate({
  template: 'crm.task_done',
  to: 'owner@example.com',
  locale: 'zh-CN',
  data: { task: { title: 'Ship the release' }, project: { name: 'Apollo' } },
});

Use renderTemplate({ template, data, locale }) when you want the rendered { subject, html, text } without sending anything — the same resolver and the same locale ladder, exposed so non-email channels render localized content instead of duplicating it.

How an authored template reaches the sender

Worth knowing, because it explains what an administrator can and cannot change.

sendTemplate resolves the email_template metadata itself, by (name, locale), at every send — the same item GET /api/v1/meta/email_template serves. Three populations live there: the built-in auth templates the email plugin declares, the templates your app declares, and the ones saved in Studio, which land at environment level and override a declaration of the same (name, locale). A template your app declares overrides the built-in copy of its (name, locale); the built-in still serves the locales your app leaves out. Each template is validated through the canonical schema when it is resolved, so a malformed one fails its send loudly instead of falling through to the built-in copy.

Change a template's wording in Studio — the email_template metadata. A save is live on the very next send, with no restart.

The sys_email_template platform object is no longer read or written by the send path. It keeps the rows earlier releases wrote, and it is closed to organization writes: a create or an edit through the data API is refused 403 PERMISSION_DENIED. A row an administrator customized before that door closed is not what sends; the v18 upgrade promotes such rows to environment-level templates.

bodyText is optional: when you omit it the service derives a plain-text alternative by stripping tags from the rendered HTML. Authoring one explicitly is still recommended for spam scoring.

  • Schema reference: Email Template — every field, generated from the spec
  • The service: services.email — send, sendTemplate, renderTemplate, error codes
  • Calling it from automation: Flows — the notify node
  • Translating other metadata: Translations

On this page