sinch-mailgun
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMailgun Email API
Mailgun 电子邮件API
Agent Instructions
Agent操作说明
- Always ask the user for their region (US or EU) if not already known. Region determines the base URL and cannot be changed after domain creation.
- Before generating code, check for existing files or environment variables for
.envandMAILGUN_API_KEY.MAILGUN_DOMAIN - When the user mentions events, logs, stats, or tags — use the current APIs (), never the deprecated v3 endpoints.
/v1/analytics/* - For domain CRUD operations, use (not v3).
/v4/domains - For detailed API parameters, fetch the linked doc pages rather than guessing.
.md
- 如果尚未知晓用户所在区域,务必询问用户(美国或欧盟)。区域决定了基础URL,且域名创建后无法更改。
- 在生成代码前,检查是否存在文件或
.env、MAILGUN_API_KEY环境变量。MAILGUN_DOMAIN - 当用户提及事件、日志、统计数据或标签时,请使用当前的API(),切勿使用已弃用的v3端点。
/v1/analytics/* - 对于域名的CRUD操作,请使用(而非v3版本)。
/v4/domains - 如需详细的API参数,请参考链接的文档页面,切勿自行猜测。
.md
Overview
概述
Mailgun (by Sinch) provides REST API and SMTP relay for transactional and bulk email — sending, receiving, tracking, and suppression management.
Mailgun(由Sinch提供)为事务性邮件和批量邮件提供REST API与SMTP中继服务,涵盖发送、接收、跟踪以及抑制列表管理等功能。
Getting Started
快速开始
Authentication
认证
See sinch-authentication for full auth setup.
All requests use HTTP Basic Auth — username: , password: your Mailgun private API key. Find it at Mailgun Dashboard > Account Settings > API Keys.
apiTwo key types:
- Primary Account API Key — full access to all endpoints and domains
- Domain Sending Keys — restricted to and
POST /messagesfor one domain/messages.mime
完整的认证设置请查看Sinch认证。
所有请求均使用HTTP基础认证——用户名:,密码:你的Mailgun私有API密钥。可在Mailgun控制台 > 账户设置 > API密钥中找到该密钥。
api密钥分为两种类型:
- 主账户API密钥——拥有所有端点和域名的完全访问权限
- 域名发送密钥——仅对单个域名的和
POST /messages端点具有访问权限/messages.mime
Base URLs
基础URL
Always match the base URL to the domain's region. Data never crosses regions.
| Service | US | EU |
|---|---|---|
| REST API | | |
| Outgoing SMTP | | |
| Inbound SMTP | | |
| Open/Click Tracking | | |
请确保基础URL与域名所在区域匹配,数据不会跨区域传输。
| 服务 | 美国 | 欧盟 |
|---|---|---|
| REST API | | |
| 出站SMTP | | |
| 入站SMTP | | |
| 打开/点击跟踪 | | |
Send an Email
发送电子邮件
bash
curl -s --user 'api:YOUR_API_KEY' \
https://api.mailgun.net/v3/YOUR_DOMAIN/messages \
-F from='Sender <sender@YOUR_DOMAIN>' \
-F to='recipient@example.com' \
-F subject='Hello from Mailgun' \
-F text='This is a test email.' \
-F html='<h1>Hello</h1><p>HTML body.</p>'Response:
{"id": "<message-id@YOUR_DOMAIN>", "message": "Queued. Thank you."}The Messages API uses — use flags, not with JSON.
multipart/form-data-F-dbash
curl -s --user 'api:YOUR_API_KEY' \
https://api.mailgun.net/v3/YOUR_DOMAIN/messages \
-F from='Sender <sender@YOUR_DOMAIN>' \
-F to='recipient@example.com' \
-F subject='Hello from Mailgun' \
-F text='This is a test email.' \
-F html='<h1>Hello</h1><p>HTML body.</p>'响应:
{"id": "<message-id@YOUR_DOMAIN>", "message": "Queued. Thank you."}Messages API使用格式——请使用参数,而非参数传递JSON。
multipart/form-data-F-dNode.js SDK
Node.js SDK
bash
npm install mailgun.js form-datajavascript
const Mailgun = require('mailgun.js');
const formData = require('form-data');
const mg = new Mailgun(formData).client({
username: 'api',
key: 'YOUR_API_KEY',
// For EU: url: 'https://api.eu.mailgun.net'
});
mg.messages.create('YOUR_DOMAIN', {
from: 'Sender <sender@YOUR_DOMAIN>',
to: ['recipient@example.com'],
subject: 'Hello',
text: 'Testing Mailgun!',
});For other SDKs: SDK Reference
bash
npm install mailgun.js form-datajavascript
const Mailgun = require('mailgun.js');
const formData = require('form-data');
const mg = new Mailgun(formData).client({
username: 'api',
key: 'YOUR_API_KEY',
// 欧盟区域请使用: url: 'https://api.eu.mailgun.net'
});
mg.messages.create('YOUR_DOMAIN', {
from: 'Sender <sender@YOUR_DOMAIN>',
to: ['recipient@example.com'],
subject: 'Hello',
text: 'Testing Mailgun!',
});其他SDK请查看:SDK参考文档
Key Concepts
核心概念
Domains
域名
- Sandbox domain — provided on signup (e.g., ). Only pre-authorized recipients can receive mail.
sandboxXXX.mailgun.org - Custom domain — requires DNS verification (SPF, DKIM, MX). Domain CRUD uses (not v3). Only
/v4/domainsremains on v3. See Domains APIDELETE
- 沙箱域名——注册时提供(例如:)。仅预授权收件人可接收邮件。
sandboxXXX.mailgun.org - 自定义域名——需要DNS验证(SPF、DKIM、MX记录)。域名的CRUD操作请使用(而非v3版本)。仅
/v4/domains操作仍保留在v3版本中。详情请查看域名APIDELETE
Sending
邮件发送
- REST API — with
POST /v3/{domain}/messages,from,to,cc,bcc,subject,text,html, attachments, headers, tags, variablesamp-html - SMTP — port 587 TLS, credentials per-domain via
smtp.mailgun.org. See Credentials API/v3/domains/{domain}/credentials - MIME —
POST /v3/{domain}/messages.mime - Batch — up to 1,000 recipients per call using for personalization
recipient-variables - Test mode — add to simulate without delivery
o:testmode=yes - Scheduling — (RFC-2822),
o:deliverytime(STO),o:deliverytime-optimize-period(TZO)o:time-zone-localize - Tracking — ,
o:tracking,o:tracking-clicksper message; or configure at domain level viao:tracking-opens. See Domain Tracking API/v3/domains/{name}/tracking
Send options (, , , params) are limited to 16KB total per request.
o:h:v:t:For full parameters: Messages API
- REST API——调用,参数包含
POST /v3/{domain}/messages、from、to、cc、bcc、subject、text、html、附件、请求头、标签、变量amp-html - SMTP——使用的587端口(TLS加密),每个域名的凭据可通过
smtp.mailgun.org获取。详情请查看凭据API/v3/domains/{domain}/credentials - MIME格式——调用
POST /v3/{domain}/messages.mime - 批量发送——每次调用最多支持1000个收件人,使用实现个性化
recipient-variables - 测试模式——添加参数即可模拟发送,不会实际投递邮件
o:testmode=yes - 定时发送——使用(RFC-2822格式)、
o:deliverytime(STO)、o:deliverytime-optimize-period(TZO)参数o:time-zone-localize - 跟踪功能——可针对单条邮件设置、
o:tracking、o:tracking-clicks参数;也可通过o:tracking-opens在域名层面配置。详情请查看域名跟踪API/v3/domains/{name}/tracking
发送选项(、、、参数)总大小限制为16KB。
o:h:v:t:完整参数请查看:Messages API
Templates
模板
Two levels:
- Domain — . See Domain Templates API
/v3/{domain}/templates - Account — (shared across all domains). See Account Templates API
/v4/templates
Reference by name when sending: . Each template supports up to 40 versions.
-F template='welcome-template' -F t:variables='{"name":"John"}'Webhooks
Webhook
Real-time HTTP POST notifications for email events.
- Domain — (v3) or
/v3/domains/{domain}/webhooks(v4). See Domain Webhooks API/v4/domains/{domain}/webhooks - Account — (fires across all domains). See Account Webhooks API
/v1/webhooks
Event types: , , , , , , ,
clickedcomplaineddeliveredfailedopenedpermanent_failtemporary_failunsubscribed针对邮件事件的实时HTTP POST通知。
- 域名级别——(v3)或
/v3/domains/{domain}/webhooks(v4)。详情请查看域名Webhook API/v4/domains/{domain}/webhooks - 账户级别——(针对所有域名触发)。详情请查看账户Webhook API
/v1/webhooks
事件类型:、、、、、、、
clickedcomplaineddeliveredfailedopenedpermanent_failtemporary_failunsubscribedEvents and Analytics
事件与分析
- Logs — for querying event data. The legacy
POST /v1/analytics/logsis deprecated. See Logs APIGET /v3/{domain}/events - Metrics — for aggregated analytics with dimensions, filters, resolutions. Replaces deprecated
POST /v1/analytics/metrics. See Metrics API/v3/stats - Tags — when sending; manage via
o:tag. Legacy/v1/analytics/tagsis deprecated. See Tags API/v3/{domain}/tags
Data retention: Logs — at least 3 days (legacy). Metrics — hourly 60 days, daily 1 year, monthly indefinite.
Inbound Routing
入站路由
Routes API — match incoming messages by recipient pattern or header expression, then forward, store, or webhook. Configure both and MX records.
mxamxbSuppressions and Allowlists
抑制列表与白名单
Per-domain suppression lists that Mailgun auto-populates. Sending to suppressed addresses silently drops.
- Bounces —
/v3/{domain}/bounces - Unsubscribes —
/v3/{domain}/unsubscribes - Complaints —
/v3/{domain}/complaints - Allowlist — — prevents addresses from being added to bounce lists
/v3/{domain}/whitelists
Mailing Lists
邮件列表
Mailing Lists API — to create/manage lists, for members. Bulk upload via or endpoints.
/v3/lists/v3/lists/{address}/members.json.csvStored Messages
存储的邮件
Retrieve: . Resend: to same path. See Messages API
GET /v3/domains/{domain}/messages/{storage_key}POSTInfrastructure Management
基础设施管理
For IPs, IP Pools, IP Warmup, DKIM Keys, and Subaccounts — see references/infrastructure.md.
关于IP、IP池、IP预热、DKIM密钥和子账户的内容,请查看references/infrastructure.md。
Common Patterns
常见模式
Batch send with personalization
个性化批量发送
Add as JSON mapping each recipient address to their variables. Use in subject/body. Max 1,000 recipients per call. See Batch Sending
recipient-variables%recipient.variable_name%添加参数,以JSON格式映射每个收件人地址对应的变量。在主题/正文中使用引用变量。每次调用最多支持1000个收件人。详情请查看批量发送
recipient-variables%recipient.variable_name%Set up domain webhooks
设置域名Webhook
- Create webhook via with
POST /v3/domains/{domain}/webhooks(event type) andidfieldsurl - Verify HMAC signature on incoming webhooks using your webhook signing key (SHA256). See Securing Webhooks
- Return 2xx or Mailgun retries with exponential backoff for ~8 hours
- 通过创建Webhook,参数包含
POST /v3/domains/{domain}/webhooks(事件类型)和id字段url - 使用你的Webhook签名密钥(SHA256)验证入站Webhook的HMAC签名。详情请查看Webhook安全
- 返回2xx状态码,否则Mailgun会以指数退避策略重试约8小时
Schedule and cancel delivery
定时发送与取消投递
- Schedule: add to send call
-F o:deliverytime='RFC-2822-date' - Cancel: to bulk-delete all scheduled/undelivered mail
DELETE /v3/{domain}/envelopes
- 定时发送:在发送请求中添加参数
-F o:deliverytime='RFC-2822格式日期' - 取消投递:调用批量删除所有已定时/未投递的邮件
DELETE /v3/{domain}/envelopes
Configure inbound email
配置入站邮件
- Add MX records pointing to and
mxa.mailgun.org(priority 10)mxb.mailgun.org - Create route via with
POST /v3/routes(match pattern) andexpression(forward/store/webhook). See Routes Guideaction
- 添加MX记录,指向和
mxa.mailgun.org(优先级10)mxb.mailgun.org - 通过创建路由,参数包含
POST /v3/routes(匹配模式)和expression(转发/存储/Webhook)。详情请查看路由指南action
Gotchas
注意事项
- Sandbox domains — only pre-authorized recipients. Add them in the dashboard first.
- Region mismatch — always use the base URL matching the domain's region. US domains 404 on EU endpoints and vice versa.
- only — the Messages endpoint does not accept JSON. Use
multipart/form-datain curl.-F - Date format — RFC-2822 with numerical timezone offsets (+0500), not abbreviated names (EST, CET).
- Domains API is v4 — use for CRUD. Only
/v4/domainsremains on v3.DELETE /v3/domains/{name} - Events/Stats deprecated — use (not
POST /v1/analytics/logs) andGET /v3/{domain}/events(notPOST /v1/analytics/metrics)./v3/stats - Tags deprecated — use (not
/v1/analytics/tags)./v3/{domain}/tags - Suppression auto-populate — Mailgun silently drops messages to bounced/unsubscribed/complained addresses.
- Rate limits — response. Check
429,X-RateLimit-Limit,X-RateLimit-Remainingheaders. Use exponential backoff.X-RateLimit-Reset - Send options 16KB cap — ,
o:,h:,v:params combined max 16KB per request.t: - Webhook caching — changes take up to 10 minutes. URLs are deduplicated across account and domain levels.
- IP warmup — new dedicated IPs need gradual volume ramp. Use to manage programmatically.
/v3/ip_warmups - Two MX records — configure both and
mxafor inbound routing.mxb - API key security — never expose the primary key client-side. Use Domain Sending Keys for restricted access.
- 沙箱域名——仅允许预授权收件人接收邮件。需先在控制台添加收件人。
- 区域不匹配——务必使用与域名所在区域匹配的基础URL。美国域名在欧盟端点会返回404,反之亦然。
- 仅支持multipart/form-data格式——Messages端点不接受JSON格式。请在curl中使用参数。
-F - 日期格式——需使用带数字时区偏移的RFC-2822格式(如+0500),而非时区缩写(如EST、CET)。
- 域名API为v4版本——CRUD操作请使用。仅
/v4/domains仍保留在v3版本。DELETE /v3/domains/{name} - 事件/统计接口已弃用——请使用(而非
POST /v1/analytics/logs)和GET /v3/{domain}/events(而非POST /v1/analytics/metrics)。/v3/stats - 标签接口已弃用——请使用(而非
/v1/analytics/tags)。/v3/{domain}/tags - 抑制列表自动填充——Mailgun会静默丢弃发送给退信/退订/投诉地址的邮件。
- 速率限制——返回响应时,请查看
429、X-RateLimit-Limit、X-RateLimit-Remaining请求头。建议使用指数退避策略重试。X-RateLimit-Reset - 发送选项大小限制——、
o:、h:、v:参数总大小不超过16KB。t: - Webhook缓存——更改需等待最多10分钟生效。URL在账户和域名层面会去重。
- IP预热——新的独立IP需要逐步提升发送量。可通过以编程方式管理。
/v3/ip_warmups - 两条MX记录——入站路由需同时配置和
mxa。mxb - API密钥安全——切勿在客户端暴露主密钥。请使用域名发送密钥实现受限访问。
Links
链接
- API Reference (full OAS): Mailgun API
- Authentication: Auth docs
- API Overview: Base URLs, regions, rate limits
- User Manual: Sending, receiving, tracking guides
- SDKs: Node.js, Python, Go, Java, PHP, Ruby
- Dashboard: https://app.mailgun.com
- Mailgun LLMs.txt: https://documentation.mailgun.com/llms.txt
- API参考(完整OAS):Mailgun API
- 认证:认证文档
- API概述:基础URL、区域、速率限制
- 用户手册:发送、接收、跟踪指南
- SDK:Node.js、Python、Go、Java、PHP、Ruby
- 控制台:https://app.mailgun.com
- Mailgun LLMs.txt:https://documentation.mailgun.com/llms.txt
References
参考文档
- references/infrastructure.md — IPs, IP Pools, Dynamic Pools, IP Warmup, DKIM Keys, Subaccounts
- references/infrastructure.md — IP、IP池、动态池、IP预热、DKIM密钥、子账户