Python으로 이메일 받기
Python에서 메일을 읽는 고전적인 방법은 실제 메일박스에 IMAP(imaplib)으로 접근하는 것입니다. 자동화와 테스트에는 무거운 방식이죠. HTTP로 통신하는 일회용 받은편지함 API가 훨씬 간단합니다. 개발자를 위한 이메일 테스트의 일부이며, 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나 스크립트에서 이렇게 쓰세요. 받은편지함을 만들고, 이메일을 발동시킨 다음, 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 이메일 테스트와 자연스럽게 어울리고, CI에서도 동일하게 동작합니다.
시작하기
OpenAPI 문서를 읽고 메일박스를 만들어 수신을 시작하세요.