跳转到正文
登入

郵件 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。