跳转到正文
登录

邮件 API 开发者指南

API Key 使用 HMAC-SHA256,签名绑定方法、路径、查询和正文;重试复用 request_id,每次使用新 nonce。

配置 API Key

请在服务端保存 Key,不要放进浏览器代码。

export DOTMAIL_API_KEY='YOUR_PERSONAL_API_KEY'
export DOTMAIL_SITE='example.test'
# Optional: local development
# export DOTMAIL_BASE_URL='http://localhost:8000'

在运行示例的终端设置这些环境变量。DOTMAIL_BASE_URL 默认是 https://dotmail.cc,DOTMAIL_SITE 请改成业务使用的站点。

对接示例

每个示例分配一个邮箱,每 5 秒查信一次、最多 60 秒,读取第一封新邮件详情,并在结束时解除邮箱。

Python 3 · 仅标准库,无需安装依赖。

python3 dotmail.py

dotmail.py

# Python 3 · run on your server, keep the key private.
import hashlib
import hmac
import json
import os
import secrets
import time
import urllib.request
from urllib.parse import quote, urlencode

BASE = os.getenv("DOTMAIL_BASE_URL", "https://dotmail.cc").rstrip("/")
KEY = os.environ["DOTMAIL_API_KEY"]


def call(method, path, payload=None, query=""):
    body = json.dumps(payload, separators=(",", ":")).encode() if payload is not None else b""
    stamp, nonce = str(int(time.time())), secrets.token_hex(16)
    canonical = "\n".join([method, path, query, stamp, nonce, hashlib.sha256(body).hexdigest()])
    signature = hmac.new(KEY.encode(), canonical.encode(), hashlib.sha256).hexdigest()
    req = urllib.request.Request(BASE + path + ("?" + query if query else ""),
        data=body if payload is not None else None, method=method, headers={
        "X-Api-Key": KEY, "X-Timestamp": stamp, "X-Nonce": nonce,
        "X-Signature": signature, "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=30) as response:
        result = json.load(response)
        if result.get("code") != 200:
            raise RuntimeError(str(result))
        return result["data"]


def main():
    # Reuse this ID if allocation needs retrying; do not create a new charge.
    request_id = os.getenv("DOTMAIL_REQUEST_ID") or secrets.token_hex(16)
    print("request_id:", request_id)
    inbox = call("POST", "/api/v1/external/emails/allocate", {
        "site": os.getenv("DOTMAIL_SITE", "example.test"), "request_id": request_id})
    path = "/api/v1/external/emails/" + quote(inbox["email"], safe="") + "/messages"
    query = urlencode({"allocation_id": inbox["allocation_id"]})
    try:
        print(inbox["email"], inbox["allocation_id"])
        for _ in range(12):
            messages = call("GET", path, query=query)
            if messages["items"]:
                message_id = messages["items"][0]["id"]
                detail = call("GET", path + "/" + str(message_id), query=query)
                print(json.dumps(detail, ensure_ascii=False))
                break
            time.sleep(5)
        else:
            print("No new mail within 60 seconds.")
    finally:
        # Early release is free; it does not refund the allocation charge.
        try:
            call("POST", "/api/v1/external/emails/release", {
                "email": inbox["email"], "allocation_id": inbox["allocation_id"]})
        except Exception as error:
            print("Release failed; retry with the same allocation_id:", error)


if __name__ == "__main__":
    main()

HMAC-SHA256 签名

下面六个字段用换行连接,再用 API Key 签名。路径、查询串、UTF-8 正文字节必须与实际请求一致;没有查询时该字段为空,GET 正文为空。签名输出小写十六进制,通过 X-Signature 发送,同时携带 X-Api-Key、X-Timestamp、X-Nonce。

METHOD
RAW_PATH
RAW_QUERY
UNIX_SECONDS
NONCE
SHA256_HEX(BODY_BYTES)

成功分配按当前 API 价格扣点,独占 10 分钟;查信和解除免费,主动提前解除不退点。保存打印出的 request_id:分配超时后,重试前将 DOTMAIL_REQUEST_ID 设为原值,保持站点和参数一致;新 ID 会创建新分配。查信和解除必须保留 allocation_id。空 items 可能只是同步仍在排队;示例读取一封邮件,分页可使用 next_cursor。

下一个邮箱,从这里开始。

为自己申请私有邮箱,或为应用接入 API。