Web前端开发网

fly63.com

首页 资源 工具 文章 教程 栏目
  • 关于我们
  • 广告合作
  • 网站投稿
  • 文章标签
  • 赞助一下
搜索

在线工具_工作生活好帮手

打造各种简单、易用、便捷的在线工具,网友无需注册和下载安装即可使用

点击查看

资源分类

AI智能 酷站推荐 招聘/兼职 框架/库 模块/管理 移动端UI框架 Web-UI框架 Js插件 Jquery插件 CSS相关 IDE环境 在线工具 图形动效 游戏框架 node相关 调试/测试 在线学习 社区/论坛 博客/团队 前端素材 图标/图库 建站资源 设计/灵感 IT资讯
提交资源 / 链接反馈

React Email

分享
复制链接
新浪微博
QQ 好友

扫一扫分享

网站地址:https://react.email
GitHub:https://github.com/resend/react-email
网站描述:下一代无样式组件集合,解锁精美邮件开发
访问官网 GitHub

传统的邮件模板开发依赖复杂的html表格和内联css,还要面对各种邮件客户端的兼容性问题。这个过程既繁琐又难以维护,让很多开发者感到头疼。现在,react Email正在改变这一现状。


什么是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组件详解

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'}}/>
TailwindTailwind包装器children<Tailwind><div className="p-4">内容</div></Tailwind>

开始使用React Email

环境搭建

首先创建项目并安装必要的依赖:

# 创建新项目
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 CSS的版本

如果你更喜欢使用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

创建好邮件组件后,需要将它们转换成实际的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 
  }
);


在Node.js服务器中使用

在实际项目中,你可能会在服务器端生成并发送邮件:

// 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 };


最佳实践和建议

1. 保持设计简洁

邮件模板应该简洁明了,避免过于复杂的设计。大多数邮件客户端对现代CSS支持有限。

2. 测试兼容性

在发送前,务必在主流邮件客户端测试显示效果,包括Gmail、Outlook、Apple Mail等。

3. 使用TypeScript

充分利用TypeScript的类型检查,减少运行时错误。

4. 组件化思维

将常用的邮件部分(如页头、页脚、按钮等)抽象为可复用组件。

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绝对值得尝试。

仅供个人学习参考/导航指引使用,具体请以第三方网站说明为准,本站不提供任何专业建议。如果地址失效或描述有误,请联系站长反馈~感谢您的理解与支持!

链接: https://fly63.com/nav/4790

more>>
相关栏目
layer
layer是一款口碑极佳的web弹层组件
点击进入 GitHub
iScroll.js
IScroll是移动页面上被使用的一款仿系统滚动插件。
官网 GitHub
wangEditor
基于javascript和css开发的 Web富文本编辑器
官网 GitHub
ueditor
由百度web前端研发部开发所见即所得富文本web编辑器
官网 GitHub
highlight
Highlight.js 是一个用 JavaScript 写的代码高亮插件,在客户端和服务端都能工作。
官网 GitHub
UglifyJS
一个js 解释器、最小化器、压缩器、美化器工具集
官网 GitHub
lozad.js
高性能,轻量级,可配置的懒加载图片工具
官网 GitHub
Sortable.js
简单灵活的 JavaScript 拖放排序插件
官网 GitHub
validate.js
表单提供了强大的验证功能,让客户端表单验证变得更简单
官网 GitHub
Draggin.js
一款兼容移动手机的js拖拽插件
官网 GitHub
lazysizes.js
响应式图像延迟加载JS插件【懒加载】
官网 GitHub
cropper.js
通过canvas实现图片裁剪
官网 GitHub
clipboard.js
浏览器中复制文本到剪贴板的插件,不需要Flash,仅仅2kb
官网 GitHub
siema
轻量级简单的纯 Js轮播插件
官网 GitHub
Mermrender
用于生成序列和UML图的RESTful渲染管道
官网 GitHub
Editor.js
JSON格式输出数据的富文本和媒体编辑器
官网 GitHub

手机预览

首页 技术导航 在线工具 技术文章 教程资源 AI工具集 前端库/框架 实用工具箱

Copyright © 2018 Web前端开发网提供免费在线工具、编程学习资源(教程/框架/库),内容以学习参考为主,助您解决各类实际问题,快速提升专业能力。