如何使用 Resend API 发送电子邮件:全攻略 (2026)
通过 Resend 开发者友好的 API 发送事务性邮件
开始使用 Hypereal 构建
通过单个 API 访问 Kling、Flux、Sora、Veo 等。免费积分开始,扩展到数百万。
无需信用卡 • 10万+ 开发者 • 企业级服务
如何使用 Resend API 发送邮件:完整指南 (2026)
Resend 是一款专为开发者打造的现代邮件 API,旨在解决传统邮件基础设施带来的困扰。由 React Email 团队开发,Resend 提供了简洁的 API、卓越的送达率,并对 Next.js、Node.js 和 Python 等框架提供了原生支持。
本指南将带你了解使用 Resend 开始发送事务性组件所需的一切,从账号设置到生产级代码示例。
为什么选择 Resend?
在深入了解之前,以下是 Resend 与其他替代方案的对比:
| 功能 | Resend | SendGrid | Amazon SES | Postmark |
|---|---|---|---|---|
| 免费档位 | 3,000 封/月 | 100 封/天 | 62,000 封/月 (12个月) | 100 封/月 |
| 起步价格 | $20/月 | $19.95/月 | $0.10 每 1,000 封 | $15/月 |
| React Email 支持 | 原生支持 | 不支持 | 不支持 | 不支持 |
| API 易用性 | 极佳 | 中等 | 复杂 | 良好 |
| Webhook 支持 | 是 | 是 | 是 (通过 SNS) | 是 |
| 自定义域名 | 是 | 是 | 是 | 是 |
Resend 以其开发者体验脱颖而出。其 API 非常精简,文档详尽,并且与 React Email 原生集成,可以使用 JSX 构建精美的邮件模板。
前置条件
开始之前,请确保你拥有:
- 一个 Resend 账号(在 resend.com 注册)
- 一个已验证的域名(或使用测试沙箱地址
onboarding@resend.dev) - 已安装 Node.js 18+ 或 Python 3.7+
- 来自 Resend 控制台的 API key
第一步:获取 API Key
- 登录 resend.com 控制台。
- 导航至侧边栏的 API Keys。
- 点击 Create API Key。
- 给它起个名字(如 "Production")并选择相应的权限。
- 立即复制该 key。它以
re_开头,且不会再次显示。
# 将你的 API key 存储为环境变量
export RESEND_API_KEY="re_your_api_key_here"
第二步:验证你的域名
要从你自己的域名(而非沙箱)发送邮件,你需要验证 DNS 记录。
- 进入 Resend 控制台的 Domains 页面。
- 点击 Add Domain 并输入你的域名(例如
mail.yourdomain.com)。 - 将 Resend 提供的 DNS 记录添加到你的域名注册商处:
| 记录类型 | 主机名 | 记录值 |
|---|---|---|
| TXT | _resend.yourdomain.com |
验证字符串 |
| MX | bounce.yourdomain.com |
由 Resend 提供 |
| TXT | bounce.yourdomain.com |
SPF 记录 |
| CNAME | resend._domainkey.yourdomain.com |
DKIM 记录 |
- 等待 DNS 记录生效后(通常需要 5-30 分钟),点击 Verify。
第三步:发送你的第一封邮件
使用 cURL
测试 API 最简单的方法:
curl -X POST 'https://api.resend.com/emails' \
-H 'Authorization: Bearer re_your_api_key_here' \
-H 'Content-Type: application/json' \
-d '{
"from": "You <hello@yourdomain.com>",
"to": ["recipient@example.com"],
"subject": "Hello from Resend",
"html": "<h1>Welcome!</h1><p>Your first email via Resend API.</p>"
}'
成功的响应将返回 200 状态码和邮件 ID:
{
"id": "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794"
}
使用 Node.js
安装官方 SDK:
npm install resend
发送邮件:
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
async function sendEmail() {
const { data, error } = await resend.emails.send({
from: 'You <hello@yourdomain.com>',
to: ['recipient@example.com'],
subject: 'Hello from Resend',
html: '<h1>Welcome!</h1><p>Your first email via Resend.</p>',
});
if (error) {
console.error('Failed to send email:', error);
return;
}
console.log('Email sent:', data.id);
}
sendEmail();
使用 Python
安装 Python SDK:
pip install resend
发送邮件:
import resend
import os
resend.api_key = os.environ["RESEND_API_KEY"]
params: resend.Emails.SendParams = {
"from": "You <hello@yourdomain.com>",
"to": ["recipient@example.com"],
"subject": "Hello from Resend",
"html": "<h1>Welcome!</h1><p>Your first email via Resend.</p>",
}
email = resend.Emails.send(params)
print(f"Email sent: {email['id']}")
第四步:使用 React Email 模板
Resend 最大的优势之一是原生支持 React Email。你可以使用 JSX 组件构建邮件模板,而不是编写原始的 HTML 表格。
安装 React Email:
npm install @react-email/components
创建一个模板:
// emails/welcome.tsx
import { Html, Head, Body, Container, Text, Button } from '@react-email/components';
export default function WelcomeEmail({ name }: { name: string }) {
return (
<Html>
<Head />
<Body style={{ fontFamily: 'Arial, sans-serif', backgroundColor: '#f4f4f5' }}>
<Container style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<Text style={{ fontSize: '24px', fontWeight: 'bold' }}>
Welcome, {name}!
</Text>
<Text>
Thank you for signing up. We are excited to have you on board.
</Text>
<Button
href="https://yourdomain.com/dashboard"
style={{
backgroundColor: '#000',
color: '#fff',
padding: '12px 24px',
borderRadius: '6px',
textDecoration: 'none',
}}
>
Go to Dashboard
</Button>
</Container>
</Body>
</Html>
);
}
通过 Resend 发送模板:
import { Resend } from 'resend';
import WelcomeEmail from './emails/welcome';
const resend = new Resend(process.env.RESEND_API_KEY);
await resend.emails.send({
from: 'You <hello@yourdomain.com>',
to: ['recipient@example.com'],
subject: 'Welcome to Our Platform',
react: WelcomeEmail({ name: 'Alice' }),
});
第五步:处理 Webhooks
Resend 可以通知你的服务器关于邮件的状态事件,如送达、退回(bounce)和打开。
- 进入 Resend 控制台的 Webhooks。
- 添加你的端点 URL(例如
https://yourdomain.com/api/webhooks/resend)。 - 选择你想要接收的事件。
在你的 API 路由中处理 webhook:
// app/api/webhooks/resend/route.ts (Next.js App Router)
import { NextRequest, NextResponse } from 'next/server';
export async function POST(req: NextRequest) {
const body = await req.json();
switch (body.type) {
case 'email.delivered':
console.log(`Email ${body.data.email_id} delivered to ${body.data.to}`);
break;
case 'email.bounced':
console.log(`Email ${body.data.email_id} bounced`);
// 从你的数据库中删除无效的邮件地址
break;
case 'email.complained':
console.log(`Spam complaint for ${body.data.email_id}`);
// 取消该用户的订阅
break;
}
return NextResponse.json({ received: true });
}
常见的 Webhook 事件
| 事件 | 描述 |
|---|---|
email.sent |
Resend 已接受邮件发送请求 |
email.delivered |
邮件已成功送达收件人的邮件服务器 |
email.bounced |
邮件被退回(无效地址) |
email.complained |
收件人将其标记为垃圾邮件 |
email.opened |
收件人打开了邮件 |
email.clicked |
收件人点击了邮件中的链接 |
第六步:批量发送
需要一次发送多封邮件?使用 batch 端点:
const { data, error } = await resend.batch.send([
{
from: 'You <hello@yourdomain.com>',
to: ['user1@example.com'],
subject: 'Your weekly report',
html: '<p>Here is your report...</p>',
},
{
from: 'You <hello@yourdomain.com>',
to: ['user2@example.com'],
subject: 'Your weekly report',
html: '<p>Here is your report...</p>',
},
]);
batch 端点每条请求支持多达 100 封邮件。
错误处理最佳实践
在使用 Resend API 时,始终要优雅地处理错误:
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
async function sendWithRetry(params, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const { data, error } = await resend.emails.send(params);
if (!error) return data;
if (error.statusCode === 429) {
// 触发频率限制 - 等待并重试
const delay = Math.pow(2, attempt) * 1000;
console.log(`Rate limited. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
// 不可重试的错误
throw new Error(`Resend API error: ${error.message}`);
}
throw new Error('Max retries exceeded');
}
速率限制 (Rate Limits)
| 方案 | 速率限制 |
|---|---|
| Free (免费) | 2 封/秒 |
| Pro (专业) | 50 封/秒 |
| Enterprise (企业) | 自定义 |
快速参考:API 端点
| 端点 | 方法 | 描述 |
|---|---|---|
/emails |
POST | 发送单封邮件 |
/emails/{id} |
GET | 获取邮件详情 |
/emails/{id} |
PATCH | 更新定时邮件 |
/emails/batch |
POST | 批量发送最多 100 封邮件 |
/domains |
GET | 列出已验证域名 |
/domains |
POST | 添加新域名 |
/api-keys |
POST | 创建 API key |
总结
Resend 为开发者简化了事务性邮件的处理流程。简洁的 API、React Email 集成以及慷慨的免费档位使其成为各种规模项目的卓越选择。从沙箱环境开始测试,验证你的域名以投入生产,并利用 webhooks 追踪邮件送达情况。
如果你正在构建需要配合邮件工作流生成多媒体内容的应用程序(例如在邮件中发送 AI 生成的图片或视频缩略图),请关注 Hypereal AI。Hypereal 提供了简洁的 API 用于 AI 图像生成、视频创作等,与事务性邮件流水线是绝佳的搭配。
