API 文档
所有接口均为 HTTP + JSON,地址前缀 /api/v1,字段使用 snake_case。请求头必须携带 X-API-Key(在管理后台「API Key」中创建)。成功时响应体为 {"code":0,"msg":"ok","data":...};失败时 HTTP 状态非 2xx,响应体为 {"code":<HTTP 状态>,"msg":"错误说明"}。
发送接口是异步的:返回 202 只表示已进入队列,最终结果请通过「查询发送状态」接口或 Webhook 回调获取。失败的邮件会按系统设置的间隔自动重试,并在多个 SMTP 通道间自动切换。
发送邮件
/api/v1/mail/send提交一封邮件进入发送队列,立即返回邮件 ID(HTTP 202)。可以直接给出 subject / html,也可以引用后台维护的模板(template + locale + vars),二者二选一。收件人全部命中抑制列表时 status 为 suppressed。
| 参数 | 位置 | 必填 | 说明 |
|---|---|---|---|
| X-API-Key | 请求头 | 是 | API Key,形如 mk_xxx |
| Idempotency-Key | 请求头 | 否 | 幂等键,24 小时内同一 Key 重复提交返回同一封邮件,见下文「幂等」 |
| to | 请求体 | 是 | 收件人数组,支持 "张三 <[email protected]>" 格式 |
| cc / bcc | 请求体 | 否 | 抄送 / 密送数组;to + cc + bcc 总数受系统上限约束 |
| subject / html / text | 请求体 | 否 | 直接编写时必填 subject 与 html;text 可选,缺省时由 html 自动生成 |
| template / locale / vars | 请求体 | 否 | 使用模板:template 为模板标识,locale 缺省时用模板默认语言,vars 为模板变量 |
| from_name | 请求体 | 否 | 发件人显示名,缺省用通道配置 |
| reply_to | 请求体 | 否 | 回复地址 |
| group | 请求体 | 否 | 通道分组,缺省用 Key 的默认分组 |
| priority | 请求体 | 否 | high 或 normal(默认)。验证码等时效性邮件建议用 high |
| send_at | 请求体 | 否 | 定时发送时间,RFC3339 格式,如 2026-10-30T09:00:00+08:00 |
| expire_in | 请求体 | 否 | 过期秒数:入队后超过该时长仍未发出则放弃(验证码类邮件推荐设置) |
| tags | 请求体 | 否 | 标签数组,便于检索与统计,回调中原样带回 |
| attachments | 请求体 | 否 | 附件数组:filename、content(base64)、content_type;content_id 非空时作为内嵌图片,HTML 中用 <img src="cid:xxx"> 引用 |
curl -X POST "https://mailer.example.com/api/v1/mail/send" \
-H "X-API-Key: mk_xxxxxxxxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"to": ["张三 <[email protected]>"],
"template": "verify-code",
"locale": "zh-CN",
"vars": { "code": "123456" },
"priority": "high",
"expire_in": 600,
"tags": ["signup"]
}'HTTP/1.1 202 Accepted
{ "code": 0, "msg": "ok", "data": { "id": 123, "status": "queued" } }批量发送
/api/v1/mail/batch一次提交多封邮件,每封可以有不同的收件人、变量与语言,适合通知类群发。可以引用模板,也可以直接给出 subject / html / text(按模板语法用每封的 vars 渲染)。单封失败不影响其他邮件,返回中按 index 对应。
| 参数 | 位置 | 必填 | 说明 |
|---|---|---|---|
| template / subject / html / text | 请求体 | 否 | 公共内容,与 send 相同,二选一 |
| locale / from_name / group / priority / tags | 请求体 | 否 | 公共参数,含义同 send |
| messages | 请求体 | 是 | 邮件数组,每项包含 to(字符串或数组)、vars,可选 locale 覆盖公共语言;单次数量受系统上限约束 |
curl -X POST "https://mailer.example.com/api/v1/mail/batch" \
-H "X-API-Key: mk_xxxxxxxxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"template": "notice",
"locale": "zh-CN",
"priority": "normal",
"messages": [
{ "to": "[email protected]", "vars": { "name": "A" }, "locale": "en" },
{ "to": ["[email protected]"], "vars": { "name": "B" } }
]
}'{
"code": 0,
"msg": "ok",
"data": {
"batch_id": "b_9f2c1e",
"items": [
{ "index": 0, "id": 1, "status": "queued" },
{ "index": 1, "error": "invalid recipient" }
]
}
}查询发送状态
/api/v1/mail/{id}查询单封邮件的状态与事件时间线。只能查询本 Key 提交的邮件。status 取值:queued(排队中)、sending(发送中)、sent(已发送)、failed(失败)、suppressed(已抑制)、canceled(已取消)。
| 参数 | 位置 | 必填 | 说明 |
|---|---|---|---|
| id | 路径 | 是 | 发送接口返回的邮件 ID |
curl "https://mailer.example.com/api/v1/mail/123" -H "X-API-Key: mk_xxxxxxxxxxxxxxxx"{
"code": 0,
"msg": "ok",
"data": {
"id": 123,
"status": "sent",
"to": ["[email protected]"],
"subject": "您的验证码",
"attempts": 1,
"created_at": "2026-10-29T10:00:00+08:00",
"send_at": null,
"sent_at": "2026-10-29T10:00:02+08:00",
"last_error": "",
"events": [
{ "type": "queued", "detail": "", "created_at": "2026-10-29T10:00:00+08:00" },
{ "type": "attempt", "detail": "channel: qq-1", "created_at": "2026-10-29T10:00:01+08:00" },
{ "type": "sent", "detail": "250 OK", "created_at": "2026-10-29T10:00:02+08:00" }
]
}
}幂等
网络超时等情况下调用方可能重复提交。发送接口支持请求头 Idempotency-Key(建议使用业务单号):24 小时内同一 API Key 使用相同的幂等键重复提交,直接返回第一次创建的邮件,不会重复发送。若相同幂等键对应的请求内容不同,返回 HTTP 409。
Idempotency-Key: order-20261029-0001错误码
| HTTP 状态 | 含义 |
|---|---|
| 400 | 参数错误(缺少收件人、模板不存在、变量渲染失败等) |
| 401 | API Key 无效或未携带 |
| 403 | Key 已禁用、已过期,或来源 IP 不在白名单内 |
| 404 | 邮件不存在(或不属于当前 Key) |
| 409 | 幂等键冲突:同一 Idempotency-Key 对应的请求内容不一致 |
| 413 | 附件超过大小上限 |
| 429 | 触发 QPS 限流,或今日配额已用尽(配额按收件人数计) |
| 500 | 服务内部错误,请稍后重试 |
HTTP/1.1 429 Too Many Requests
{ "code": 429, "msg": "daily quota exceeded" }Webhook 回调
在后台为 API Key 配置回调地址后,邮件进入终态(sent 已发送、failed 最终失败、suppressed 已抑制)时,系统会向该地址发送 POST 请求。业务方返回 2xx 视为成功,否则按 30 秒 / 2 分钟 / 10 分钟 / 1 小时 / 6 小时的间隔重试。回调可能重复送达,请以 message_id + event 做去重。
POST /your/callback HTTP/1.1
Content-Type: application/json
X-Mailer-Event: sent
X-Mailer-Timestamp: 1730000000
X-Mailer-Signature: sha256=5d41402abc4b2a76b9719d911017c592...
{
"event": "sent",
"message_id": 123,
"status": "sent",
"to": ["[email protected]"],
"tags": ["signup"],
"error": "",
"timestamp": 1730000000
}回调验签
每个 Key 有独立的回调签名密钥(创建 Key 或在后台重新生成时显示一次)。签名算法:hex(HMAC_SHA256(secret, timestamp + "." + body)),其中 timestamp 为请求头 X-Mailer-Timestamp,body 为原始请求体字节。将结果加上 sha256= 前缀后与请求头 X-Mailer-Signature 做常量时间比较,并建议拒绝时间戳偏差超过 5 分钟的请求。
import crypto from "node:crypto";
import express from "express";
const SECRET = process.env.MAILER_WEBHOOK_SECRET;
const app = express();
// 必须使用原始请求体计算签名
app.post("/mailer/callback", express.raw({ type: "application/json" }), (req, res) => {
const ts = req.get("X-Mailer-Timestamp") || "";
const sig = req.get("X-Mailer-Signature") || "";
// 拒绝 5 分钟以外的请求,防止重放
if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return res.sendStatus(401);
const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(ts + "." + req.body).digest("hex");
const ok = sig.length === expected.length && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
if (!ok) return res.sendStatus(401);
const event = JSON.parse(req.body.toString("utf8"));
console.log(event.event, event.message_id, event.status);
res.sendStatus(200);
});
app.listen(3000);package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"math"
"net/http"
"os"
"strconv"
"time"
)
var secret = []byte(os.Getenv("MAILER_WEBHOOK_SECRET"))
func callback(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
ts := r.Header.Get("X-Mailer-Timestamp")
sig := r.Header.Get("X-Mailer-Signature")
// 拒绝 5 分钟以外的请求,防止重放
sec, err := strconv.ParseInt(ts, 10, 64)
if err != nil || math.Abs(float64(time.Now().Unix()-sec)) > 300 {
http.Error(w, "expired", http.StatusUnauthorized)
return
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(ts + "."))
mac.Write(body)
expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(sig), []byte(expected)) {
http.Error(w, "bad signature", http.StatusUnauthorized)
return
}
// TODO: 解析 body 并处理事件
w.WriteHeader(http.StatusOK)
}
func main() {
http.HandleFunc("/mailer/callback", callback)
http.ListenAndServe(":3000", nil)
}import hashlib
import hmac
import os
import time
from flask import Flask, abort, request
SECRET = os.environ["MAILER_WEBHOOK_SECRET"].encode()
app = Flask(__name__)
@app.post("/mailer/callback")
def callback():
body = request.get_data() # 原始请求体
ts = request.headers.get("X-Mailer-Timestamp", "")
sig = request.headers.get("X-Mailer-Signature", "")
# 拒绝 5 分钟以外的请求,防止重放
if not ts.isdigit() or abs(time.time() - int(ts)) > 300:
abort(401)
expected = "sha256=" + hmac.new(SECRET, ts.encode() + b"." + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(sig, expected):
abort(401)
event = request.get_json()
print(event["event"], event["message_id"], event["status"])
return "", 200