MoeMail
返回部落格

用 Python 接收 email

在 Python 裡讀信的經典做法,是對著真實郵箱用 IMAP(imaplib)。對自動化與測試來說這太笨重;一個透過 HTTP 的拋棄式收件匣 API 簡單得多。本文是開發者 email 測試的一部分;另見 Node.js 版本。

建立並輪詢(requests)

import os, time, requests

API = "https://moemail.app/api"
H = {"X-API-Key": os.environ["MAIL_KEY"]}

def create_inbox():
    return requests.post(API + "/emails/generate", headers=H).json()

def wait_for_email(inbox_id, timeout=30):
    end = time.time() + timeout
    while time.time() < end:
        msgs = requests.get(API + "/emails/" + inbox_id + "/messages", headers=H).json()["messages"]
        if msgs:
            return msgs[0]
        time.sleep(1.5)
    raise TimeoutError("no email arrived")

在 pytest 或腳本裡這樣用:建立一個收件匣、觸發 email,再呼叫 wait_for_email 並讀 msg["text"]

或者接 webhook(Flask)

from flask import Flask, request

app = Flask(__name__)

@app.post("/inbound")
def inbound():
    mail = request.get_json()  # verify the signature first in production
    print("got mail for", mail["to"], "-", mail["subject"])
    return "", 200  # respond fast; non-2xx triggers retries

這跟 Selenium email 測試天生搭配,在 CI 裡跑起來也一樣。

開始動手

讀讀 OpenAPI 文件,再建立一個郵箱就能開始接收。