MoeMail
Back to Blog

Receive Email with Python

The classic way to read mail in Python is IMAP (imaplib) against a real mailbox. For automation and tests that's heavy; a disposable inbox API over HTTP is far simpler. Part of email testing for developers; see also the Node.js version.

Create & poll (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")

Use it in pytest or a script: create an inbox, trigger the email, then wait_for_email and read msg["text"].

Or accept a 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

This pairs naturally with Selenium email testing and runs the same in CI.

Get started

Read the OpenAPI docs and create a mailbox to start receiving.