sinch-mailgun

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Mailgun Email API

Mailgun 电子邮件API

Agent Instructions

Agent操作说明

  1. 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.
  2. Before generating code, check for existing
    .env
    files or environment variables for
    MAILGUN_API_KEY
    and
    MAILGUN_DOMAIN
    .
  3. When the user mentions events, logs, stats, or tags — use the current APIs (
    /v1/analytics/*
    ), never the deprecated v3 endpoints.
  4. For domain CRUD operations, use
    /v4/domains
    (not v3).
  5. For detailed API parameters, fetch the linked
    .md
    doc pages rather than guessing.
  1. 如果尚未知晓用户所在区域,务必询问用户(美国或欧盟)。区域决定了基础URL,且域名创建后无法更改。
  2. 在生成代码前,检查是否存在
    .env
    文件或
    MAILGUN_API_KEY
    MAILGUN_DOMAIN
    环境变量。
  3. 当用户提及事件、日志、统计数据或标签时,请使用当前的API(
    /v1/analytics/*
    ),切勿使用已弃用的v3端点。
  4. 对于域名的CRUD操作,请使用
    /v4/domains
    (而非v3版本)。
  5. 如需详细的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:
api
, password: your Mailgun private API key. Find it at Mailgun Dashboard > Account Settings > API Keys.
Two key types:
  • Primary Account API Key — full access to all endpoints and domains
  • Domain Sending Keys — restricted to
    POST /messages
    and
    /messages.mime
    for one domain
完整的认证设置请查看Sinch认证
所有请求均使用HTTP基础认证——用户名:
api
,密码:你的Mailgun私有API密钥。可在Mailgun控制台 > 账户设置 > API密钥中找到该密钥。
密钥分为两种类型:
  • 主账户API密钥——拥有所有端点和域名的完全访问权限
  • 域名发送密钥——仅对单个域名的
    POST /messages
    /messages.mime
    端点具有访问权限

Base URLs

基础URL

Always match the base URL to the domain's region. Data never crosses regions.
ServiceUSEU
REST API
api.mailgun.net
api.eu.mailgun.net
Outgoing SMTP
smtp.mailgun.org
smtp.eu.mailgun.org
Inbound SMTP
mxa.mailgun.org
,
mxb.mailgun.org
mxa.eu.mailgun.org
,
mxb.eu.mailgun.org
Open/Click Tracking
mailgun.org
eu.mailgun.org
请确保基础URL与域名所在区域匹配,数据不会跨区域传输。
服务美国欧盟
REST API
api.mailgun.net
api.eu.mailgun.net
出站SMTP
smtp.mailgun.org
smtp.eu.mailgun.org
入站SMTP
mxa.mailgun.org
,
mxb.mailgun.org
mxa.eu.mailgun.org
,
mxb.eu.mailgun.org
打开/点击跟踪
mailgun.org
eu.mailgun.org

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
multipart/form-data
— use
-F
flags, not
-d
with JSON.
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>'
响应:
{"id": "<message-id@YOUR_DOMAIN>", "message": "Queued. Thank you."}
Messages API使用
multipart/form-data
格式——请使用
-F
参数,而非
-d
参数传递JSON。

Node.js SDK

Node.js SDK

bash
npm install mailgun.js form-data
javascript
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-data
javascript
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.,
    sandboxXXX.mailgun.org
    ). Only pre-authorized recipients can receive mail.
  • Custom domain — requires DNS verification (SPF, DKIM, MX). Domain CRUD uses
    /v4/domains
    (not v3). Only
    DELETE
    remains on v3. See Domains API
  • 沙箱域名——注册时提供(例如:
    sandboxXXX.mailgun.org
    )。仅预授权收件人可接收邮件。
  • 自定义域名——需要DNS验证(SPF、DKIM、MX记录)。域名的CRUD操作请使用
    /v4/domains
    (而非v3版本)。仅
    DELETE
    操作仍保留在v3版本中。详情请查看域名API

Sending

邮件发送

  • REST API
    POST /v3/{domain}/messages
    with
    from
    ,
    to
    ,
    cc
    ,
    bcc
    ,
    subject
    ,
    text
    ,
    html
    ,
    amp-html
    , attachments, headers, tags, variables
  • SMTP
    smtp.mailgun.org
    port 587 TLS, credentials per-domain via
    /v3/domains/{domain}/credentials
    . See Credentials API
  • MIME
    POST /v3/{domain}/messages.mime
  • Batch — up to 1,000 recipients per call using
    recipient-variables
    for personalization
  • Test mode — add
    o:testmode=yes
    to simulate without delivery
  • Scheduling
    o:deliverytime
    (RFC-2822),
    o:deliverytime-optimize-period
    (STO),
    o:time-zone-localize
    (TZO)
  • Tracking
    o:tracking
    ,
    o:tracking-clicks
    ,
    o:tracking-opens
    per message; or configure at domain level via
    /v3/domains/{name}/tracking
    . See Domain Tracking API
Send options (
o:
,
h:
,
v:
,
t:
params) are limited to 16KB total per request.
For full parameters: Messages API
  • REST API——调用
    POST /v3/{domain}/messages
    ,参数包含
    from
    to
    cc
    bcc
    subject
    text
    html
    amp-html
    、附件、请求头、标签、变量
  • SMTP——使用
    smtp.mailgun.org
    的587端口(TLS加密),每个域名的凭据可通过
    /v3/domains/{domain}/credentials
    获取。详情请查看凭据API
  • MIME格式——调用
    POST /v3/{domain}/messages.mime
  • 批量发送——每次调用最多支持1000个收件人,使用
    recipient-variables
    实现个性化
  • 测试模式——添加
    o:testmode=yes
    参数即可模拟发送,不会实际投递邮件
  • 定时发送——使用
    o:deliverytime
    (RFC-2822格式)、
    o:deliverytime-optimize-period
    (STO)、
    o:time-zone-localize
    (TZO)参数
  • 跟踪功能——可针对单条邮件设置
    o:tracking
    o:tracking-clicks
    o:tracking-opens
    参数;也可通过
    /v3/domains/{name}/tracking
    在域名层面配置。详情请查看域名跟踪API
发送选项(
o:
h:
v:
t:
参数)总大小限制为16KB。
完整参数请查看:Messages API

Templates

模板

Two levels:
Reference by name when sending:
-F template='welcome-template' -F t:variables='{"name":"John"}'
. Each template supports up to 40 versions.
分为两个层级:
  • 域名级别——
    /v3/{domain}/templates
    。详情请查看域名模板API
  • 账户级别——
    /v4/templates
    (所有域名共享)。详情请查看账户模板API
发送邮件时通过名称引用模板:
-F template='welcome-template' -F t:variables='{"name":"John"}'
。每个模板最多支持40个版本。

Webhooks

Webhook

Real-time HTTP POST notifications for email events.
Event types:
clicked
,
complained
,
delivered
,
failed
,
opened
,
permanent_fail
,
temporary_fail
,
unsubscribed
针对邮件事件的实时HTTP POST通知。
  • 域名级别——
    /v3/domains/{domain}/webhooks
    (v3)或
    /v4/domains/{domain}/webhooks
    (v4)。详情请查看域名Webhook API
  • 账户级别——
    /v1/webhooks
    (针对所有域名触发)。详情请查看账户Webhook API
事件类型:
clicked
complained
delivered
failed
opened
permanent_fail
temporary_fail
unsubscribed

Events and Analytics

事件与分析

  • Logs
    POST /v1/analytics/logs
    for querying event data. The legacy
    GET /v3/{domain}/events
    is deprecated. See Logs API
  • Metrics
    POST /v1/analytics/metrics
    for aggregated analytics with dimensions, filters, resolutions. Replaces deprecated
    /v3/stats
    . See Metrics API
  • Tags
    o:tag
    when sending; manage via
    /v1/analytics/tags
    . Legacy
    /v3/{domain}/tags
    is deprecated. See Tags API
Data retention: Logs — at least 3 days (legacy). Metrics — hourly 60 days, daily 1 year, monthly indefinite.
  • 日志——调用
    POST /v1/analytics/logs
    查询事件数据。旧版
    GET /v3/{domain}/events
    已弃用。详情请查看日志API
  • 指标——调用
    POST /v1/analytics/metrics
    获取聚合分析数据,支持维度、筛选、时间粒度。替代已弃用的
    /v3/stats
    。详情请查看指标API
  • 标签——发送时使用
    o:tag
    参数;通过
    /v1/analytics/tags
    管理。旧版
    /v3/{domain}/tags
    已弃用。详情请查看标签API
数据保留期限:日志——至少3天(旧版)。指标——小时级数据保留60天,天级数据保留1年,月级数据永久保留。

Inbound Routing

入站路由

Routes API — match incoming messages by recipient pattern or header expression, then forward, store, or webhook. Configure both
mxa
and
mxb
MX records.
路由API——通过收件人模式或请求头表达式匹配入站邮件,然后执行转发、存储或触发Webhook操作。需同时配置
mxa
mxb
两条MX记录。

Suppressions 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
    /v3/{domain}/whitelists
    — prevents addresses from being added to bounce lists
Mailgun会自动填充每个域名的抑制列表。向抑制列表中的地址发送邮件会被静默丢弃。

Mailing Lists

邮件列表

Mailing Lists API
/v3/lists
to create/manage lists,
/v3/lists/{address}/members
for members. Bulk upload via
.json
or
.csv
endpoints.
邮件列表API——通过
/v3/lists
创建/管理列表,通过
/v3/lists/{address}/members
管理列表成员。支持通过
.json
.csv
端点批量上传。

Stored Messages

存储的邮件

Retrieve:
GET /v3/domains/{domain}/messages/{storage_key}
. Resend:
POST
to same path. See Messages API
检索:
GET /v3/domains/{domain}/messages/{storage_key}
。重发:向同一路径发送
POST
请求。详情请查看Messages API

Infrastructure 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
recipient-variables
as JSON mapping each recipient address to their variables. Use
%recipient.variable_name%
in subject/body. Max 1,000 recipients per call. See Batch Sending
添加
recipient-variables
参数,以JSON格式映射每个收件人地址对应的变量。在主题/正文中使用
%recipient.variable_name%
引用变量。每次调用最多支持1000个收件人。详情请查看批量发送

Set up domain webhooks

设置域名Webhook

  1. Create webhook via
    POST /v3/domains/{domain}/webhooks
    with
    id
    (event type) and
    url
    fields
  2. Verify HMAC signature on incoming webhooks using your webhook signing key (SHA256). See Securing Webhooks
  3. Return 2xx or Mailgun retries with exponential backoff for ~8 hours
  1. 通过
    POST /v3/domains/{domain}/webhooks
    创建Webhook,参数包含
    id
    (事件类型)和
    url
    字段
  2. 使用你的Webhook签名密钥(SHA256)验证入站Webhook的HMAC签名。详情请查看Webhook安全
  3. 返回2xx状态码,否则Mailgun会以指数退避策略重试约8小时

Schedule and cancel delivery

定时发送与取消投递

  • Schedule: add
    -F o:deliverytime='RFC-2822-date'
    to send call
  • Cancel:
    DELETE /v3/{domain}/envelopes
    to bulk-delete all scheduled/undelivered mail
  • 定时发送:在发送请求中添加
    -F o:deliverytime='RFC-2822格式日期'
    参数
  • 取消投递:调用
    DELETE /v3/{domain}/envelopes
    批量删除所有已定时/未投递的邮件

Configure inbound email

配置入站邮件

  1. Add MX records pointing to
    mxa.mailgun.org
    and
    mxb.mailgun.org
    (priority 10)
  2. Create route via
    POST /v3/routes
    with
    expression
    (match pattern) and
    action
    (forward/store/webhook). See Routes Guide
  1. 添加MX记录,指向
    mxa.mailgun.org
    mxb.mailgun.org
    (优先级10)
  2. 通过
    POST /v3/routes
    创建路由,参数包含
    expression
    (匹配模式)和
    action
    (转发/存储/Webhook)。详情请查看路由指南

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.
  • multipart/form-data
    only
    — the Messages endpoint does not accept JSON. Use
    -F
    in curl.
  • Date format — RFC-2822 with numerical timezone offsets (+0500), not abbreviated names (EST, CET).
  • Domains API is v4 — use
    /v4/domains
    for CRUD. Only
    DELETE /v3/domains/{name}
    remains on v3.
  • Events/Stats deprecated — use
    POST /v1/analytics/logs
    (not
    GET /v3/{domain}/events
    ) and
    POST /v1/analytics/metrics
    (not
    /v3/stats
    ).
  • Tags deprecated — use
    /v1/analytics/tags
    (not
    /v3/{domain}/tags
    ).
  • Suppression auto-populate — Mailgun silently drops messages to bounced/unsubscribed/complained addresses.
  • Rate limits
    429
    response. Check
    X-RateLimit-Limit
    ,
    X-RateLimit-Remaining
    ,
    X-RateLimit-Reset
    headers. Use exponential backoff.
  • Send options 16KB cap
    o:
    ,
    h:
    ,
    v:
    ,
    t:
    params combined max 16KB per request.
  • 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
    /v3/ip_warmups
    to manage programmatically.
  • Two MX records — configure both
    mxa
    and
    mxb
    for inbound routing.
  • 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
    。仅
    DELETE /v3/domains/{name}
    仍保留在v3版本。
  • 事件/统计接口已弃用——请使用
    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:
    t:
    参数总大小不超过16KB。
  • Webhook缓存——更改需等待最多10分钟生效。URL在账户和域名层面会去重。
  • IP预热——新的独立IP需要逐步提升发送量。可通过
    /v3/ip_warmups
    以编程方式管理。
  • 两条MX记录——入站路由需同时配置
    mxa
    mxb
  • API密钥安全——切勿在客户端暴露主密钥。请使用域名发送密钥实现受限访问。

Links

链接

References

参考文档

  • references/infrastructure.md — IPs, IP Pools, Dynamic Pools, IP Warmup, DKIM Keys, Subaccounts
  • references/infrastructure.md — IP、IP池、动态池、IP预热、DKIM密钥、子账户