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

如何使用Next.js将带样式的React组件以HTML形式发送邮件

解决SendGrid + Next.js/React中React组件转HTML邮件的JSON序列化错误

问题背景

用SendGrid、Next.js和React开发邮件发送功能,目标是将带样式的React组件转换为HTML格式发送。已经完成带样式组件的创建和邮件发送API接口编写,但在主页表单提交时,直接将React组件作为html字段传入消息对象,执行JSON.stringify时触发错误:

TypeError: Converting circular structure to JSON

错误原因

React组件本质是包含循环引用的JavaScript对象(比如组件props中存在父组件引用、内部状态关联等循环依赖结构),而JSON.stringify无法处理这种循环引用的对象,因此直接传递组件对象会导致序列化失败。

解决方案

使用ReactDOMServer提供的renderToStaticMarkup方法,将React组件转换为静态HTML字符串,再将该字符串传入消息对象的html字段。

代码示例

  1. 导入ReactDOMServer:
import ReactDOMServer from 'react-dom/server';
  1. 定义你的带样式邮件组件:
const EmailTemplate = ({ username, userMessage }) => (
  <div style={{ padding: '24px', backgroundColor: '#f8f9fa', borderRadius: '8px' }}>
    <h3 style={{ color: '#2d3748' }}>来自{username}的新消息</h3>
    <p style={{ color: '#4a5568', lineHeight: '1.6' }}>{userMessage}</p>
  </div>
);
  1. 将组件转换为HTML字符串并构造SendGrid消息:
// 从表单获取用户输入
const username = '张三';
const userMessage = '这是测试邮件内容';

// 转换组件为静态HTML字符串
const emailHtml = ReactDOMServer.renderToStaticMarkup(
  <EmailTemplate username={username} userMessage={userMessage} />
);

// 构造SendGrid消息对象
const msg = {
  to: 'target@example.com',
  from: 'sender@example.com',
  subject: '新消息通知',
  html: emailHtml // 传入HTML字符串而非组件对象
};

// 调用SendGrid API发送邮件(示例)
// await sgMail.send(msg);

为什么用renderToStaticMarkup?

该方法会生成不包含React内部标识属性(如data-reactroot)的纯HTML代码,更适合作为邮件内容,避免引入不必要的冗余标记,同时保证HTML结构的完整性和样式的正常渲染。

内容的提问来源于stack exchange,提问作者daniel sas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:20:42