Skip to content
Mailcycle
Get started
Python email SDK

Python email API: receive, read and send email in Python.

The Mailcycle Python email API receives email with no mail server and no IMAP login. Create an address in one call, wait for the message that lands on it, read the text, HTML and attachments, and reply in the same thread. Mail is encrypted on arrival and opened by your Python process.

Install the Python package
pip install mailcycle
Python: receive and read a message
import os
from mailcycle import Mailcycle

mc = Mailcycle.sign_in(os.environ["MAILCYCLE_PHRASE"])
address = mc.addresses.create()
print("Send an email to", address.email_address)

message = mc.messages.wait_for(address_id=address.id, timeout=300)
print(message.subject, message.text)
  • mailcycle
  • Python 3.10 or later

The Python SDK is one way into the Mailcycle email API. Full reference at https://docs.mailcycle.email.

Quickstart

Receive and send email in Python.

Sign in, create an address, wait for a message and answer it. That is the whole loop, and it is the same loop whether the mail is a sign-up code, a customer or a receipt.

  1. 1Install mailcycle. Create a free account (no card) and set MAILCYCLE_PHRASE to the twelve-word recovery phrase it shows you.
  2. 2Create an address with mc.addresses.create(). It receives mail straight away.
  3. 3Wait for the next message with mc.messages.wait_for(), or take it from a webhook.
  4. 4Reply with mc.messages.send(), threaded under the original.
The full Python guide
Python: create an address, wait for mail, reply
import os
from mailcycle import Mailcycle

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

# A new address that receives mail, sealed to your key.
address = mc.addresses.create(prefix="signup", label="Test run 42")
print(address.email_address)  # signup-x7k2@...

# Wait for the verification email, decrypted here.
message = mc.messages.wait_for(
    address_id=address.id, subject="verification", timeout=60
)
print(message.subject, message.text)

# Reply in the same thread.
mc.messages.send(
    from_address=address.email_address,
    to=message.reply_to,
    subject=f"Re: {message.subject}",
    text="Thanks, confirmed.",
    reply_to=message,
)
Receive email

Read email in Python.

Create an address, wait for the next email that lands on it, then read the sender, subject, text and attachments from a plain dataclass. Mail that is already there comes back from list().

  • wait_for returns the next message, decrypted, within the timeout you set.
  • mc.messages.list(address_id) returns the mail already received.
  • Attachments come back as bytes, opened by your Python process.
Python: receive email and save its attachments
import os
from pathlib import Path

from mailcycle import Mailcycle

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

# An address that receives email from now on.
address = mc.addresses.create(prefix="orders")
print("Send an email to", address.email_address)

# Receive the next email, waiting up to five minutes.
message = mc.messages.wait_for(address_id=address.id, timeout=300)
print(f"{message.from_address}: {message.subject}")
print(message.text)

# Save each attachment, opened on this machine.
for file in message.attachments:
    data = mc.messages.attachment(message, file.index)
    Path(Path(file.filename).name).write_bytes(data)
What it does

The whole email API, from Python.

Everything the Mailcycle console can do is in the package: addresses, inbound mail, sending, webhooks, events, API keys and devices.

Create email addresses from Python

mc.addresses.create() mints a new address on a shared domain, or on your own domain from Scale, and it receives mail at once. Give it a prefix and a label sealed on your machine.

Receive email and wait for it

mc.messages.wait_for() listens on the event stream and returns the next matching message, filtered by sender or subject, opened and ready to read. Without a stream it checks every five seconds.

Read and parse incoming email

mc.messages.list() and .attachment() return the sender, subject, plain text, the original HTML, a safe HTML with remote images and trackers removed, and every attachment as bytes.

Send email and reply in the thread

mc.messages.send() sends from an address your account owns, with up to ten files. Pass the message you are answering and the threading headers are filled in.

Inbound email webhooks

Register a URL and every message.received event is POSTed to it, signed with HMAC-SHA256 and retried. verify_webhook_signature() checks the signature in one line.

A live event stream

mc.events.stream() carries the same events over a WebSocket the moment they happen, and reconnects after a drop. Events carry ids, never content.

Email testing

Test email verification in pytest, Playwright for Python and Selenium.

Create a fresh address in a pytest fixture, drive your sign-up form with Playwright or Selenium, then call wait_for and pull the one-time code or magic link out of message.text. Delete the address in teardown and its place on your plan is free again.

  • A real address on a real domain, so the mail goes through the same path your users' does.
  • One call blocks until the message lands, filtered by subject or sender, with a timeout you set.
  • Text, HTML and attachments come back parsed, so pulling out a code or a link is a regular expression.
  • Mail received from the moment you start waiting counts, even if it lands before the stream is up.
Inbound email webhooks

Handle incoming email in Flask, Django and FastAPI.

Rather than polling, let the mail come to you. A webhook POSTs each event to your URL the moment it happens, signed so you can prove it came from Mailcycle, and retried if your server is down.

Events carry ids, never content. Fetch the message by id and it is opened in your code, exactly as it would be otherwise. Webhooks are on Operator and above.

Webhooks in the docs
Flask: verify a webhook, then fetch the message
import os

from flask import Flask, abort, request
from mailcycle import Mailcycle, verify_webhook_signature

app = Flask(__name__)
mc = Mailcycle.sign_in(os.environ["MAILCYCLE_PHRASE"])
SECRET = os.environ["MAILCYCLE_WEBHOOK_SECRET"]  # from mc.webhooks.create(), shown once

@app.post("/hooks/mailcycle")
def mailcycle_webhook():
    raw = request.get_data()  # the body exactly as it arrived
    signature = request.headers.get("Mailcycle-Signature")
    if not verify_webhook_signature(SECRET, raw, signature):
        abort(401)

    event = request.get_json()
    if event["type"] == "message.received":
        message = mc.messages.get(event["payload"]["messageId"])
        print(message.from_address, message.subject, message.text)
    return "", 204
No mail server

Instead of smtplib, imaplib and a mailbox.

Python's standard library can speak SMTP and IMAP, but smtplib needs an SMTP server to hand mail to and imaplib needs a mailbox to read from. You end up provisioning a mail account, storing its password, polling it and parsing raw MIME with the email package.

Here an address is a function call, mail is pushed to a webhook or waited on with one blocking call, and the message comes back already parsed: sender, subject, text, HTML with remote content stripped, and attachments as bytes.

Sending is built for answering the mail your addresses receive, within your plan's daily limit.

Encrypted on arrival

Mail is encrypted the moment it arrives and opened in your Python code.

Each address has a key pair derived from your recovery phrase. Incoming mail is sealed to its public key before anything is written down, and the package derives the private key on your machine to open it.

How the encryption works
  • Signing in proves you hold the key by answering a challenge, so the phrase never crosses the wire.
  • Bodies, attachments, address labels and API key names are all sealed. The server stores ciphertext.
  • Mail sealed by one SDK opens in every other, and in the app, because they share one published format.
  • The package is checked against Mailcycle's published test vectors, including the cases that must be refused.
  • Search runs on your device, where mail is decrypted.
Use cases

What developers build with the Python SDK.

It runs in Django and Flask apps, FastAPI services, Celery workers, Jupyter notebooks and command-line scripts: anywhere Python code needs an email address of its own.

End-to-end tests for sign-up and login

Verification emails, one-time passcodes, magic links, password resets and invitations, checked by a real test in pytest, Playwright for Python and Selenium.

A support or orders inbox your code answers

Give an address to a queue, read what customers send, and reply from the address they wrote to, threaded under their message.

Receipts, invoices and alerts as data

Point suppliers, monitoring and other services at an address and pull the text and attachments straight into your own records.

An address per customer, job or device

Mint addresses on demand and keep each stream of mail separate, with its own label, and delete one when the job is done.

Building an AI agent? It can have an inbox too, through the Mailcycle MCP server, without writing any Python at all.

The package

Python SDK at a glance.

Maintained by Mailcycle, the team that runs the API.

The Mailcycle Python SDK at a glance
Packagemailcycle
RegistryPyPI
Install withpip, uv or Poetry
NeedsPython 3.10 or later
AlsoAdd the events extra, pip install 'mailcycle[events]', for the live event stream.
LicenceApache 2.0, free to use in your own applications
APIJSON over HTTPS at api.mailcycle.email
GuideThe Python guide in the docs
GuidesSend email from PythonReceive email in Python

What each plan unlocks. Free receives mail. A signed-in session sends from Personal up. API keys and webhooks start at Operator, and sending from an API key at Scale. See pricing.

Questions

Python email SDK questions.

Install the package with pip install mailcycle, sign in with your recovery phrase, and create an address with mc.addresses.create(). Mail sent to that address is stored encrypted, and mc.messages.list() or mc.messages.wait_for() returns it decrypted, with the sender, subject, text, HTML and attachments already parsed. There is no mail server or IMAP account to set up.

The Mailcycle email API is JSON over HTTPS, and the mailcycle package on PyPI is its Python library. It creates email addresses, receives and reads their mail, sends replies with attachments, verifies webhooks and streams events, and it decrypts each message inside your Python process.

Call mc.messages.list(address.id). It returns a page whose messages each carry from_address, subject, text, html, safe_html and attachments, plus a next_cursor for the next page. mc.messages.iterate(address.id) walks every page for you.

Every message lists its files in message.attachments, each with index, filename, mime_type and size. mc.messages.attachment(message, file.index) returns the bytes, decrypted on your machine, ready to write to disk or hand to your own storage.

Register a webhook for message.received and add a POST view, as in the Flask example on this page. Check the Mailcycle-Signature header with verify_webhook_signature on the raw body, then fetch the message by id with mc.messages.get. Webhooks are on Operator and above; a worker process can call wait_for instead.

Call mc.messages.send() with a from address your account owns, a recipient, a subject and text. The API sends it; you never configure SMTP credentials. Passing reply_to=message fills in the threading headers so the reply lands in the same conversation. Sending from a signed-in session works from the Personal plan, and from an API key on Scale and above.

Yes. Create an address in a fixture, submit it to the sign-up form under test, and call mc.messages.wait_for(address_id=..., subject=...) to block until the verification email arrives, then read the code or link from message.text. If nothing arrives before the timeout it raises an APIError with the code timeout, which fails the test cleanly.

Yes. The client is synchronous, so in an async function call it through asyncio.to_thread and the event loop keeps running while it waits: message = await asyncio.to_thread(mc.messages.wait_for, address_id=address.id, timeout=300). One client can serve many such calls at once.

Python 3.10 or later. The live event stream needs the optional websockets dependency, installed with pip install 'mailcycle[events]'. Without it, wait_for checks the address every five seconds instead.

The package is free and open source under the Apache 2.0 licence. The Mailcycle Free plan costs nothing and needs no card: 3 email addresses and 3,000 messages received a month, receive only. Sending starts on Personal at $7 a month, API keys and webhooks on Operator at $15, and sending from an API key on Scale at $19.

Incoming mail is encrypted to the address's public key the moment it arrives, and the private key is derived from your recovery phrase inside your Python process. Mail you send leaves in plain text so the recipient's server can read it, and the copy kept in Sent is sealed like the rest.

Call mc.addresses.create() at the start of the run and delete the address at the end, which frees its place on your plan. Each address receives mail as soon as it exists. This is for testing your own product and for mail meant for you: registering accounts on other services in bulk, or against their terms, breaks the Acceptable Use Policy.

Up to 60 messages an hour per account and 20 an hour per device or agent (more on Fleet and Enterprise), within your plan's daily limit. The Acceptable Use Policy covers what may be sent.

The API is plain JSON over HTTPS at api.mailcycle.email, so anything can call it. Message content comes back encrypted, though, and the package is what derives the keys and opens it. Without an SDK you would implement the published encryption format yourself.

Give your Python code an email address.

Create an account, create an address, and read what arrives. The free tier needs no card.