扫一扫分享
传统的邮件模板开发依赖复杂的html表格和内联css,还要面对各种邮件客户端的兼容性问题。这个过程既繁琐又难以维护,让很多开发者感到头疼。现在,react Email正在改变这一现状。
React Email是一个开源的React组件库,专门为电子邮件开发设计。它提供了一系列无样式的核心组件,比如<Section>、<Button>、<Img>等。开发者可以用JSX语法组合这些组件,然后用Tailwind、CSS或内联样式来自定义外观。
React Email的核心优势在于它的编译器能够将JSX代码转换成各种邮件客户端都能正确显示的HTML,解决了传统邮件开发中最让人头疼的兼容性问题。
无样式组件:组件本身不带样式,可以灵活搭配各种CSS方案
TypeScript支持:内置完整的类型定义,开发时有更好的提示和错误检查
自动内联样式:通过@react-email/render将样式自动转为内联CSS,适配Gmail、Outlook等客户端
React 19集成:兼容最新的React特性,提升动态渲染性能
React Email的组件库专注于邮件所需的语义化元素,所有组件都采用无样式设计,方便与各种样式方案结合。这些组件会自动处理兼容性问题,比如使用<table>进行布局,还支持暗黑模式。
下面是常用的组件列表:
| 组件名 | 用途说明 | 主要属性 | 代码示例 |
|---|---|---|---|
| Html | 邮件根元素 | lang(语言) | <Html lang="zh-CN">内容</Html> |
| Head | 邮件头部 | children | <Head><title>欢迎邮件</title></Head> |
| Body | 邮件主体容器 | style | <Body style={{backgroundColor:'#fff'}}> |
| Preview | 邮件预览文本 | children | <Preview>新功能更新!</Preview> |
| Container | 内容容器 | style | <Container style={{width:'600px'}}> |
| Section | 区块容器 | style | <Section style={{padding:'20px'}}> |
| Row | 行容器 | style | <Row style={{display:'table-row'}}> |
| Column | 列容器 | width, style | <Column width="50%">列内容</Column> |
| Text | 文本元素 | style | <Text style={{fontSize:'16px'}}>文本</Text> |
| Heading | 标题元素 | as, style | <Heading as="h1">大标题</Heading> |
| Link | 超链接 | href, style | <Link href="https://example.com">链接</Link> |
| Button | 按钮 | href, style | <Button href="/">点击我</Button> |
| Img | 图片 | src, alt, width | <Img src="logo.png" alt="Logo" width={200}/> |
| Hr | 水平线 | style | <Hr style={{borderTop:'1px solid #ccc'}}/> |
| Tailwind | Tailwind包装器 | children | <Tailwind><div className="p-4">内容</div></Tailwind> |
首先创建项目并安装必要的依赖:
# 创建新项目
npx create-react-email@latest my-email-app
cd my-email-app
# 安装核心依赖
npm install @react-email/components @react-email/render react@19 react-dom@19如果需要使用Tailwind CSS,还需要额外配置:
npm install tailwindcss @react-email/tailwind --save
npx tailwindcss init配置Tailwind配置文件tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
plugins: [require('@react-email/tailwind')],
corePlugins: {
preflight: false, // 禁用不兼容的Tailwind功能
},
};下面我们创建一个完整的欢迎邮件组件:
// WelcomeEmail.tsx
import {
Html,
Head,
Body,
Section,
Button,
Text,
Preview
} from '@react-email/components';
import * as React from 'react';
interface WelcomeEmailProps {
userName: string;
activationLink: string;
}
const WelcomeEmail: React.FC<WelcomeEmailProps> = ({
userName,
activationLink
}) => {
return (
<Html lang="zh-CN">
<Head>
<title>欢迎加入我们!</title>
</Head>
<Preview>欢迎{userName},请激活您的账户开始使用</Preview>
<Body style={{
backgroundColor: '#f8fafc',
fontFamily: 'Arial, sans-serif',
margin: 0,
padding: '20px'
}}>
<Container style={{
maxWidth: '600px',
margin: '0 auto',
backgroundColor: '#ffffff',
borderRadius: '8px',
overflow: 'hidden'
}}>
{/* 邮件头部 */}
<Section style={{
backgroundColor: '#3b82f6',
padding: '30px 20px',
textAlign: 'center'
}}>
<Text style={{
color: '#ffffff',
fontSize: '28px',
fontWeight: 'bold',
margin: 0
}}>
欢迎加入我们!
</Text>
</Section>
{/* 邮件内容 */}
<Section style={{ padding: '30px' }}>
<Text style={{
fontSize: '18px',
color: '#1f2937',
lineHeight: '1.6'
}}>
亲爱的 {userName},
</Text>
<Text style={{
fontSize: '16px',
color: '#4b5563',
lineHeight: '1.6',
marginTop: '15px'
}}>
感谢您注册我们的服务。我们很高兴能为您提供优质的产品体验。
</Text>
<Text style={{
fontSize: '16px',
color: '#4b5563',
lineHeight: '1.6',
marginTop: '15px'
}}>
请点击下方按钮激活您的账户:
</Text>
<Section style={{ textAlign: 'center', margin: '30px 0' }}>
<Button
href={activationLink}
style={{
backgroundColor: '#3b82f6',
color: '#ffffff',
padding: '12px 30px',
borderRadius: '6px',
textDecoration: 'none',
fontSize: '16px',
fontWeight: 'bold',
display: 'inline-block'
}}
>
激活账户
</Button>
</Section>
<Text style={{
fontSize: '14px',
color: '#6b7280',
lineHeight: '1.6',
marginTop: '20px'
}}>
如果按钮无法点击,请复制以下链接到浏览器地址栏:<br />
{activationLink}
</Text>
</Section>
{/* 邮件底部 */}
<Section style={{
backgroundColor: '#f1f5f9',
padding: '20px',
textAlign: 'center'
}}>
<Text style={{
fontSize: '12px',
color: '#64748b'
}}>
© 2024 我们的公司. 保留所有权利.<br />
如果您有任何问题,请联系 support@example.com
</Text>
</Section>
</Container>
</Body>
</Html>
);
};
export default WelcomeEmail;如果你更喜欢使用Tailwind,可以这样写:
// WelcomeEmailTailwind.tsx
import {
Html,
Head,
Body,
Section,
Button,
Text,
Preview,
Tailwind
} from '@react-email/components';
import * as React from 'react';
interface WelcomeEmailProps {
userName: string;
activationLink: string;
}
const WelcomeEmailTailwind: React.FC<WelcomeEmailProps> = ({
userName,
activationLink
}) => {
return (
<Html lang="zh-CN">
<Head>
<title>欢迎加入我们!</title>
</Head>
<Preview>欢迎{userName},请激活您的账户开始使用</Preview>
<Tailwind>
<Body className="bg-gray-50 font-sans m-0 p-5">
<div className="max-w-2xl mx-auto bg-white rounded-lg overflow-hidden">
{/* 邮件头部 */}
<Section className="bg-blue-500 py-8 px-5 text-center">
<Text className="text-white text-2xl font-bold m-0">
欢迎加入我们!
</Text>
</Section>
{/* 邮件内容 */}
<Section className="p-8">
<Text className="text-lg text-gray-800 leading-relaxed">
亲爱的 {userName},
</Text>
<Text className="text-base text-gray-600 leading-relaxed mt-4">
感谢您注册我们的服务。我们很高兴能为您提供优质的产品体验。
</Text>
<Text className="text-base text-gray-600 leading-relaxed mt-4">
请点击下方按钮激活您的账户:
</Text>
<Section className="text-center my-8">
<Button
href={activationLink}
className="bg-blue-500 text-white py-3 px-6 rounded-lg no-underline text-base font-bold inline-block"
>
激活账户
</Button>
</Section>
<Text className="text-sm text-gray-500 leading-relaxed mt-5">
如果按钮无法点击,请复制以下链接到浏览器地址栏:<br />
{activationLink}
</Text>
</Section>
{/* 邮件底部 */}
<Section className="bg-gray-100 py-5 px-5 text-center">
<Text className="text-xs text-gray-500">
© 2024 我们的公司. 保留所有权利.<br />
如果您有任何问题,请联系 support@example.com
</Text>
</Section>
</div>
</Body>
</Tailwind>
</Html>
);
};
export default WelcomeEmailTailwind;创建好邮件组件后,需要将它们转换成实际的HTML代码:
// renderEmail.ts
import { render } from '@react-email/render';
import WelcomeEmail from './emails/WelcomeEmail';
// 渲染为HTML字符串
const htmlContent = render(
<WelcomeEmail
userName="张三"
activationLink="https://example.com/activate?token=abc123"
/>,
{
pretty: true // 格式化输出,便于调试
}
);
// 保存到文件或发送邮件
console.log(htmlContent);
// 也可以渲染为纯文本
const textContent = render(
<WelcomeEmail
userName="张三"
activationLink="https://example.com/activate?token=abc123"
/>,
{
plainText: true
}
);在实际项目中,你可能会在服务器端生成并发送邮件:
// server/sendWelcomeEmail.ts
import { render } from '@react-email/render';
import WelcomeEmail from '../emails/WelcomeEmail';
import nodemailer from 'nodemailer';
async function sendWelcomeEmail(userEmail: string, userName: string) {
// 创建邮件传输器
const transporter = nodemailer.createTransport({
host: 'smtp.example.com',
port: 587,
secure: false,
auth: {
user: 'your-email@example.com',
pass: 'your-password'
}
});
// 渲染邮件内容
const html = await render(
<WelcomeEmail
userName={userName}
activationLink={`https://fly63.com/activate?email=${userEmail}`}
/>
);
const text = await render(
<WelcomeEmail
userName={userName}
activationLink={`https://fly63.com/activate?email=${userEmail}`}
/>,
{ plainText: true }
);
// 发送邮件
const mailOptions = {
from: '"我们的团队" <noreply@example.com>',
to: userEmail,
subject: `欢迎${userName}加入我们!`,
html: html,
text: text
};
try {
const result = await transporter.sendMail(mailOptions);
console.log('邮件发送成功:', result.messageId);
return result;
} catch (error) {
console.error('邮件发送失败:', error);
throw error;
}
}
export { sendWelcomeEmail };邮件模板应该简洁明了,避免过于复杂的设计。大多数邮件客户端对现代CSS支持有限。
在发送前,务必在主流邮件客户端测试显示效果,包括Gmail、Outlook、Apple Mail等。
充分利用TypeScript的类型检查,减少运行时错误。
将常用的邮件部分(如页头、页脚、按钮等)抽象为可复用组件。
// 可复用的按钮组件
interface EmailButtonProps {
href: string;
children: React.ReactNode;
variant?: 'primary' | 'secondary';
}
const EmailButton: React.FC<EmailButtonProps> = ({
href,
children,
variant = 'primary'
}) => {
const baseStyle = {
padding: '12px 24px',
borderRadius: '4px',
textDecoration: 'none',
fontSize: '16px',
fontWeight: 'bold',
display: 'inline-block' as const
};
const variantStyles = {
primary: {
backgroundColor: '#3b82f6',
color: '#ffffff'
},
secondary: {
backgroundColor: '#6b7280',
color: '#ffffff'
}
};
return (
<Button
href={href}
style={{ ...baseStyle, ...variantStyles[variant] }}
>
{children}
</Button>
);
};React Email彻底改变了电子邮件模板的开发方式。它让开发者能够使用熟悉的React组件化思维来创建邮件模板,结合TypeScript的类型安全和现代开发工具,大大提升了开发效率和代码质量。
无论你是要创建营销邮件、通知邮件还是事务性邮件,React Email都能提供良好的开发体验。它的无样式设计让你可以灵活选择样式方案,自动化的兼容性处理则省去了大量调试时间。
如果你正在寻找一种更现代、更高效的邮件模板开发方案,React Email绝对值得尝试。
仅供个人学习参考/导航指引使用,具体请以第三方网站说明为准,本站不提供任何专业建议。如果地址失效或描述有误,请联系站长反馈~感谢您的理解与支持!
手机预览