Emails
Change the login code email, write it in the reader's language, and send your own emails with ctx.email.
The CMS sends one email itself: the login code. A project can rewrite it, in every locale it
publishes in, and send its own emails (a welcome, an order confirmation) from server code with
ctx.email. Both go out through the email provider, or are printed to
the console in cms dev without one.
Where templates live
cms.config is bundled into the admin, so a template that imports anything heavy (a renderer,
your copy files) belongs in a *.server.ts module, which the admin build stubs, as for
signup.allow:
// cms.config.ts
import { config } from "@cms/config";
import { ses } from "@cms/email-ses";
import { loginCode } from "./emails.server";
export default config({
// ...
email: {
provider: ses({ from: process.env.EMAIL_SENDER, region: process.env.AWS_SES_REGION }),
templates: { loginCode },
},
});
templates works without a provider: cms dev then prints each email’s recipient, subject and
text part, which is how to try a template locally.
The login code email
templates.loginCode(input, ctx) returns { subject, html, text? }. The engine sends it to the
address that asked. input holds the code, expiresInMinutes, the locale to write in,
whether it’s a signup, the user (null on a signup) and their role; ctx is the
server context, for reading branding from a global with
ctx.system. See email.templates for every field.
It can’t skip the email: a person who asked for a code is waiting for it. A throw fails the request
with a 500, as a failed delivery does, and is logged and reported.
Translate the default
loginCodeEmail(input, copy) is the built-in email. Give it your words and keep its layout; a key
you leave out stays English. Picking the copy for a locale, and what pt-BR gets, is yours:
// emails.server.ts
import { type EmailTemplates, type LoginCodeCopy, loginCodeEmail } from "@cms/config";
const PT: Partial<LoginCodeCopy> = {
subject: "O seu código de acesso",
heading: "O seu código de acesso",
expiry: (minutes) => `Este código expira em ${minutes} minuto${minutes === 1 ? "" : "s"}.`,
ignore: "Se não pediu este código, pode ignorar este email.",
};
const COPY: Record<string, Partial<LoginCodeCopy>> = { pt: PT };
export const loginCode: EmailTemplates["loginCode"] = (input) =>
loginCodeEmail(input, COPY[input.locale]);
The copy is plain text: it’s escaped into the HTML and used as is in the text part.
Brand it for customers
input.role.adminPanel tells editors from an app’s customers. Keep the default for editors and
send customers your own:
// emails.server.ts
import { type EmailTemplates, html, loginCodeEmail } from "@cms/config";
export const loginCode: EmailTemplates["loginCode"] = async (input, ctx) => {
if (input.role.adminPanel) return loginCodeEmail(input);
// A global holding the app's name and logo. `ctx.system` is untyped: see Hooks → Typed calls.
const { data: brand } = await ctx.system.get("brand");
const name = String(brand?.name ?? "Acme");
const pt = input.locale === "pt";
return {
subject: pt ? `O seu código ${name}` : `Your ${name} code`,
html: html`<img src="${String(brand?.logoUrl ?? "")}" alt="${name}" height="32">
<p style="font-size:32px;letter-spacing:6px">${input.code}</p>`,
text: input.code,
};
};
With react-email
Renderers such as react-email or MJML return a string they’ve already
escaped, which html takes as is:
// emails.server.tsx
import type { EmailTemplates } from "@cms/config";
import { Html, Text } from "@react-email/components";
import { render } from "@react-email/render";
function LoginCode({ code, minutes }: { code: string; minutes: number }) {
return (
<Html>
<Text>Your code is {code}. It expires in {minutes} minutes.</Text>
</Html>
);
}
export const loginCode: EmailTemplates["loginCode"] = async (input) => {
const email = <LoginCode code={input.code} minutes={input.expiresInMinutes} />;
return {
subject: "Your login code",
html: await render(email),
text: await render(email, { plainText: true }),
};
};
Which locale
input.locale is always one of your locales: the one the client passed to
auth.request(email, { locale }), else the user’s preferredLocale, else the default. A locale
you don’t have (navigator.language giving pt-BR against your pt) is skipped, so a client can
pass what the browser says.
With more than one locale, _user has a preferredLocale. Signup fills it from the request’s
locale; after that it changes only through a normal _user update, such as a profile form, under
the role’s permissions. A sign-in never changes it. The admin’s login sends no locale, so editors
get theirs, or the default.
Sending your own emails
Every piece of server code (hooks, routes, plugin observers, server.ready) has ctx.email.send,
which sends through the same provider as the login code:
// emails.server.ts
import { type HookContext, html } from "@cms/config";
export const confirmOrder = async (order: Record<string, unknown>, ctx: HookContext) => {
const { data: customer } = await ctx.system.get("_user", order.customer as string);
const pt = customer.preferredLocale === "pt";
await ctx.email.send({
to: customer.email as string,
subject: pt ? `Encomenda ${order.number}` : `Order ${order.number}`,
html: html`<p>${pt ? "Obrigado" : "Thanks"}, ${customer.name as string}.</p>
<ul>${(order.items as { title: string }[]).map((item) => html`<li>${item.title}</li>`)}</ul>`,
text: pt ? "Obrigado pela sua encomenda." : "Thanks for your order.",
replyTo: "orders@acme.com",
});
};
// cms.config.ts
entity("orders", { fields: [/* ... */], hooks: { afterCreate: confirmOrder } });
- Send from after-hooks. A send from a before-hook goes out even when the write then fails. After-hooks run after the commit and nothing waits on them, so awaiting the send holds nothing back; a rejection is logged and reported.
sendrejects when the message is invalid (a line break in the subject, an address that isn’t one) or delivery fails. Catch it where an email is optional to what you’re doing.- No queue or retries. A send runs inline, once.
fromoverrides the provider’s sender, asaddressorName <address>. With SES, verify it (or its domain) first.
Escaping: html
A value put into markup can carry markup of its own: a customer named <a href=…> would turn into
a link. The html tag escapes everything it interpolates, except another html result or
raw(...), so fragments compose:
import { html, raw } from "@cms/config";
html`<p>Hi ${user.name}</p>${raw(trustedFooter)}`;
Arrays are joined, and null, undefined and false render nothing, so ${cond && html…}
works. Use html whenever you build an email from a template string. A renderer (react-email,
MJML) already escapes what it renders: pass its output as a string.
A welcome email
The CMS doesn’t email users when their account is created: editors hear it from whoever added
them, and an app decides what its customers get. Send one from a _user extension’s afterCreate,
which runs for users created in the admin, through the API, and by signup. See the welcome recipe
in Hooks, which writes it in the user’s preferredLocale.
cms user create writes straight to the database, so _user hooks don’t run and a user it
creates gets no welcome email.
Plugins
Plugins send their own emails with ctx.email and don’t change the login code email: only the
project sets email.templates, so it always knows what its users receive.
Previous
Drafts and publishing
Next
Assets