A shared layout and four components that turn Tailwind classes into inline styles at render time — and why the pixel preset, not the class names, decides whether Outlook keeps your spacing.
The Problem
Your welcome email is a React component. It looks right in the browser, so you render it to a string and hand the string to your mail provider.
export function WelcomeMail({ name }: { name: string }) {
return (
<div className="mx-auto max-w-[600px] p-6 text-sm text-gray-700">
<h1 className="mb-4 text-2xl font-bold">Welcome, {name}</h1>
<p className="mb-6">Your account is ready. Sign in to get started.</p>
<a
className="rounded-lg bg-teal-700 px-4 py-2 text-white"
href="https://example.com/dashboard"
>
Open dashboard
</a>
</div>
);
}
Gmail web renders it. Outlook desktop renders a full-width white page with 12px text, no padding, and a link that looks like a link. Apple Mail renders the button but at a font size you never set. Nothing threw. The HTML is valid. The email is broken.
You try the three obvious fixes.
-
Move every style into a
styleobject. It works in Outlook, but now you maintain two styling systems, andhover:, media queries, anddark:have no object form.
const el = <div style={{ maxWidth: 600, padding: 24, fontSize: 14 }} />;
-
Put the classes in a
<style>block in<Head>. Gmail web honors it. Outlook.com and the Gmail iOS app for third-party accounts drop it, so the mail arrives unstyled.
<Head>
<style>{`.card { padding: 24px; max-width: 600px; }`}</style>
</Head>
- Switch the whole thing to MJML. You get reliable table markup, but you also get a second templating language. Props, types, and every shared component stop at the boundary, and your app logic has to be re-expressed as MJML includes.
You want to author email in the same React and Tailwind vocabulary as the app, but clients only honor a narrow, inlined subset of CSS that the browser never had to explain to you.
The resolution is a layout that renders the same tree for every mail, with the design tokens in one place and a compile step that inlines them:
export function EmailLayout({
appName,
previewText,
supportMail,
children,
}: {
appName: string;
previewText: string;
supportMail: string;
children: React.ReactNode;
}) {
return (
<Html lang="en">
<Tailwind
config={{
presets: [pixelBasedPreset],
theme: { extend: { colors: TOKENS } },
}}
>
<Head />
<Body className="bg-background text-foreground">
<Preview>{previewText}</Preview>
<Container className="mx-auto max-w-[600px] border border-border p-5">
{children}
</Container>
</Body>
</Tailwind>
</Html>
);
}
The Mental Model
Think of a printing press with one plate.
- Identity: the JSX tree is the plate. It is the only original. The HTML you send is a print, and you can make as many prints as you like without redrawing.
-
Update timing: Tailwind classes are compiled when you run the press (
render()), not when the app builds. Change a class in the plate and the next print changes; the client never sees the class name. - Read timing: clients read only what is physically on the page — inline styles. Anything left in a stylesheet is ink that never touched the paper.
Two consequences follow. First, a class that cannot be inlined (hover:, group-hover:, complex selectors) cannot be trusted, no matter how good it looks in the preview. Second, the pixel preset is not cosmetic: without it, p-6 prints as 1.5rem, and the Word rendering engine behind Outlook desktop does not know what a rem is.
The template is the plate; the inbox only ever sees the print.
How to Use It
Install React Email. The preview app ships separately.
pnpm add react-email
pnpm add -D @react-email/ui
src/
└── mail/
├── components/
│ ├── email-layout.tsx
│ ├── email-button.tsx
│ ├── email-heading.tsx
│ ├── email-info-card.tsx
│ ├── email-link.tsx
│ └── index.ts
├── templates/
│ ├── welcome-mail.tsx
│ ├── reset-password-mail.tsx
│ └── index.ts
├── mail.types.ts
└── mail-service.tsx
src/mail/components/email-layout.tsx — one layout owns the palette, the width, and the footer:
import {
Body,
Container,
Head,
Html,
Link,
Preview,
Section,
Tailwind,
Text,
pixelBasedPreset,
} from "react-email";
const TOKENS = {
background: "#ffffff",
foreground: "#111827",
muted: "#6b7280",
border: "#e5e7eb",
card: "#f9fafb",
primary: "#0f766e",
"primary-foreground": "#f0fdfa",
};
const YEAR = new Date().getFullYear();
export interface EmailLayoutProps {
appName: string;
previewText: string;
supportMail: string;
children: React.ReactNode;
}
export function EmailLayout({
appName,
previewText,
supportMail,
children,
}: EmailLayoutProps) {
return (
<Html lang="en">
<Tailwind
config={{
presets: [pixelBasedPreset],
theme: { extend: { colors: TOKENS } },
}}
>
<Head />
<Body className="m-0 bg-background px-2 font-sans text-foreground">
<Preview>{previewText}</Preview>
<Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-border p-5">
<Section className="mb-6 text-center">
<Text className="m-0 text-2xl font-bold">{appName}</Text>
</Section>
<Section className="text-sm">{children}</Section>
<Section className="mt-8 border-t border-border pt-4 text-center">
<Text className="m-0 text-sm text-muted">
Need help? Contact us at{" "}
<Link href={`mailto:${supportMail}`} className="text-primary">
{supportMail}
</Link>
</Text>
<Text className="mt-2 text-xs text-muted">
{`© ${YEAR} ${appName}. All rights reserved.`}
</Text>
</Section>
</Container>
</Body>
</Tailwind>
</Html>
);
}
src/mail/components/email-button.tsx — the anchor is the button. There is no JavaScript in email:
import { Button } from "react-email";
export function EmailButton({
children,
...props
}: React.ComponentProps<typeof Button>) {
return (
<Button
className="inline-block rounded-lg bg-primary px-5 py-3 text-sm font-semibold text-primary-foreground no-underline"
{...props}
>
{children}
</Button>
);
}
src/mail/components/email-heading.tsx:
import { Text } from "react-email";
export function EmailHeading({ children }: { children: React.ReactNode }) {
return (
<Text className="mt-0 mb-2 text-lg font-bold text-foreground">
{children}
</Text>
);
}
src/mail/components/email-info-card.tsx — a bordered box for security context:
import { Section } from "react-email";
export function EmailInfoCard({ children }: { children: React.ReactNode }) {
return (
<Section className="my-4 rounded-md border border-border bg-card p-4">
{children}
</Section>
);
}
src/mail/components/email-link.tsx — long URLs must wrap, or they blow out the 600px column:
import { Link } from "react-email";
export function EmailLink({
href,
children,
...props
}: React.ComponentProps<typeof Link>) {
return (
<Link href={href} className="text-sm break-all text-primary" {...props}>
{children}
</Link>
);
}
src/mail/components/index.ts:
export { EmailLayout, type EmailLayoutProps } from "./email-layout";
export { EmailButton } from "./email-button";
export { EmailHeading } from "./email-heading";
export { EmailInfoCard } from "./email-info-card";
export { EmailLink } from "./email-link";
src/mail/templates/welcome-mail.tsx:
import { Section, Text } from "react-email";
import {
EmailButton,
EmailHeading,
EmailLayout,
EmailLink,
} from "@/mail/components";
export interface WelcomeMailProps {
userName: string;
appName: string;
supportMail: string;
dashboardUrl: string;
}
export default function WelcomeMail({
userName,
appName,
supportMail,
dashboardUrl,
}: WelcomeMailProps) {
return (
<EmailLayout
appName={appName}
previewText="Your account is ready."
supportMail={supportMail}
>
<EmailHeading>Welcome to {appName}</EmailHeading>
<Text>Hello {userName},</Text>
<Text>Your account is ready. Here is the fastest way in:</Text>
<Section className="my-6 text-center">
<EmailButton href={dashboardUrl}>Open dashboard</EmailButton>
</Section>
<Text className="text-sm text-muted">
If the button does not work, paste this link into your browser:
</Text>
<EmailLink href={dashboardUrl}>{dashboardUrl}</EmailLink>
</EmailLayout>
);
}
WelcomeMail.PreviewProps = {
userName: "Ada",
appName: "Ledger",
supportMail: "help@ledger.dev",
dashboardUrl: "https://ledger.dev/dashboard",
} satisfies WelcomeMailProps;
src/mail/templates/reset-password-mail.tsx — the same components, different content:
import { Section, Text } from "react-email";
import {
EmailButton,
EmailHeading,
EmailInfoCard,
EmailLayout,
} from "@/mail/components";
export interface ResetPasswordMailProps {
userName: string;
resetUrl: string;
appName: string;
supportMail: string;
ipAddress?: string;
}
export default function ResetPasswordMail({
userName,
resetUrl,
appName,
supportMail,
ipAddress,
}: ResetPasswordMailProps) {
return (
<EmailLayout
appName={appName}
previewText="Reset your password"
supportMail={supportMail}
>
<EmailHeading>Reset your password</EmailHeading>
<Text>Hello {userName},</Text>
<Text>We received a request to reset your {appName} password.</Text>
<Section className="my-6 text-center">
<EmailButton href={resetUrl}>Choose a new password</EmailButton>
</Section>
{ipAddress ? (
<EmailInfoCard>
<Text className="m-0 text-xs text-muted">
Request came from IP <span className="font-mono">{ipAddress}</span>.
</Text>
</EmailInfoCard>
) : null}
<Text className="text-sm text-muted">
This link expires in one hour. If you did not ask for it, ignore this
email and your password stays the same.
</Text>
</EmailLayout>
);
}
src/mail/templates/index.ts:
export { default as WelcomeMail, type WelcomeMailProps } from "./welcome-mail";
export {
default as ResetPasswordMail,
type ResetPasswordMailProps,
} from "./reset-password-mail";
The rest of the family is the same layout with different props. Nothing below needs a new component, only a new heading, a new call to action, and the fields the mail must report:
| Template | Props besides userName, appName, supportMail
|
Uses |
|---|---|---|
EmailVerificationMail |
verifyUrl, userAgent?, ipAddress?
|
EmailButton, EmailInfoCard, EmailLink
|
PasswordChangedMail |
changeTimestamp, ipAddress, deviceInfo
|
EmailButton, EmailInfoCard
|
NewDeviceLoginMail |
loginTimestamp, deviceInfo, browser, ipAddress, approximateLocation, secureAccountUrl
|
Row/Column inside EmailInfoCard
|
SuspiciousLoginMail |
attemptTimestamp, ipAddress, location, deviceInfo, secureAccountUrl
|
EmailButton, EmailInfoCard
|
AccountLockedMail |
lockTimestamp, failedAttempts, ipAddress, unlockUrl
|
EmailButton, EmailInfoCard
|
RoleChangedMail |
oldRole, newRole, changedBy, permissionsUrl
|
Row/Column inside EmailInfoCard
|
Every one of them takes userName, appName, and supportMail. That is correct at the component level — the layout cannot guess them — but it is a bad prop surface for a call site: eight senders, eight chances to pass the wrong app name or forget the support address. The service below takes the shared ones once and hides them.
Import the shared layout and templates through the alias. This article uses @/, which maps to src/; swap in whatever alias your project uses. If you have no alias, use relative paths.
Pattern 1: Serve templates through one service, not through call sites
Email needs an HTML part and a plain-text part, so every send has to render one tree twice over. The layout also needs appName and supportMail, and no caller should have to know that. Both problems have the same fix: put them in a config object, subtract them from the public option type, and render every template in one place.
src/mail/mail.types.ts — transport options plus the template's props, minus the ones the service fills:
import type { SendMailOption } from "@/mail/transport/mail-transport.types";
export interface MailConfig {
appName: string;
systemMail: string;
supportMail: string;
}
/** Transport options plus the template's props, minus the ones the service fills. */
export type MailTemplateOptions<TProps> = Omit<
SendMailOption,
"from" | "subject" | "text" | "html"
> &
Omit<TProps, "appName" | "supportMail">;
export interface QueueMailResult {
success: boolean;
emailId?: string;
error?: string;
}
/** The layer that persists and queues a rendered mail. */
export interface MailQueue {
sendMail: (
options: SendMailOption,
isSystemMail?: boolean
) => Promise<QueueMailResult>;
}
The Omit<TProps, "appName" | "supportMail"> is the whole trick. MailTemplateOptions<WelcomeMailProps> still requires userName and dashboardUrl, still forbids a typo, and no longer offers a field the caller could get wrong. If someone passes appName anyway, it is an excess-property error, not a silently ignored prop.
src/mail/mail-service.tsx — one render path, two templates:
import { render, toPlainText } from "react-email";
import { APP_NAME } from "@/constants";
import type {
MailConfig,
MailQueue,
MailTemplateOptions,
QueueMailResult,
} from "@/mail/mail.types";
import {
ResetPasswordMail,
type ResetPasswordMailProps,
WelcomeMail,
type WelcomeMailProps,
} from "@/mail/templates";
import type { SendMailOption } from "@/mail/transport/mail-transport.types";
export interface MailServiceConfig {
mailConfig: MailConfig;
queue: MailQueue;
}
export class MailService {
private readonly mailConfig: MailConfig;
private readonly queue: MailQueue;
constructor({ mailConfig, queue }: MailServiceConfig) {
this.mailConfig = mailConfig;
this.queue = queue;
}
public async sendMailTemplate(
from: string,
to: string | string[],
subject: string,
component: React.ReactNode,
isSystemMail = true,
options: Partial<Omit<SendMailOption, "from" | "to" | "subject">> = {}
): Promise<QueueMailResult> {
let html: string;
let text: string;
try {
html = await render(component);
text = toPlainText(html);
} catch (error) {
throw new Error(
error instanceof Error ? error.message : "Failed to render template"
);
}
return this.queue.sendMail(
{ ...options, from, to, subject, html, text },
isSystemMail
);
}
public sendWelcomeMail({
to,
...options
}: MailTemplateOptions<WelcomeMailProps>): Promise<QueueMailResult> {
return this.sendMailTemplate(
`${APP_NAME} <${this.mailConfig.systemMail}>`,
to,
`Welcome to ${this.mailConfig.appName}`,
<WelcomeMail
appName={this.mailConfig.appName}
supportMail={this.mailConfig.supportMail}
{...options}
/>,
true,
options
);
}
public sendPasswordResetMail({
to,
...options
}: MailTemplateOptions<ResetPasswordMailProps>): Promise<QueueMailResult> {
return this.sendMailTemplate(
`${APP_NAME} <${this.mailConfig.systemMail}>`,
to,
`Reset your password for ${this.mailConfig.appName}`,
<ResetPasswordMail
appName={this.mailConfig.appName}
supportMail={this.mailConfig.supportMail}
{...options}
/>,
true,
options
);
}
}
export function createMailService(config: MailServiceConfig): MailService {
return new MailService(config);
}
Now the call site is honest about what it knows:
import type { MailService } from "@/mail/mail-service";
export async function requestReset(mailService: MailService, request: Request) {
return mailService.sendPasswordResetMail({
to: "ada@example.com",
userName: "Ada",
resetUrl: "https://ledger.dev/reset?token=abc",
ipAddress: request.headers.get("cf-connecting-ip") ?? undefined,
});
}
No app name, no support address, no subject. That is the payoff: a rename touches MailConfig, and every template plus every subject line follows at once.
❌ Do not make appName optional and default it inside the template. A defaulted "App name" is what ships to a customer the day the config key is missing, and the preview app happily renders it.
Pattern 2: Plug the service into a queue or a provider
The service renders; something else delivers. Give it the smallest interface it needs and both a direct provider and a queue fit behind it.
import { Resend } from "resend";
import type { MailQueue } from "@/mail/mail.types";
/** Direct provider call: fine for a low-volume internal tool. */
export function createDirectQueue(apiKey: string): MailQueue {
const resend = new Resend(apiKey);
return {
async sendMail(mail) {
const { data, error } = await resend.emails.send({
from: mail.from,
to: mail.to,
subject: mail.subject,
html: mail.html ?? "",
text: mail.text,
});
return data
? { success: true, emailId: data.id }
: { success: false, error: error.message };
},
};
}
The key comes from the environment the caller already has, not from a module-scope process.env. In a Worker that matters: secrets arrive on env, and a module-scope read is evaluated once, before the binding exists.
Swap createDirectQueue for a D1-backed producer and every template call site stays identical:
import type { Env } from "@/mail/enqueue";
import { enqueueMail } from "@/mail/enqueue";
import { createMailService } from "@/mail/mail-service";
export function buildService(env: Env) {
return createMailService({
mailConfig: {
appName: "Ledger",
systemMail: "hello@ledger.dev",
supportMail: "help@ledger.dev",
},
queue: {
sendMail: async (mail) => {
// One recipient row per email, so a fan-out becomes several rows.
const to = Array.isArray(mail.to) ? mail.to[0] : mail.to;
if (!to) return { success: false, error: "No recipient" };
const { emailId } = await enqueueMail(env, { ...mail, to });
return { success: true, emailId };
},
},
});
}
The service does not know whether a row was written or a provider was called, only that sendMail resolves. That is the seam the companion post on D1 and Cloudflare Queues plugs into.
MailQueue.sendMail returns the project's own QueueMailResult, not a provider response, so the transport's shape never leaks into the template layer. The one field that needs care is to: this interface allows string | string[], while a ledger with one recipient row per email needs a single address. Normalize at the adapter, not in the template.
Pattern 3: Preview every template without sending
pnpm exec email dev --dir="src/mail/templates" --port=8088
The preview app reads each default export and its static PreviewProps. You edit a class, save, and see the print change. Nothing is sent, which is also the cheapest way to catch a broken prop.
Pattern 4: Assert the service, not just the template
A template test proves the markup renders. A service test proves the two shared props actually reached it, which is the failure mode the preview cannot show.
import { expect, test } from "vitest";
import { createMailService } from "@/mail/mail-service";
test("every mail gets the configured app name and support address", async () => {
let sent: { subject: string; html: string } | undefined;
const service = createMailService({
queue: {
sendMail: async (mail) => {
sent = { subject: mail.subject, html: mail.html ?? "" };
return { success: true };
},
},
mailConfig: {
appName: "Ledger",
systemMail: "hello@ledger.dev",
supportMail: "help@ledger.dev",
},
});
await service.sendPasswordResetMail({
to: "ada@example.com",
userName: "Ada",
resetUrl: "https://ledger.dev/reset?token=abc",
});
expect(sent?.subject).toBe("Reset your password for Ledger");
expect(sent?.html).toContain("help@ledger.dev");
expect(sent?.html).toContain("https://ledger.dev/reset?token=abc");
});
sendMail is a stub, so the test never touches a provider, a queue, or D1. It catches the three regressions that matter: a subject built from a hard-coded name, a footer that lost the support address, and a template that silently stopped rendering the action link.
import { render } from "react-email";
import { expect, test } from "vitest";
import ResetPasswordMail from "@/mail/templates/reset-password-mail";
test("reset mail carries the action link and the expiry warning", async () => {
const html = await render(
<ResetPasswordMail
userName="Ada"
resetUrl="https://ledger.dev/reset?token=abc"
appName="Ledger"
supportMail="help@ledger.dev"
/>
);
expect(html).toContain("https://ledger.dev/reset?token=abc");
expect(html).toContain("expires in one hour");
});
This one catches the failure the preview cannot: a prop that is accidentally required, renamed, or missing from one call site.
❌ Do not put render() behind a client component or a shared module. It pulls in the server renderer. Keep it in a server-only file, or the bundler will try to ship React DOM server to the browser.
When to Use It
Reach for this setup only when all three are true:
- You send more than one kind of email and want them to share a palette, spacing scale, and footer.
- You need HTML and plain text from a single source of truth.
- Your team already writes React and Tailwind, so the template is not a new skill.
| Situation | Better tool |
|---|---|
| One plain-text alert from a cron job | A template string |
| A marketing email designed by a non-engineer | A visual email builder |
| Pixel-perfect complex layout with nested columns | MJML, or a builder that emits tables |
| Per-locale copy for 20 languages | Content files resolved before render, not 20 components |
| Rendering user-supplied HTML | Sanitize it; never render it as a template |
| A one-off mail whose copy changes every quarter | Keep it in the service, but skip the shared layout |
Smell test: if a class you rely on cannot survive being pasted into a style attribute, it is decoration in the preview and a bug in the inbox.
How It Works Under the Hood
Tailwindis a render-time compiler, not a build step. It walks the tree, collects the class names it finds, compiles those rules with Tailwind, and inlines the matching declarations onto each element. That is whyEmailLayoutcan hold the config: the config is read when the component renders, not when Vite builds.pixelBasedPresetswaps the scales topx. Tailwind's spacing and type scales arerem-based. The preset replaces both withpxvalues (p-6→padding: 24px,text-sm→font-size: 14px; line-height: 20px). Outlook desktop's Word engine ignoresremand inherited font sizing; this single preset is the difference between the design you drew and a wall of 12px text.render()returns a whole document,toPlainText()returns a second artifact. One tree, two outputs. If you build the text version by hand, the link in the text part is the first thing to drift.Inlining covers most rules, and the leftovers are the ones that break. React Email inlines declarations it can attach to a single element, and emits the rest into a
<style>element inside<Head>— which is exactly whyhover:and media queries can look right in the preview and vanish in Outlook. There is no stylesheet specificity to fight, but there is also no:focusand no descendant selector you can rely on. State-based styling has to become a prop (isPrimary) or an inline color.Every render costs CPU twice over. Compiling the classes is work, and you do it once per email. A batch of 500 password resets compiles the same CSS 500 times. For high volume, render once per distinct prop set and reuse the HTML, or render at build time and store the artifact. In a Worker, that CPU is billed.
| Phase | What exists | What the client sees | Failure if skipped |
|---|---|---|---|
| Author | JSX tree with class names | Nothing | — |
| Module load | Component functions, token object | Nothing | Config drift between templates |
| Service construction |
MailConfig with app/support |
Nothing | Call sites invent their own names |
| Render pass | React element tree | Nothing | — |
| Tailwind compile | Rules for the classes used | Nothing | Unstyled classes |
| Inline serialization | HTML with style attributes |
The layout | Outlook ignores the stylesheet |
toPlainText |
Text alternative | The fallback part | HTML-only mail, no link for text clients |
| Preview render | A print that is thrown away | Nothing | Broken props ship |
| Send | Transport payload | The email | A beautiful mail nobody receives |
The discarded render is the preview: email dev re-renders on every save and throws the result away. It is also the retry attempt in a queue consumer that re-renders a template instead of reusing the stored HTML. Store the artifact, not the component, once the mail is queued.
Server rendering note. render() uses the server renderer under the hood. In a Cloudflare Worker that means nodejs_compat in compatibility_flags, because the Tailwind compiler and the renderer reach for Node built-ins. Do not import a template module into client code: the render path and the Tailwind compiler are server-side dependencies, and the browser bundle needs neither.
Compared to the built-ins. renderToStaticMarkup from react-dom/server gives you HTML and nothing else: no Tailwind compilation, no preview text handling, no text conversion. You would have to run Tailwind yourself at build time and inline the result. MJML gives you reliable tables, but its input is MJML XML, not React components, so props and shared app code cannot cross the boundary. React Email's limitation is the mirror image: it only inlines what Tailwind can express in a single element's style attribute.
Conclusion
The trade is a render-time compiler plus a thin service in exchange for one source of truth. You write the same React and Tailwind you already know, and you accept that the output is a print with a narrow vocabulary.
- Put the palette, width, and footer in one layout; never restyle them per template.
- Always enable
pixelBasedPreset, and treat any class that cannot be inlined as decoration. - Let one service own
appName,supportMail, the subject, and the render, so a rename cannot leave a template behind.
Use this when you have a family of transactional emails and a team that already thinks in components. When you have one email that never changes, a plain HTML string is the boring, better answer.
Top comments (0)