关于 email-sending
提供邮件发送实现示例,涵盖 Node.js、Python 和 Java,以及 SMTP 与事务邮件服务。内容还介绍模板方案和保障邮件可靠送达的运营检查项。
主要功能
- 01使用 Nodemailer 通过 SMTP 发信
- 02事务邮件服务示例
- 03React Email 与 MJML 模板
- 04Python 和 Java 示例
- 05送达与重试实践
- 06生产环境邮件检查清单
适用场景
- 01发送应用事务邮件
- 02制作欢迎或密码重置模板邮件
- 03为服务配置邮件投递
- 04准备生产环境邮件发送
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill email-sending安装后在 Claude Code 中输入/email-sending确认已加载。
详细介绍
发送电子邮件
Node.js(Nodemailer)
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: 587,
secure: false, // true for 465
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});
await transporter.sendMail({
from: '"My App" <[email protected]>',
to: '[email protected]',
subject: 'Welcome!',
html: '<h1>Welcome</h1><p>Thanks for signing up.</p>',
});
事务性电子邮件服务
Resend(推荐,简单易用)
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
await resend.emails.send({
from: 'My App <[email protected]>',
to: ['[email protected]'],
subject: 'Welcome!',
html: '<h1>Welcome</h1>',
});
SendGrid
import sgMail from '@sendgrid/mail';
sgMail.setApiKey(process.env.SENDGRID_API_KEY!);
await sgMail.send({
to: '[email protected]',
from: '[email protected]',
templateId: 'd-abc123', // Dynamic template
dynamicTemplateData: { name: 'John', link: resetUrl },
});
Amazon SES(通过 AWS SDK v3)
import { SESv2Client, SendEmailCommand } from '@aws-sdk/client-sesv2';
const ses = new SESv2Client({ region: 'us-east-1' });
await ses.send(new SendEmailCommand({
FromEmailAddress: '[email protected]',
Destination: { ToAddresses: ['[email protected]'] },
Content: {
Simple: {
Subject: { Data: 'Welcome!' },
Body: { Html: { Data: htmlContent } },
},
},
}));
电子邮件模板
React Email(推荐用于 React 项目)
// emails/welcome.tsx
import { Html, Head, Body, Container, Text, Button } from '@react-email/components';
export function WelcomeEmail({ name, url }: { name: string; url: string }) {
return (
<Html>
<Head />
<Body style={{ fontFamily: 'sans-serif' }}>
<Container>
<Text>Welcome, {name}!</Text>
<Button href={url} style={{ background: '#000', color: '#fff', padding: '12px 20px' }}>
Get Started
</Button>
</Container>
</Body>
</Html>
);
}
// Render to HTML string
import { render } from '@react-email/render';
const html = await render(<WelcomeEmail name="John" url="https://app.com" />);
MJML(与框架无关)
import mjml2html from 'mjml';
const { html } = mjml2html(`
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text>Welcome, {{name}}!</mj-text>
<mj-button href="{{url}}">Get Started</mj-button>
</mj-column>
</mj-section>
</mj-body>
</mjml>
`);
Python
from email.message import EmailMessage
import aiosmtplib
msg = EmailMessage()
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = "Welcome!"
msg.set_content("Welcome!", subtype="html")
await aiosmtplib.send(msg, hostname=SMTP_HOST, port=587,
username=SMTP_USER, password=SMTP_PASS, start_tls=True)
Java(Spring Mail)
@Service
public class EmailService {
@Autowired private JavaMailSender mailSender;
@Autowired private TemplateEngine templateEngine; // Thymeleaf
public void sendWelcome(String to, String name) {
var ctx = new Context();
ctx.setVariable("name", name);
String html = templateEngine.process("welcome", ctx);
var message = mailSender.createMimeMessage();
var helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setFrom("[email protected]");
helper.setSubject("Welcome!");
helper.setText(html, true);
mailSender.send(message);
}
}
反模式
| 反模式 | 修正方法 |
|---|---|
| 在请求处理程序中发送电子邮件 | 使用后台作业队列(BullMQ、Celery) |
| 临时故障时不重试 | 使用指数退避重试(3 次) |
| 发件人地址硬编码 | 使用环境变量,并匹配已验证的域名 |
| HTML 邮件没有纯文本备用版本 | 始终同时包含 HTML 和纯文本版本 |
| 没有退订标头 | 添加 List-Unsubscribe 标头(Gmail/Yahoo 要求) |
| 使用未验证的域名发送邮件 | 设置 SPF、DKIM、DMARC 记录 |
生产环境检查清单
- 已配置 SPF、DKIM、DMARC DNS 记录
- 已在电子邮件服务提供商处验证域名
- 营销邮件包含
List-Unsubscribe标头 - 处理退信和投诉(webhook)
- 通过后台队列发送电子邮件(而非在请求中发送)
- 实施速率限制,确保不超出服务提供商的限制
- 所有 HTML 邮件均提供纯文本备用版本
- 部署前预览/测试模板
评论
支持 Markdown