简介
React Email 是 Resend 开源的库,让你用 React 组件写事务邮件 —— 跟 web 同样的 JSX,加邮件安全的 primitive(Container / Section / Heading / Text / Button / Link / Img / Preview)编译成各邮件客户端容忍的 HTML。带开发预览服务器。适合已经在 React 上、想要类型化组件化邮件而不想写表格 HTML 汤的团队。兼容 Resend / SendGrid / Postmark / AWS SES —— 渲染成 HTML 后传给任何 provider。装机时间 5 分钟。
安装
npm install @react-email/components react-email欢迎邮件组件
// emails/welcome.tsx
import { Body, Container, Head, Heading, Html, Preview, Text, Button, Link } from "@react-email/components";
interface Props { firstName: string; activationUrl: string }
export default function WelcomeEmail({ firstName, activationUrl }: Props) {
return (
<Html>
<Head />
<Preview>欢迎来到 TokRepo —— 一键激活账户</Preview>
<Body style={{ fontFamily: "system-ui", backgroundColor: "#f6f9fc", padding: "24px" }}>
<Container style={{ background: "white", padding: "32px", borderRadius: "8px" }}>
<Heading as="h1">欢迎,{firstName} 👋</Heading>
<Text>点下面激活你的 TokRepo 账户。链接 24 小时内有效。</Text>
<Button href={activationUrl} style={{ background: "#000", color: "#fff", padding: "12px 20px", borderRadius: "6px" }}>
激活账户
</Button>
<Text style={{ marginTop: "24px", color: "#666", fontSize: "12px" }}>
没注册?忽略此邮件或<Link href="https://tokrepo.com/help">联系客服</Link>。
</Text>
</Container>
</Body>
</Html>
);
}配 Resend 渲染 + 发送
import { Resend } from "resend";
import WelcomeEmail from "./emails/welcome";
const resend = new Resend(process.env.RESEND_API_KEY);
await resend.emails.send({
from: "TokRepo <welcome@tokrepo.com>",
to: "user@example.com",
subject: "欢迎来到 TokRepo",
react: WelcomeEmail({ firstName: "Jane", activationUrl: "https://tokrepo.com/a/abc123" }),
});预览服务器(npx react-email dev)
npx react-email dev
# 打开 http://localhost:3000 —— ./emails/ 下每封邮件实时刷新预览邮件安全组件 cheat sheet
| 组件 | 替代什么 |
|---|---|
<Container> |
<div style="max-width: 600px"> 表格包装 |
<Section> |
<table> 块 |
<Row> / <Column> |
布局网格 |
<Heading> |
h1-h6,邮件安全默认 |
<Button> |
样式化 <a> 渲染成按钮(避开 Outlook 坏块) |
<Img> |
<img> 带安全默认(无边框、块显示) |
<Preview> |
收件箱预览文本(body 中不可见渲染) |
FAQ
Q: Gmail 暗模式能用吗? A: 能 —— primitive 含强制 color token 避开 Gmail 自动色彩反转毁品牌色。在 Resend 仪表盘的邮件渲染预览里测,能并排看明暗。
Q: 能用 Tailwind 吗?
A: 能 —— React Email 支持 @react-email/tailwind。内联样式仍最可移植,但 Tailwind class 渲染时会解析成内联样式。
Q: 怎么加附件?
A: Resend 的 emails.send 接收 attachments: [{filename, content}] 字段,content 是 Buffer 或 base64。React Email 处理 body,Resend 处理附件。