mailtrap-email-integration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMailtrap Email Integration
Mailtrap 邮件集成
Patterns for adding transactional email sending to an application using Mailtrap's Email API and Sandbox, covering authentication, environment separation, and common delivery pitfalls.
本指南介绍如何使用Mailtrap的Email API和Sandbox为应用添加事务性邮件发送功能,涵盖认证、环境隔离以及常见投递问题的解决方案。
When to Activate
适用场景
- Implementing a "send email" feature (signup confirmation, password reset, notifications, receipts)
- Debugging why emails aren't arriving in dev/staging
- Setting up a project's first email-sending integration
- Reviewing code that calls an email API directly without sandbox separation
- 实现“发送邮件”功能(注册确认、密码重置、通知、收据)
- 调试开发/预发布环境中邮件无法送达的问题
- 搭建项目首个邮件发送集成
- 审查未做沙箱隔离直接调用邮件API的代码
Core Concepts
核心概念
Sandbox vs. Production separation. Mailtrap provides a Sandbox API that captures emails without delivering them, used for dev/staging so test emails never reach real inboxes. Production sending uses a separate, verified-domain endpoint. Never point a dev environment at the production sending endpoint.
Authentication. Requests use a Bearer token in the header. Tokens are scoped per project; sandbox and production typically use different tokens.
AuthorizationDomain verification. Production sending requires verifying a sending domain via DNS records (SPF, DKIM, DMARC) before Mailtrap will deliver to real recipients. Skipping this causes silent delivery failures or spam-folder placement.
沙箱与生产环境隔离。Mailtrap提供Sandbox API,可捕获邮件而不实际投递,用于开发/预发布环境,确保测试邮件不会发送至真实收件箱。生产环境发送需使用独立的已验证域名端点。切勿将开发环境指向生产发送端点。
认证机制。请求需在头部携带Bearer令牌。令牌按项目划分权限,沙箱和生产环境通常使用不同的令牌。
Authorization域名验证。生产环境发送邮件前,需通过DNS记录(SPF、DKIM、DMARC)验证发送域名,否则Mailtrap不会将邮件投递至真实收件人。跳过此步骤会导致邮件静默投递失败或被放入垃圾邮件文件夹。
Code Examples
代码示例
typescript
// Sending via Mailtrap's Email API (production)
async function sendEmail(to: string, subject: string, html: string) {
const response = await fetch("https://send.api.mailtrap.io/api/send", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.MAILTRAP_API_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: { email: "no-reply@yourverifieddomain.com", name: "Your App" },
to: [{ email: to }],
subject,
html,
}),
});
if (!response.ok) {
throw new Error(`Email send failed: ${response.status}`);
}
return response.json();
}typescript
// Same call, routed to Sandbox in non-production environments
const MAILTRAP_ENDPOINT = process.env.NODE_ENV === "production"
? "https://send.api.mailtrap.io/api/send"
: `https://sandbox.api.mailtrap.io/api/send/${process.env.MAILTRAP_INBOX_ID}`;typescript
// Sending via Mailtrap's Email API (production)
async function sendEmail(to: string, subject: string, html: string) {
const response = await fetch("https://send.api.mailtrap.io/api/send", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.MAILTRAP_API_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: { email: "no-reply@yourverifieddomain.com", name: "Your App" },
to: [{ email: to }],
subject,
html,
}),
});
if (!response.ok) {
throw new Error(`Email send failed: ${response.status}`);
}
return response.json();
}typescript
// Same call, routed to Sandbox in non-production environments
const MAILTRAP_ENDPOINT = process.env.NODE_ENV === "production"
? "https://send.api.mailtrap.io/api/send"
: `https://sandbox.api.mailtrap.io/api/send/${process.env.MAILTRAP_INBOX_ID}`;Anti-Patterns
反模式
| Anti-Pattern | Why It's a Problem | Instead |
|---|---|---|
| Using the production sending endpoint in dev/test | Real test emails reach real inboxes, risking spam complaints and leaked test data | Route non-production environments to the Sandbox endpoint |
| Hardcoding API tokens in source | Credential leak risk if committed to version control | Load tokens from environment variables / secrets manager |
| Sending before domain verification completes | Emails silently fail or land in spam | Verify SPF/DKIM/DMARC records before enabling production sending |
| No retry/error handling on send failures | Silent notification failures (e.g., user never gets password reset email) | Check response status, log failures, surface actionable errors |
| 反模式 | 问题所在 | 正确做法 |
|---|---|---|
| 在开发/测试环境使用生产发送端点 | 测试邮件会发送至真实收件箱,可能引发垃圾邮件投诉和测试数据泄露 | 将非生产环境流量路由至Sandbox端点 |
| 在源码中硬编码API令牌 | 若提交至版本控制系统,存在凭证泄露风险 | 从环境变量/密钥管理器加载令牌 |
| 域名验证完成前就发送邮件 | 邮件会静默失败或被放入垃圾邮件文件夹 | 启用生产发送前先验证SPF/DKIM/DMARC记录 |
| 发送失败时无重试/错误处理机制 | 通知会静默失败(例如用户无法收到密码重置邮件) | 检查响应状态、记录失败信息并提供可操作的错误提示 |
Best Practices
最佳实践
- Keep sandbox and production tokens in separate environment variables, never share one token across environments
- Verify sending domain DNS records before any production launch involving email
- Log delivery failures with enough context to debug (recipient, template, timestamp, response code)
- Treat email sending as a fallible network call: wrap in try/catch, never assume success
- 将沙箱和生产环境令牌分别存储在不同的环境变量中,切勿跨环境共享同一令牌
- 在任何涉及邮件的生产发布前,验证发送域名的DNS记录
- 记录投递失败信息时包含足够的调试上下文(收件人、模板、时间戳、响应码)
- 将邮件发送视为易出错的网络调用:用try/catch包裹,切勿假设发送一定会成功
Related Skills
相关技能
api-and-interface-designsecurity-and-hardeningci-cd-and-automationapi-and-interface-designsecurity-and-hardeningci-cd-and-automation