如何在Next.js的Nodemailer中使用React/JSX组件作为邮件模板?
Next.js 中使用 JSX 作为 Nodemailer 邮件模板的轻量方案
你提到的ReactDOMServer.renderToStaticMarkup完全可以在Next.js服务端环境使用,无法调用大概率是导入路径错误,正确的实现步骤如下:
1. 编写邮件JSX模板
创建独立的邮件模板组件,所有样式使用内联写法适配邮箱客户端规则:
// components/EmailTemplate.jsx export default function EmailTemplate({ content }) { return ( <div style={{ height: "100%", backgroundColor: "blue" }}> <div style={{ color: "white" }}>{content}</div> <div style={{ height: "20px", backgroundColor: "red" }}>{content}</div> </div> ) }
2. 服务端转换JSX为HTML字符串
在Next.js的API路由(Pages Router)或者Route Handler(App Router)中,正确导入renderToStaticMarkup方法,将组件渲染为纯HTML字符串:
// app/api/send-email/route.js (App Router写法) import { renderToStaticMarkup } from 'react-dom/server' import nodemailer from 'nodemailer' import EmailTemplate from '@/components/EmailTemplate' export async function POST(req) { const { textarea } = await req.json() // 转换JSX为HTML字符串 const emailHtml = renderToStaticMarkup(<EmailTemplate content={textarea} />) // 初始化Nodemailer传输器 const transporter = nodemailer.createTransport({ // 你的SMTP配置 host: 'smtp.你的邮箱服务商.com', port: 465, secure: true, auth: { user: '你的邮箱地址', pass: '你的邮箱授权码' } }) // 发送邮件 await transporter.sendMail({ from: '发件人名称 <发件人邮箱>', to: '收件人邮箱', subject: '邮件主题', html: emailHtml }) return Response.json({ success: true }) }
注意事项
- 邮件模板不要使用className、外部CSS、内部
<style>标签,所有样式用内联style属性编写,避免绝大多数邮箱客户端样式失效 - 若需要更完善的邮件兼容能力、内置响应式组件,可使用轻量的
react-email工具集,无需复杂配置即可生成高兼容的邮件HTML
内容的提问来源于stack exchange,提问作者Marius
相关产品推荐
相关产品推荐

