react-email

react-email

熱門

當你需要使用 React 元件建立 HTML 電子郵件範本、利用 React Email 視覺化編輯器在應用程式中新增電子郵件編輯器、將電子郵件轉換渲染為 HTML,或透過 Resend 發送電子郵件時使用。涵蓋歡迎信、重設密碼信、通知信、訂單確認信、電子報、交易型電子郵件,以及可嵌入的電子郵件編輯器元件。

1.9萬星標
1058分支
更新於 2026/7/14
SKILL.md
唯讀
名稱
react-email
描述

當你需要使用 React 元件建立 HTML 電子郵件範本、利用 React Email 視覺化編輯器在應用程式中新增電子郵件編輯器、將電子郵件轉換渲染為 HTML,或透過 Resend 發送電子郵件時使用。涵蓋歡迎信、重設密碼信、通知信、訂單確認信、電子報、交易型電子郵件,以及可嵌入的電子郵件編輯器元件。

React Email

使用 React 元件打造並發送 HTML 電子郵件。採用現代化的元件化電子郵件開發方式,可完美相容於各大主流電子郵件用戶端。

安裝

npm i react-email

或建立新專案:

npx create-email@latest
cd react-email-starter
npm install
npm run dev

適用於任何套件管理器(npm、yarn、pnpm、bun)——請自行替換相對應的命令。

開發伺服器(dev server)會運行於 localhost:3000,並提供 emails 資料夾中郵件範本的預覽介面。

加入現有專案

安裝套件並在 package.json 中新增腳本(script):

{
  "scripts": {
    "email": "email dev --dir emails --port 3000"
  }
}

請確保指向 emails 資料夾的路徑是相對於專案根目錄的相對路徑。同時確認 tsconfig.json 已適當設定對 JSX 的支援。

基礎電子郵件範本

建立結構完整的電子郵件元件,並使用 Tailwind 元件處理樣式:

import {
  Html,
  Head,
  Preview,
  Body,
  Container,
  Heading,
  Text,
  Button,
  Tailwind,
  pixelBasedPreset
} from 'react-email';

interface WelcomeEmailProps {
  name: string;
  verificationUrl: string;
}

export default function WelcomeEmail({ name, verificationUrl }: WelcomeEmailProps) {
  return (
    <Html lang="en">
      <Tailwind
        config={{
          presets: [pixelBasedPreset],
          theme: {
            extend: {
              colors: {
                brand: '#007bff',
              },
            },
          },
        }}
      >
        <Head />
        <Body className="bg-gray-100 font-sans">
          <Preview>Welcome - Verify your email</Preview>
          <Container className="max-w-xl mx-auto p-5">
            <Heading className="text-2xl text-gray-800">
              Welcome!
            </Heading>
            <Text className="text-base text-gray-800">
              Hi {name}, thanks for signing up!
            </Text>
            <Button
              href={verificationUrl}
              className="bg-brand text-white px-5 py-3 rounded block text-center no-underline box-border"
            >
              Verify Email
            </Button>
          </Container>
        </Body>
      </Tailwind>
    </Html>
  );
}

// Preview props for testing
WelcomeEmail.PreviewProps = {
  name: 'John Doe',
  verificationUrl: 'https://example.com/verify/abc123'
} satisfies WelcomeEmailProps;

export { WelcomeEmail };

行為指引

  • 在迭代修改程式碼時,僅更新使用者要求的內容,其餘部分請保持原樣。
  • 若使用者要求使用媒體查詢(media queries),請提醒他們大多數電子郵件用戶端並不支援,並建議採用其他替代方案。
  • 切勿在 TypeScript 程式碼中直接使用範本變數(例如 {{name}}),而是直接引用底層屬性。若使用者明確要求使用 {{variableName}},請僅將 mustache 字串放在 PreviewProps 中,絕不要放在元件的 JSX 內:
const EmailTemplate = (props) => {
  return (
    <h1>Hello, {props.variableName}!</h1>
  );
}

EmailTemplate.PreviewProps = {
  variableName: "{{variableName}}",
};

export default EmailTemplate;
  • 切勿在元件結構中直接編寫 {{variableName}} 的模式。若使用者堅持,請解釋這樣會導致範本無效。

核心元件

請參閱 references/COMPONENTS.md 取得完整的元件說明文件。

核心結構:

  • Html - 帶有 lang 屬性的根包裝元件
  • Head - Meta 元素、樣式與字型
  • Body - 主要內容包裝元件
  • Container - 最外層的置中包裝元件(內建 max-width: 37.5em)。每封電子郵件僅使用一次。
  • Section - 內部內容區塊(無內建最大寬度)。用於在 Container 內部對內容進行分組。
  • RowColumn - 多欄式版面配置
  • Tailwind - 啟用 Tailwind CSS 工具類別(utility classes)

內容:

  • Preview - 收件匣預覽文字,固定放在 <Body> 內的第一個位置
  • Heading - h1-h6 標題
  • Text - 段落
  • Button - 帶樣式的連結按鈕(務必包含 box-border
  • Link - 超連結
  • Img - 圖片(詳見下方「靜態檔案與圖片」章節)
  • Hr - 水平分隔線

特化元件:

  • CodeBlock - 帶語法高亮顯示的程式碼區塊
  • CodeInline - 行內程式碼
  • Markdown - 渲染 Markdown
  • Font - 自訂 Web 字型

開始編寫程式碼之前

當使用者要求建立電子郵件範本時,若尚未提供以下資訊,請先詢問釐清:

  1. 品牌顏色 - 詢問主要品牌顏色(十六進位碼,如 #007bff)
  2. 標誌 (Logo) - 詢問是否有 Logo 檔案及其格式(僅限 PNG/JPG——若為 SVG/WEBP 請予以提醒 Warning)
  3. 風格偏好 - 專業、休閒或極簡語調
  4. 正式環境 URL (Production URL) - 靜態資源在正式環境中將託管於何處?

靜態檔案與圖片

目錄結構

本地圖片必須放在 emails 目錄下的 static 資料夾中:

project/
├── emails/
│   ├── welcome.tsx
│   └── static/           <-- 圖片放在這裡
│       └── logo.png

開發與正式環境 URL

使用此模式可讓圖片同時在開發預覽與正式環境中順暢運作:

const baseURL = process.env.NODE_ENV === "production"
  ? "https://cdn.example.com"  // 使用者的正式環境 CDN
  : "";

export default function Email() {
  return (
    <Img
      src={`${baseURL}/static/logo.png`}
      alt="Logo"
      width="150"
      height="50"
    />
  );
}

運作原理:

  • 開發環境: baseURL 為空字串,因此 URL 為 /static/logo.png——由 React Email 的開發伺服器提供服務
  • 正式環境: baseURL 為 CDN 網域,因此 URL 為 https://cdn.example.com/static/logo.png

重要提醒: 務必詢問使用者的正式環境託管 URL。切勿寫死 localhost:3000

樣式設定

請參閱 references/STYLING.md 取得包含排版、版面配置模式、深色模式及品牌一致性等完整樣式文件。

核心規則

  • 使用 Tailwind 並搭配 pixelBasedPreset(電子郵件用戶端不支援 rem)。從 react-email 匯入 pixelBasedPreset
  • 切勿使用 flexbox 或 grid——請使用 Row/Column 元件或表格進行版面配置。
  • 避免使用 CSS/Tailwind 媒體查詢(sm:, md:, lg:, xl:)——電子郵件用戶端對此支援度有限。
  • 切勿使用主題選擇器(dark:, light:)——不被支援。
  • 切勿使用 SVG 或 WEBP 圖片——若使用者使用,請提醒可能發生的渲染問題。
  • 務必指定邊框類型(border-solid, border-dashed 等)——電子郵件用戶端不會繼承邊框樣式。
  • 設定單邊邊框時,請先重置其他邊框(border-none border-l border-solid)。

必填 Class

元件 必填 Class 原因
Button box-border 防止內距(padding)超出按鈕寬度
Hr / 任何邊框 border-solid(或 border-dashed 等) 電子郵件用戶端不會繼承邊框類型
單邊邊框 border-none + 指定邊 重置其他邊的預設邊框

結構注意事項

  • 使用 Tailwind CSS 時,務必在 <Tailwind> 內部定義 <Head />
  • <Preview> 應始終作為 <Body> 內的第一個元素
  • 僅在 PreviewProps 中包含元件實際有使用的 props
  • 尺寸固定的元素(Logo、圖示)使用固定寬高;內容圖片則使用響應式尺寸(w-full, h-auto

渲染

轉換為 HTML

import { render } from 'react-email';
import { WelcomeEmail } from './emails/welcome';

const html = await render(
  <WelcomeEmail name="John" verificationUrl="https://example.com/verify" />
);

轉換為純文字

const text = await render(<WelcomeEmail name="John" verificationUrl="https://example.com/verify" />, { plainText: true });

發送電子郵件

React Email 支援透過任何電子郵件服務提供者發送。請參閱 references/SENDING.md 取得包含 Resend、Nodemailer 及 SendGrid 範例的完整發送文件。

使用 Resend SDK 的快速範例:

import { Resend } from 'resend';
import { WelcomeEmail } from './emails/welcome';

const resend = new Resend(process.env.RESEND_API_KEY);

const { data, error } = await resend.emails.send({
  from: 'Acme <onboarding@resend.dev>',
  to: ['user@example.com'],
  subject: 'Welcome to Acme',
  react: <WelcomeEmail name="John" verificationUrl="https://example.com/verify" />
});

Resend Node SDK 會自動處理 HTML 與純文字的渲染。

CLI 命令

react-email 套件提供可透過 email 命令使用的 CLI 工具:

命令 說明
email dev --dir <path> --port <port> 啟動預覽開發伺服器(預設:./emails,連接埠 3000)
email build --dir <path> 建置用於正式環境部署的預覽應用程式
email start 運行建置好的預覽應用程式
email export --outDir <path> --pretty --plainText --dir <path> 將範本匯出為靜態 HTML 檔案
email resend setup 透過 API 金鑰將 CLI 連接至您的 Resend 帳號
email resend reset 移除儲存的 Resend API 金鑰

國際化

請參閱 references/I18N.md 取得完整多國語言(i18n)文件。React Email 支援三個套件庫:next-intl、react-i18next 與 react-intl。

電子郵件編輯器

React Email 包含一個可嵌入至您應用程式中的視覺化編輯器(@react-email/editor)。它基於 TipTap/ProseMirror 開發,並能產生適合電子郵件格式的 HTML。

請參閱 references/EDITOR.md 取得完整說明文件,包含:

  • EmailEditor — 開箱即用的元件,包含浮動選單(bubble menus)、斜線命令(slash commands)與主題設定
  • StarterKit — 35+ 個電子郵件專用擴充功能(標題、清單、表格、欄位、按鈕等)
  • Inspector — 用於編輯樣式的情境側邊欄
  • EmailTheming — 內建主題(basicminimal)與可自訂的 CSS 屬性
  • composeReactEmail — 將編輯器內容匯出為電子郵件相容的 HTML 與純文字
  • 透過 EmailNodeEmailMark 自訂擴充功能

快速範例:

import { EmailEditor, type EmailEditorRef } from '@react-email/editor';
import '@react-email/editor/themes/default.css';
import { useRef } from 'react';

export function MyEditor() {
  const ref = useRef<EmailEditorRef>(null);

  return (
    <EmailEditor
      ref={ref}
      content="<p>Start typing...</p>"
      theme="basic"
    />
  );
}

常見模式

請參閱 references/PATTERNS.md 取得完整範例,包含:

  • 重設密碼電子郵件
  • 包含商品清單的訂單確認信
  • 包含程式碼區塊的通知信
  • 多欄式版面配置
  • 團隊邀請信

電子郵件最佳實踐

  1. 跨電子郵件用戶端測試 - Gmail、Outlook、Apple Mail、Yahoo Mail
  2. 保持響應式設計 - 最大寬度控制在 600px 左右,並在行動裝置上進行測試
  3. 使用絕對圖片 URL - 託管於可靠的 CDN 上
  4. 編寫有意義的 alt 文字 - 為內容圖片描述其目的與細節;裝飾性圖片(間距、分隔線、背景花紋)使用 alt=""。React Email 的 <Img> 預設為 alt=""
  5. 提供純文字版本 - 提升無障礙性(accessibility)的必備項目
  6. 保持檔案大小小於 102KB - Gmail 會裁切超過此大小的電子郵件
  7. 加入適當的 TypeScript 型別 - 為所有電子郵件 props 定義介面(interface)
  8. 包含預覽 props - 加入 .PreviewProps