You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在现有React项目中通过Resend集成React Email?

在React项目中通过Resend集成React Email实现表单邮件自动化

步骤1:获取Resend API密钥

  • 注册Resend账号,进入控制台创建并保存API密钥(注意保密,不要提交到代码仓库)
  • 在项目根目录新建.env文件,添加密钥配置:
    # 后端环境变量(生产环境必须用后端中转,禁止前端直接暴露)
    RESEND_API_KEY=你的Resend密钥
    

步骤2:创建React Email邮件模板

在项目中新建src/emails/ContactFormEmail.jsx文件,用@react-email/components构建邮件内容:

import { Html, Body, Container, Heading, Paragraph, Text } from '@react-email/components';

export default function ContactFormEmail({ name, email, message }) {
  return (
    <Html>
      <Body style={{ fontFamily: 'system-ui, sans-serif' }}>
        <Container style={{ maxWidth: '620px', margin: '30px auto', padding: '20px' }}>
          <Heading style={{ color: '#2d3748' }}>新的作品集表单提交</Heading>
          <Paragraph style={{ fontSize: '16px', lineHeight: '1.6' }}>你收到一条来自访客的消息:</Paragraph>
          <Text style={{ fontSize: '16px', margin: '8px 0' }}><strong>姓名:</strong>{name}</Text>
          <Text style={{ fontSize: '16px', margin: '8px 0' }}><strong>联系邮箱:</strong>{email}</Text>
          <Text style={{ fontSize: '16px', margin: '8px 0' }}><strong>内容:</strong>{message}</Text>
        </Container>
      </Body>
    </Html>
  );
}

步骤3:搭建后端中转接口(核心!避免密钥泄露)

前端不能直接调用Resend API(会暴露密钥),必须通过后端中转。这里以Express为例,Vercel/Netlify Serverless函数逻辑一致:

  1. 安装依赖:
npm install express cors dotenv
  1. 新建server.js文件:
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const { Resend } = require('resend');
const ContactFormEmail = require('./src/emails/ContactFormEmail').default;

const app = express();
app.use(cors());
app.use(express.json());

// 初始化Resend客户端
const resend = new Resend(process.env.RESEND_API_KEY);

// 邮件发送接口
app.post('/api/send-email', async (req, res) => {
  const { name, email, message } = req.body;

  try {
    const result = await resend.emails.send({
      from: '作品集官网 <onboarding@resend.dev>', // 免费版可用默认地址,生产建议绑定验证过的自有域名
      to: '你的接收邮箱@example.com', // 你要接收消息的邮箱
      subject: `新消息来自${name}`,
      react: ContactFormEmail({ name, email, message }),
    });

    res.status(200).json({ success: true, data: result });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`后端服务运行在端口${PORT}`));

步骤4:前端表单提交逻辑

修改你的表单组件,添加提交事件:

import { useState } from 'react';

function ContactForm() {
  const [formData, setFormData] = useState({ name: '', email: '', message: '' });
  const [isLoading, setIsLoading] = useState(false);
  const [status, setStatus] = useState('');

  const handleInputChange = (e) => {
    setFormData(prev => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setStatus('');

    try {
      const response = await fetch('http://localhost:3001/api/send-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      const data = await response.json();
      if (data.success) {
        setStatus('消息发送成功!');
        setFormData({ name: '', email: '', message: '' });
      } else {
        setStatus(`发送失败:${data.error}`);
      }
    } catch (err) {
      setStatus('网络异常,请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} style={{ maxWidth: '500px', margin: '0 auto' }}>
      <div style={{ marginBottom: '16px' }}>
        <label style={{ display: 'block', marginBottom: '4px' }}>姓名</label>
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleInputChange}
          required
          style={{ width: '100%', padding: '8px' }}
        />
      </div>
      <div style={{ marginBottom: '16px' }}>
        <label style={{ display: 'block', marginBottom: '4px' }}>邮箱</label>
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleInputChange}
          required
          style={{ width: '100%', padding: '8px' }}
        />
      </div>
      <div style={{ marginBottom: '16px' }}>
        <label style={{ display: 'block', marginBottom: '4px' }}>留言</label>
        <textarea
          name="message"
          value={formData.message}
          onChange={handleInputChange}
          required
          rows="4"
          style={{ width: '100%', padding: '8px' }}
        />
      </div>
      <button
        type="submit"
        disabled={isLoading}
        style={{ padding: '10px 20px', cursor: 'pointer' }}
      >
        {isLoading ? '发送中...' : '提交留言'}
      </button>
      {status && <p style={{ marginTop: '12px', color: status.includes('成功') ? '#2f855a' : '#c53030' }}>{status}</p>}
    </form>
  );
}

export default ContactForm;

步骤5:测试运行

  1. 启动后端服务:node server.js
  2. 启动React项目:npm start
  3. 填写表单提交,检查接收邮箱是否收到邮件

注意事项

  • Resend的from邮箱在免费版可使用默认的onboarding@resend.dev,生产环境建议绑定并验证自有域名,提升邮件可信度
  • 生产环境需将后端部署到服务器(如Vercel、Heroku),不要用localhost
  • 可添加前端表单验证(如邮箱格式校验),过滤无效提交

内容的提问来源于stack exchange,提问作者Ryan Bitonio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 01:55:37