How to Receive Email in Python: Read the Inbox, Save Attachments and Get New Mail Pushed

Receive email in Python without IMAP: create an address, open messages, save attachments to disk, wait for new mail, and get webhooks in FastAPI.

By · · 18 min read

Python code from this guide, in inbox.py, sending or reading email with Mailcycle

You want to receive email in Python: read a supplier’s invoice and save the PDF, pick a sign-in code out of a verification email in a test, or hand a customer’s reply to your app or your agent. The classic route is imaplib: log in to a mailbox, search it, fetch raw MIME and pick it apart with the email package. That works when you already have a mailbox and the credentials for it. If what you want is “give my code an address and let it read what arrives”, an email API is shorter.

This tutorial shows how to receive and read email in Python with Mailcycle’s Python SDK, the mailcycle package. You’ll create an address that receives mail, list and open messages, save attachments to disk, block until the next email arrives, and organise the inbox. Then you’ll get new mail pushed to a FastAPI app by webhook, or to a worker over a WebSocket, and finish with a straight comparison against imaplib and poplib.

It is the receiving half of How to send email from Python. That post covers sending, HTML, attachments you send, Django’s send_mail and threaded replies. This one goes deep on the inbox. Every snippet below was type-checked with mypy and run against the SDK’s own fake API.

Quick answer: how to receive email in Python

To receive email in Python, install the mailcycle package, sign in with your recovery phrase, create an address, and call mc.messages.wait_for(). It blocks until a message arrives and returns it parsed and decrypted, with the sender, subject, text, HTML and attachments as plain Python fields. There is no IMAP server, port or mailbox password to set up.

pip install mailcycle
import os

from mailcycle import Mailcycle

mc = Mailcycle.sign_in(os.environ["MAILCYCLE_PHRASE"])

address = mc.addresses.create(prefix="inbound", label="Python inbox")
print("Send an email to", address.email_address)

message = mc.messages.wait_for(address_id=address.id, timeout=300)
print(message.from_address, message.subject)
print(message.text)

Run it, send an email to the address it prints from any mail app, and the script prints what you sent. The rest of this guide is what a real app needs around that: paging, attachments, folders, push and errors.

Flow: a sender writes to your address, Mailcycle encrypts the mail on arrival, the Python SDK lists, waits for or receives it by webhook, and your Python code reads the message
Mail sent to a Mailcycle address is encrypted on arrival, then your Python code reads it with the Python SDK, by waiting for it or from a webhook.

Prerequisites

  • Python 3.10 or later. Check with python3 --version.
  • A Mailcycle account. Receiving works on every plan, Free included, when your script signs in with the recovery phrase. API keys and the event stream for API keys start at Operator, and so do webhooks. Pricing has the plans, and the 7-day trial needs no card.
  • Your recovery phrase, in an environment variable, for any process that opens mail. The callout below explains why.
  • FastAPI, only for the webhook section: pip install 'fastapi[standard]'.

Step 1: Install the Python package

pip install mailcycle
# or, with the WebSocket event stream used later:
pip install 'mailcycle[events]'

Version 0.8.0 is current at the time of writing. It depends on httpx for HTTP and cryptography for the decryption it does locally. The events extra adds websockets, which wait_for and the worker example use to hear about new mail the moment it lands. The package ships type hints, so your editor completes message. and mypy or Pyright catches a misspelt field.

Step 2: Build a client that can open mail

Every reading call goes through one Mailcycle client. There are two ways to build one that can open messages:

Mailcycle.sign_in(phrase) Mailcycle.with_api_key(key, phrase=phrase)
Plans Every plan, Free included Operator and up
Credential A 30-day session, from a challenge-response in which nothing secret crosses the wire An mak_… key you can revoke in the app
Opens mail Yes Yes, once the phrase is passed too
Can add webhooks and API keys Yes No: those need a session

Put the choice in one small module, built once per process, and import it everywhere else. The rest of this tutorial imports client and ADDRESS_ID from it:

# inbox.py
import os
from functools import cache

from mailcycle import Mailcycle


@cache
def client() -> Mailcycle:
    """One client per process, able to open mail."""
    phrase = os.environ["MAILCYCLE_PHRASE"]
    api_key = os.environ.get("MAILCYCLE_API_KEY")
    if api_key:
        return Mailcycle.with_api_key(api_key, phrase=phrase)  # Operator and up
    return Mailcycle.sign_in(phrase)  # every plan, Free included


ADDRESS_ID = os.environ.get("MAILCYCLE_ADDRESS_ID", "ibx_k3v9x2mq7a")

When you pass both a key and a phrase, the client checks the phrase belongs to the key’s account before it opens anything, and raises MailcycleError if it doesn’t.

Reuse the session instead of signing in every run

Each sign_in opens a new 30-day session. A cron job that runs every five minutes shouldn’t make thousands of them, so keep the token and pick it up with Mailcycle.resume():

# session.py
import os
from pathlib import Path

from mailcycle import APIError, Mailcycle

TOKEN_FILE = Path.home() / ".config" / "mailcycle" / "session"


def signed_in() -> Mailcycle:
    phrase = os.environ["MAILCYCLE_PHRASE"]
    if TOKEN_FILE.exists():
        try:
            return Mailcycle.resume(TOKEN_FILE.read_text().strip(), phrase)
        except APIError as error:
            if error.status != 401:  # 401: the session expired or was ended
                raise
    mc = Mailcycle.sign_in(phrase)
    TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
    TOKEN_FILE.touch(mode=0o600)
    TOKEN_FILE.write_text(mc.session_token or "")
    return mc

resume still needs the phrase, because the token proves who you are but can’t open mail. Treat the token file like a password: it’s readable by your user only.

Step 3: Create an email address that receives mail

An address that receives mail needs a public key the mail server can seal to. mc.addresses.create() derives that key pair from your phrase, uploads only the public half, and keeps the private half on your machine. That is why creating a receiving address needs a client built with the phrase. An API key alone can’t do it.

from inbox import client

mc = client()

address = mc.addresses.create(prefix="invoices", label="Supplier invoices", retention_days=30)
print(address.email_address, address.id)

for existing in mc.addresses.list():
    state = "receives" if existing.receives else "has no key yet"
    print(existing.email_address, existing.label, state)

The options, from the email addresses guide:

  • prefix="invoices" gives invoices- plus a random ending on a shared domain.
  • style="person", "business", "team" or "neutral" rolls a name in that style, like maya.holt. To choose before creating, call mc.addresses.roll_names("person") and pass the one you like as local_part. Rolled names work on every plan.
  • local_part="invoices" asks for an exact name. Any name you type needs Scale or above, and so does domain= with your own domain.
  • label is sealed on your machine, so the server stores it as ciphertext.
  • retention_days is 1 to 90, 7 by default. Mail older than that is deleted, in every folder.

Save the ibx_… id: every reading call takes it. address.receives is False for an address created somewhere without a public key. It refuses mail until it has one, and opening Mailcycle on the account adds it.

Step 4: List and read emails in the inbox

mc.messages.list() returns one page of a folder, newest first. Iterate it directly:

from inbox import ADDRESS_ID, client

mc = client()

page = mc.messages.list(ADDRESS_ID, limit=20)
for message in page:
    flag = " " if message.read else "*"
    print(flag, message.received_at, message.from_address, message.subject)

if page.next_cursor:
    older = mc.messages.list(ADDRESS_ID, limit=20, cursor=page.next_cursor)
    print(len(older), "older messages on the next page")

limit is up to 200, and 50 by default. next_cursor is opaque: pass it back as cursor and don’t parse it. It is None on the last page.

To walk a whole folder, iterate() does the paging for you and yields one Message at a time:

from inbox import ADDRESS_ID, client

mc = client()

invoices = [
    message
    for message in mc.messages.iterate(ADDRESS_ID)
    if "invoice" in message.subject.lower() and message.attachments
]
print(len(invoices), "invoices with files attached")

That filter is also how you search. Content is sealed, so there’s no server-side search or ?q= parameter: you decrypt, then filter in Python. Pass folder="sent", "junk", "trash" or "starred" to list() or iterate() to read another folder.

What’s in a Message

Each Message is a frozen dataclass, already parsed from MIME and decrypted:

Field What it holds
id, address_id The message’s msg_… id and the address it arrived at.
received_at When it arrived, as an ISO 8601 string in UTC.
from_address, from_name The sender’s address and display name.
reply_to Where a reply should go: the Reply-To header if set, otherwise From.
to, subject The recipient and the subject line.
text The plain-text body.
html The HTML body exactly as sent. Don’t render this one.
safe_html The HTML with remote images, trackers and embeds removed.
blocked What safe_html had taken out, as BlockedTracker items.
attachments A tuple of Attachment: index, filename, mime_type, size, content_id, stored.
message_id The sender’s Message-ID header, used to thread a reply.
read, starred, folder The message’s state.
opened False if it couldn’t be decrypted: no phrase, or the wrong one.

A message that won’t open comes back with opened=False and empty content rather than raising, so one bad message never hides the rest of a page.

Read the email body in Python: text, HTML and safe_html

Most mail carries both a plain-text and an HTML part. Use text for anything you parse, such as codes, order numbers or a reply to hand to a model. If you show the HTML anywhere, in an admin page or an internal tool, use safe_html:

from pathlib import Path

from mailcycle import summarize_blocked

from inbox import client

mc = client()
message = mc.messages.get("msg_91be02c4a7d1")

if not message.opened:
    raise SystemExit("This message would not open: check the recovery phrase.")

print(message.text or "(no plain-text part)")

if message.safe_html:
    Path("preview.html").write_text(message.safe_html, encoding="utf-8")
    print(summarize_blocked(list(message.blocked)))  # e.g. "1 tracker blocked from track.example."

mc.messages.get() fetches one message by id, from any folder. safe_html is the HTML the Mailcycle apps show: remote images, tracking pixels, remote stylesheets and embeds are taken out, so opening it doesn’t tell the sender when, where or whether you read it. blocked lists each removed item with its url, host and kind (pixel, image or link), and summarize_blocked() turns that into one line for a log. safe_html removes remote content. It isn’t a general HTML sanitiser for your own pages, so if you embed it in a page of your own, put it in a sandboxed <iframe>.

Download email attachments in Python

Attachments are listed on the message and fetched one at a time. Their bodies are sealed like the message, and mc.messages.attachment() opens them on your machine. Here’s a small module that saves a message’s files to disk, safely:

# attachments.py
import re
from pathlib import Path

from mailcycle import Message

from inbox import client

DOWNLOADS = Path("downloads")


def safe_name(filename: str) -> str:
    """A file name that cannot climb out of the folder or upset the shell."""
    name = re.sub(r"[^\w.\- ]", "_", Path(filename).name).strip(" .")
    return name or "attachment"


def save_attachments(message: Message, folder: Path = DOWNLOADS, *, inline: bool = False) -> list[Path]:
    """Writes a message's files to folder/<message id>/ and returns their paths."""
    target = folder / message.id
    saved: list[Path] = []
    for attachment in message.attachments:
        if not attachment.stored:
            continue  # an empty part: there is nothing to fetch
        if attachment.content_id and not inline:
            continue  # an image the HTML shows inline, like a logo
        data = client().messages.attachment(message, attachment.index)  # opened on this machine
        target.mkdir(parents=True, exist_ok=True)
        path = target / f"{attachment.index}-{safe_name(attachment.filename)}"
        path.write_bytes(data)
        saved.append(path)
    return saved

Then process every unread message that has files, and mark each one read so the next run skips it:

from attachments import save_attachments
from inbox import ADDRESS_ID, client

mc = client()

for message in mc.messages.iterate(ADDRESS_ID):
    if message.read or not message.attachments:
        continue
    for path in save_attachments(message):
        print("saved", path)
    mc.messages.mark_read(message.id)

The details that matter with real mail:

  • The file name comes from the sender. A name like ../../.bashrc is a classic path-traversal trick. safe_name keeps only the last path component and a conservative set of characters, and the index prefix stops two files called invoice.pdf overwriting each other.
  • stored is False for a part that had no body. Fetching it returns a 404, so skip it.
  • content_id marks an inline image, the kind HTML shows with <img src="cid:logo">. Most pipelines want the PDF, not the sender’s logo, so they’re skipped unless you pass inline=True.
  • mime_type and size are there if you want to keep only application/pdf, or refuse anything over a size, before you download it.
  • Treat files as untrusted. Scan them, or open them in a sandbox, before anything else touches them.

That’s the job a Python email parser does for attachments, without the MIME tree: no walking multipart/mixed, decoding base64 or guessing a file name from Content-Disposition.

Wait for the next email in Python

mc.messages.wait_for() blocks until a matching message arrives and returns it opened. It’s the shortest way to read a verification email in an end-to-end test, or to wait for a reply in a script:

import re
from datetime import datetime, timezone

from mailcycle import APIError

from inbox import ADDRESS_ID, client

mc = client()
started = datetime.now(timezone.utc)  # take the time before the email is triggered

# ...trigger the email here: submit a sign-up form, call your own API...

try:
    message = mc.messages.wait_for(
        address_id=ADDRESS_ID,
        subject="verify",
        since=started,
        timeout=120,
    )
except APIError as error:
    if error.code == "timeout":
        raise SystemExit("No verification email within two minutes.") from error
    raise

match = re.search(r"\b(\d{6})\b", message.text)
if match is None:
    raise SystemExit(f"No code in: {message.text[:200]!r}")
print("code:", match.group(1))

How it behaves:

  • since is the important one. Mail received from that moment on counts, even if it landed before wait_for started listening. Take the time before you trigger the email, so a fast delivery can’t slip past. It defaults to now.
  • from_address and subject match text the sender or subject contains, ignoring case. address_id limits the wait to one address.
  • Push when it can, polling when it can’t. With mailcycle[events] installed it listens on the event stream. Without it, it polls the address every poll_seconds (five by default), asking only for mail newer than the newest it has seen.
  • timeout is in seconds, 60 by default. When it runs out you get APIError with code="timeout".

For a test suite, give each test its own address and delete it afterwards. Deleting an address removes its mail, and the address is never issued again:

# conftest.py
from collections.abc import Iterator

import pytest
from mailcycle import Address

from inbox import client


@pytest.fixture
def fresh_address() -> Iterator[Address]:
    """A new address for one test, deleted with its mail afterwards."""
    mc = client()
    address = mc.addresses.create(prefix="test", retention_days=1)
    yield address
    mc.addresses.delete(address.id)

Sign up with fresh_address.email_address in the app under test, then wait_for(address_id=fresh_address.id, ...). The same pattern in a browser test is in Test email verification with Playwright.

Mark as read, star, move and delete

The SDK can organise mail as well as read it. These calls change state only, so they don’t open any content:

Call What it does
mc.messages.mark_read(id) Marks read. mark_read(id, False) marks unread.
mc.messages.star(id) Stars it. star(id, False) unstars. A star is a flag, not a folder.
mc.messages.move(id, "junk") Moves to "inbox", "junk" or "trash". "restore" takes it back out of the trash.
mc.messages.delete(id) Deletes it now.
mc.messages.empty_trash() Deletes everything in the trash and returns how many.

A triage pass that saves invoices, stars them and files newsletters as junk:

from attachments import save_attachments
from inbox import ADDRESS_ID, client

mc = client()

for message in mc.messages.iterate(ADDRESS_ID):
    if message.read:
        continue
    if message.attachments:
        save_attachments(message)
        mc.messages.star(message.id)
    elif "newsletter" in message.subject.lower():
        mc.messages.move(message.id, "junk")
    mc.messages.mark_read(message.id)

Moving messages while you iterate is safe: the cursor marks a position in time, not an offset, so nothing gets skipped.

Only read what’s new

Reading is metered per message body or attachment you fetch, and listing a page fetches the bodies on it. A job that walks the whole inbox every five minutes spends reads on mail it has already handled. Since pages come newest first, keep a marker and stop when you reach it:

from pathlib import Path

from inbox import ADDRESS_ID, client

MARK = Path("last-seen.txt")
mc = client()

last_seen = MARK.read_text().strip() if MARK.exists() else ""
newest = last_seen

for message in mc.messages.iterate(ADDRESS_ID, limit=50):  # newest first
    if message.received_at <= last_seen:
        break  # everything from here on was handled by an earlier run
    print(message.received_at, message.from_address, message.subject)
    newest = max(newest, message.received_at)

MARK.write_text(newest)

The timestamps are ISO 8601 strings in UTC in one fixed format, so comparing them as strings sorts them by time. The hourly read allowances are in the rate limits reference. Better still, stop polling altogether and let new mail come to you.

Get new email pushed to Python: webhooks or the event stream

Mailcycle can tell your code the moment mail arrives, in two ways. Both send a message.received event with the message’s id and its address’s id, never the content. Your code fetches the message by id and opens it locally, so the phrase stays on your machine.

Webhooks Event stream
Transport Mailcycle POSTs to an HTTPS URL of yours Your code holds a WebSocket open
Needs A public URL pip install 'mailcycle[events]' and no public URL
Plans Operator and up Every plan with a session, Operator and up with an API key
If you’re offline Retried for about a day and a half Events while disconnected are not replayed
Fits Web apps, serverless functions Workers, scripts, desktop tools

Receive email in FastAPI with a webhook

Add a webhook in the app under API, on the Webhooks tab, or from Python with a signed-in session (an API key can’t add one):

import os

from mailcycle import Mailcycle

mc = Mailcycle.sign_in(os.environ["MAILCYCLE_PHRASE"])  # adding a webhook needs a session

created = mc.webhooks.create(
    "https://example.com/hooks/mailcycle",
    ["message.received"],
    "Inbound mail",
)
print(created.secret)  # whsec_..., shown once: store it as MAILCYCLE_WEBHOOK_SECRET
mc.webhooks.test(created.webhook.id)

The URL must be HTTPS on a hostname. For local development, expose your dev server through a tunnel. Then the receiving route:

# app.py
import json
import os
from typing import Annotated

from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request
from mailcycle import verify_webhook_signature

from attachments import save_attachments
from inbox import client

app = FastAPI()
SECRET = os.environ["MAILCYCLE_WEBHOOK_SECRET"]
seen: set[str] = set()  # one process only: use Redis or a table with a unique key in production


def process(message_id: str) -> None:
    mc = client()
    message = mc.messages.get(message_id)  # fetched by id, opened here
    if not message.opened:
        return
    saved = save_attachments(message)
    print(f"{message.from_address}: {message.subject} ({len(saved)} files)")
    mc.messages.mark_read(message.id)


@app.post("/hooks/mailcycle", status_code=204)
async def mailcycle_webhook(
    request: Request,
    background: BackgroundTasks,
    signature: Annotated[str | None, Header(alias="Mailcycle-Signature")] = None,
    event_id: Annotated[str | None, Header(alias="Mailcycle-Event-Id")] = None,
) -> None:
    raw = await request.body()  # the exact bytes, before any parsing
    if not verify_webhook_signature(SECRET, raw, signature):
        raise HTTPException(401)
    if event_id:
        if event_id in seen:
            return  # a retry of an event already handled
        seen.add(event_id)

    event = json.loads(raw)
    if event["type"] == "message.received":
        background.add_task(process, event["payload"]["messageId"])

Run it with fastapi dev app.py. What each part is for:

  • The signature is an HMAC-SHA256 of the timestamp and the raw body, keyed with your whsec_ secret. verify_webhook_signature checks it in constant time and refuses a timestamp more than five minutes old. Check the bytes as they arrived: a body that has been parsed and re-serialised won’t match.
  • Answer fast. Mailcycle waits 10 seconds for a 2xx. Fetching, decrypting and saving files happens in process, after the response. It’s a plain def, so FastAPI runs it in a thread and the blocking SDK calls don’t stall the event loop.
  • Deduplicate. An event can arrive more than once, and Mailcycle-Event-Id is the same on every attempt. The in-memory set suits one process. With several workers, insert the id into a table with a unique constraint, or SET NX it in Redis.
  • Other frameworks work the same way. In Flask, read request.get_data(). In Django, use request.body and request.headers["Mailcycle-Signature"].

You can test the route without a live webhook. webhook_signature_header() builds the header Mailcycle would send:

# test_webhook.py
import json
import time

from fastapi.testclient import TestClient
from mailcycle import webhook_signature_header

from app import SECRET, app

client = TestClient(app)
BODY = json.dumps({"id": "evt_test_1", "type": "webhook.test", "payload": {}})


def test_refuses_an_unsigned_delivery() -> None:
    assert client.post("/hooks/mailcycle", content=BODY).status_code == 401


def test_accepts_a_signed_delivery() -> None:
    headers = {
        "Mailcycle-Signature": webhook_signature_header(SECRET, BODY, int(time.time())),
        "Mailcycle-Event-Id": "evt_test_1",
    }
    assert client.post("/hooks/mailcycle", content=BODY, headers=headers).status_code == 204

Retries, the delivery log and every event type are in the webhooks guide, and Receive email with a webhook walks through the receiver in more depth.

A Python email listener over the event stream

A long-running worker doesn’t need a public URL. It can hold the event stream open and react the moment mail lands. The stream reconnects on its own after a network drop, but events that happen while it’s down aren’t replayed, so the worker catches up from the inbox at start-up and after every reconnect:

# worker.py
import threading

from mailcycle import Message

from attachments import save_attachments
from inbox import ADDRESS_ID, client

mc = client()
reconnected = threading.Event()


def handle(message: Message) -> None:
    saved = save_attachments(message)
    print(f"{message.from_address}: {message.subject} ({len(saved)} files)")
    mc.messages.mark_read(message.id)


def catch_up() -> None:
    """Unread mail that arrived while nothing was listening."""
    for message in mc.messages.list(ADDRESS_ID, limit=50):
        if not message.read:
            handle(message)


catch_up()
with mc.events.stream(on_reconnect=reconnected.set) as events:
    while not events.ended:
        event = events.next_event(timeout=30)
        if reconnected.is_set():  # the socket dropped and came back: events were missed
            reconnected.clear()
            catch_up()
        if event is None or event.type != "message.received":
            continue
        if event.payload.get("inboxId") != ADDRESS_ID:
            continue
        message = mc.messages.get(event.payload["messageId"])
        if not message.read:
            handle(message)
    print("stream ended:", events.closed_reason)

Notes on the design:

  • next_event(timeout=30) returns None when nothing arrives, so the loop wakes up regularly to check the reconnect flag. Iterating with for event in events also works, but blocks until the next event.
  • on_reconnect runs on the stream’s own thread, so it only sets a flag. The catch-up happens on the main thread.
  • The read flag doubles as “already handled”, so a message the catch-up processed isn’t handled again when its event arrives.
  • events.ended becomes true only when the server ends the stream for a reason reconnecting can’t fix, such as a revoked key (close code 4001) or a plan without the stream for API keys (4003). closed_reason says which. Run the worker under systemd, Docker or a process manager that restarts it.

The stream carries every event type on the account, which is why the loop filters on type and inboxId. Close codes and frames are in the event stream guide.

imaplib vs poplib vs an email API

Python’s standard library has two ways to read a mailbox. Here’s the usual imaplib version of “print unread mail and save the attachments”, with the email package doing the parsing:

import email
import imaplib
import os
from email import policy
from email.message import EmailMessage
from pathlib import Path

with imaplib.IMAP4_SSL("imap.example.com") as imap:
    imap.login(os.environ["IMAP_USER"], os.environ["IMAP_PASSWORD"])
    imap.select("INBOX")
    _, data = imap.search(None, "UNSEEN")
    for number in data[0].split():
        _, parts = imap.fetch(number, "(RFC822)")  # also marks the message \Seen
        item = parts[0]
        if not isinstance(item, tuple):
            continue
        msg = email.message_from_bytes(item[1], policy=policy.default)
        assert isinstance(msg, EmailMessage)  # policy.default builds an EmailMessage

        body = msg.get_body(preferencelist=("plain", "html"))
        print(msg["From"], msg["Subject"])
        print(body.get_content() if body else "")

        for part in msg.iter_attachments():
            filename = part.get_filename()
            payload = part.get_payload(decode=True)
            if filename and isinstance(payload, bytes):
                Path(Path(filename).name).write_bytes(payload)

That is solid code. policy.default gives you the modern EmailMessage API, with get_body() and iter_attachments(), which beats walking the MIME tree by hand. What it needs around it is a mailbox: an IMAP host, port 993, and credentials. Gmail and Microsoft 365 generally won’t accept your normal password over IMAP: they expect an app password or OAuth 2.0, which imaplib supports through authenticate("XOAUTH2", ...) once you have a token. For push, IMAP has IDLE, and Python 3.14 added IMAP4.idle(). On earlier versions you poll or use a third-party library.

poplib is simpler and narrower. POP3 downloads messages to one client, usually deleting them from the server, and has no folders, flags or search. It suits draining a mailbox into your own storage.

imaplib poplib Mailcycle Python SDK
Install Standard library Standard library pip install mailcycle
You need An IMAP mailbox and its credentials A POP3 mailbox and its credentials A recovery phrase, plus an API key if you want one
New addresses Made at your mail provider Made at your mail provider mc.addresses.create() in code
Parsing Raw MIME, parsed with email Raw MIME, parsed with email Parsed fields: text, html, attachments
Tracker-free HTML Strip it yourself Strip it yourself safe_html, with blocked listing what was removed
Attachments iter_attachments() and get_payload(decode=True) The same mc.messages.attachment(message, index)
Folders and flags Yes, server-side No Inbox, sent, junk, trash, stars, read state
Search Server-side SEARCH No In Python, after decrypting
New-mail push IDLE (IMAP4.idle() from 3.14) No Webhooks and the event stream
Wait for one email Write the loop yourself Write the loop yourself wait_for()
Mail at rest Depends on the provider Depends on the provider Sealed with keys from your recovery phrase

Choose imaplib when the mail lives in a mailbox you already have, like a shared support inbox at Gmail, Outlook or your own server, and your code needs to read it where it is. Choose poplib to drain a simple mailbox into your own storage. Choose an email API when your code needs addresses of its own: one per customer, per test run or per agent, created in code, with mail pushed to you as it arrives.

Troubleshooting

  • Messages have opened=False and empty fields. The client has no phrase, or a phrase from a different account. Build it with phrase=, or with Mailcycle.sign_in().
  • MailcycleError: The recovery phrase is needed to … You called addresses.create() or messages.attachment() on a client built from an API key alone. Pass phrase= as well.
  • MailcycleError: That phrase belongs to a different account The API key and the phrase are from two accounts. Check both environment variables.
  • Nothing arrives at a new address. Check address.receives in mc.addresses.list(). An address without a public key refuses mail. Also check the sender used the exact address, since prefixed names have a random ending.
  • wait_for raises MailcycleError about address_id. Without the event stream, it can only wait by polling one address. Pass address_id=, or install mailcycle[events].
  • APIError with code="rate_limited" (429). You’re reading too much too fast. Back off, read only what’s new as shown above, or switch to webhooks.
  • session_required (403). Adding a webhook or an API key needs a signed-in session. Use Mailcycle.sign_in() for that call.
  • A 404 fetching an attachment. The part has stored=False: it had no body. Skip it.
  • The webhook route returns 401 for real deliveries. You’re verifying a parsed body, or the wrong secret. Use the raw request bytes and the whsec_ secret of this webhook. Rotating the secret makes the old one stop working at once.
  • The event stream ends with 4003. An API key on a plan without the stream, or a plan that stopped including it. Use a session, or upgrade.

Every error code is listed in Errors.

Reply from Python, or hand the inbox to an agent

Reading is half of a conversation. To answer a message in the same thread, pass it as reply_to= to mc.messages.send(), and send to message.reply_to. Sending email from Python covers that, along with the plans that send. A signed-in session sends from Personal up, and an API key from Scale up.

If an AI agent, rather than your own code, should read the inbox, Mailcycle also runs as an MCP server with tools such as wait_for_message, read_message and read_attachment, for Claude Code, Cursor, Codex or any other MCP client. Start with Give your AI agent its own email inbox and the email MCP server guide. Before an agent reads mail from strangers, read AI agent email security: a message can carry instructions, and reply-only mode stops it getting the agent to mail anyone else, but the message can still steer the reply or the agent’s other tools.

Next steps

FAQ

How do I receive email in Python?

Give your code an address that receives mail, then read it with a client. With Mailcycle, pip install mailcycle, sign in with Mailcycle.sign_in(phrase), create an address with mc.addresses.create(), and call mc.messages.wait_for(address_id=...) to block until the next message arrives. It comes back already parsed and decrypted: sender, subject, text, HTML and attachments.

How do I read emails from an inbox in Python?

Call mc.messages.list(address_id) for one page, newest first, or loop over mc.messages.iterate(address_id) to walk the whole folder. Each item is a Message with from_address, subject, text, safe_html, attachments and read. Pass folder="junk", "trash", "sent" or "starred" to read another folder.

How do I download email attachments in Python?

Each Message lists its files in message.attachments, with filename, mime_type, size and index. Call mc.messages.attachment(message, attachment.index) to get the bytes, opened on your machine, and write them with Path.write_bytes(). Clean the file name first, because it comes from the sender.

Is there an alternative to imaplib for reading email in Python?

Yes. An email API replaces the IMAP connection, the login and the MIME parsing with one HTTPS client. Mailcycle's Python SDK returns each message as a typed dataclass with the body and attachments already separated, and can push new mail to you by webhook or WebSocket.

What is the difference between imaplib and poplib?

IMAP keeps mail on the server, with folders, read flags and server-side search, so several clients see the same mailbox. POP3 downloads messages to one client and usually deletes them from the server, with no folders or flags. Both are in Python's standard library, and both hand you raw MIME that you parse with the email package.

How can a Python script wait for a new email?

Call mc.messages.wait_for(address_id=..., subject=..., since=..., timeout=...). It listens on the event stream when mailcycle[events] is installed and polls every five seconds otherwise, and returns the first matching message. If nothing matches in time it raises APIError with code="timeout".

How do I get notified when an email arrives in a Python web app?

Add a webhook for message.received, point it at a route in your FastAPI, Flask or Django app, and check each delivery with verify_webhook_signature() against the raw body. The event carries the message id, never the content, so fetch it with mc.messages.get() in a background task. Webhooks are on the Operator plan and above.

Can I receive email in Python on the free plan?

Yes. A script signed in with the recovery phrase through Mailcycle.sign_in() can create addresses, read mail, download attachments and use the event stream on every plan, Free included. API keys and webhooks start at Operator. See Plans and limits.

Why does Mailcycle need my recovery phrase to read email?

Mail is sealed the moment it arrives, to a key derived from your recovery phrase. The Python client derives the same key on your machine and opens each message in your process. Without the phrase, messages still list but come back with opened=False and empty content.

Receive email in code