Metadata-Version: 2.5
Name: fake-email-pro
Version: 0.2.0
Summary: Official client for the fake-email.pro API: disposable mailboxes for testing signup, OTP and magic-link emails.
Project-URL: Homepage, https://fake-email.pro/api
Project-URL: Documentation, https://fake-email.pro/api/docs/sdks
Project-URL: API reference, https://api.fake-email.pro/docs
Project-URL: Repository, https://github.com/fake-email-pro/fake-email-python
Project-URL: Issues, https://github.com/fake-email-pro/fake-email-python/issues
Project-URL: Changelog, https://github.com/fake-email-pro/fake-email-python/blob/main/CHANGELOG.md
Author: fake-email.pro
License: MIT
License-File: LICENSE
Keywords: api,disposable email,e2e,email testing,fake email,inbox,mailbox,otp,playwright,pytest,sdk,temp mail,temp-mail,temporary email,testing,verification code
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Software Development :: Testing
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: anyio>=3
Requires-Dist: httpx<1,>=0.25
Provides-Extra: dev
Requires-Dist: anyio>=4; extra == 'dev'
Requires-Dist: build>=1; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: pyyaml>=6; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: twine>=5; extra == 'dev'
Requires-Dist: types-pyyaml; extra == 'dev'
Description-Content-Type: text/markdown

# fake-email-pro

[![PyPI](https://img.shields.io/pypi/v/fake-email-pro.svg)](https://pypi.org/project/fake-email-pro/)
[![Python versions](https://img.shields.io/pypi/pyversions/fake-email-pro.svg)](https://pypi.org/project/fake-email-pro/)
[![CI](https://github.com/fake-email-pro/fake-email-python/actions/workflows/ci.yml/badge.svg)](https://github.com/fake-email-pro/fake-email-python/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/fake-email-pro/fake-email-python/blob/main/LICENSE)

The official Python client for the [fake-email.pro API](https://fake-email.pro/api): disposable
mailboxes over HTTP for testing signup, OTP and magic-link emails in pytest, Playwright and CI.

Create a real inbox in one call, let your app send to it, and get the one-time code or the confirmation
link back — no mail server, no shared test inbox, no regex over HTML.

```python
from fake_email_pro import FakeEmail

client = FakeEmail()  # reads FAKE_EMAIL_API_KEY
mailbox = client.mailboxes.create()

# ... your app sends a verification email to mailbox.address ...

code = client.wait_for_code(mailbox.address)  # "048213"
```

- Sync and async clients with the same API, fully typed (`py.typed`), Python 3.9+.
- Test helpers that long-poll the server: `wait_for_message`, `wait_for_code`, `wait_for_link`.
- One-time codes and confirm links are extracted by the server, so you don't parse emails yourself.
- Automatic retries on rate limits and transient errors, honoring `Retry-After`; the wait helpers ride out
  a rate limit or a deploy until their own deadline.
- Small dependencies: [httpx](https://www.python-httpx.org/) and [anyio](https://anyio.readthedocs.io/)
  (which httpx already uses).

**Links:** [Product page](https://fake-email.pro/api) ·
[SDK docs](https://fake-email.pro/api/docs/sdks) ·
[API reference](https://api.fake-email.pro/docs) ·
[Changelog](https://github.com/fake-email-pro/fake-email-python/blob/main/CHANGELOG.md)

## Install

```bash
pip install fake-email-pro
```

or `uv add fake-email-pro`, or `poetry add fake-email-pro`.

## Get an API key

API access comes with every account, the free plan included:

1. Sign in at [fake-email.pro](https://fake-email.pro).
2. Open **Settings → API keys** ([fake-email.pro/settings/api-keys](https://fake-email.pro/settings/api-keys))
   and create a key. It starts with `fep_` and is shown only once.
3. Put it in the `FAKE_EMAIL_API_KEY` environment variable (or a CI secret of that name).

```bash
export FAKE_EMAIL_API_KEY=fep_...
```

Need a bigger monthly mailbox quota or higher rate limits? See the
[PRO plan](https://fake-email.pro/pricing). Your current numbers are always in `client.limits.get()`.

The API is server-to-server: never ship the key to browser JavaScript.

## Quickstart

```python
from fake_email_pro import FakeEmail

with FakeEmail() as client:
    mailbox = client.mailboxes.create()
    print(mailbox.address)  # e.g. quiet.harbor.42@<domain>
    print(mailbox.expires_at)  # accepts mail for 24 hours

    signup(email=mailbox.address)  # your code under test

    message = client.wait_for_message(mailbox.address, subject="verify", timeout=60)
    print(message.from_, message.subject)
    print(message.code)  # best one-time code, or None
    print(message.confirm_link)  # best "confirm / sign in" link, or None

    client.mailboxes.delete(mailbox.address)
```

`wait_for_message` returns as soon as a matching message is there — including one that arrived
*before* the call — and raises `WaitTimeoutError` when `timeout` seconds pass without one (at once for a
`timeout` of 0 or less).

## Async

`AsyncFakeEmail` has the same methods, awaited. It works with asyncio and trio.

```python
import asyncio
from fake_email_pro import AsyncFakeEmail


async def main() -> None:
    async with AsyncFakeEmail() as client:
        mailbox = await client.mailboxes.create()
        await signup(email=mailbox.address)
        link = await client.wait_for_link(mailbox.address)
        print(link)
        async for message in client.messages.iter(mailbox.address):
            print(message.subject)


asyncio.run(main())
```

## pytest: a fresh mailbox per test

```python
# conftest.py
import contextlib

import pytest
from fake_email_pro import FakeEmail, NotFoundError


@pytest.fixture(scope="session")
def fake_email():
    with FakeEmail() as client:
        yield client


@pytest.fixture
def mailbox(fake_email: FakeEmail):
    mailbox = fake_email.mailboxes.create()
    yield mailbox
    with contextlib.suppress(NotFoundError):  # the test may have deleted it already
        fake_email.mailboxes.delete(mailbox.address)
```

```python
# test_password_reset.py
def test_reset_email_has_a_code(fake_email, mailbox, app):
    app.request_password_reset(mailbox.address)

    code = fake_email.wait_for_code(mailbox.address, subject="reset", timeout=30)

    assert app.reset_password(mailbox.address, code, "n3w-passw0rd").ok
```

Each test gets its own address, so tests can run in parallel (`pytest -n auto`) without reading each
other's mail. Every created mailbox spends one unit of the monthly quota; deleting it does not give the
unit back, but keeps your mailbox list short.

## Playwright: sign up with an emailed code

With [pytest-playwright](https://pypi.org/project/pytest-playwright/) and the fixtures above:

```python
from playwright.sync_api import Page, expect


def test_signup_with_otp(page: Page, fake_email, mailbox):
    page.goto("https://staging.example.com/signup")
    page.get_by_label("Email").fill(mailbox.address)
    page.get_by_role("button", name="Create account").click()

    code = fake_email.wait_for_code(mailbox.address, from_="no-reply@example.com")

    page.get_by_label("Verification code").fill(code)
    page.get_by_role("button", name="Verify").click()
    expect(page.get_by_text("Welcome")).to_be_visible()
```

For a magic link, open the URL instead:

```python
link = fake_email.wait_for_link(mailbox.address, subject="sign in")
page.goto(link)
```

## Waiting for messages

### The next message: `after`

Without `after`, any message of the mailbox counts. To wait for the *next* one, pass the id of the message
you already have:

```python
first = client.wait_for_message(mailbox.address)
trigger_resend()
second = client.wait_for_message(mailbox.address, after=first.id)
```

`after` also takes a time — an RFC 3339 string or a `datetime` — for "messages since moment X" by the
server's clock. Prefer a message id: two messages in the same millisecond can't be told apart by time.
A naive `datetime` is taken as local time.

### Filters and `match`

```python
client.wait_for_message(
    mailbox.address,
    from_="acme.example",  # case-insensitive substring of the sender address
    subject="verification code",  # case-insensitive substring of the subject
    match=lambda m: m.attachments_count > 0,  # any predicate over SimpleMessage
    timeout=90,
)
```

`from_` and `subject` are applied by the server. A message that fails `match` is skipped and the wait
goes on after it, until the deadline. If a skipped message is deleted meanwhile, the wait goes on after its
time instead of its id.

### Codes and links

`wait_for_code` and `wait_for_link` wait for a message *that has* a code or a link and return it as a
string. They take the same arguments as `wait_for_message`. A message without one (a welcome email that
arrives first, say) is skipped.

```python
code = client.wait_for_code(mailbox.address, subject="code")
link = client.wait_for_link(mailbox.address, subject="confirm")
```

The server ranks what it finds: `message.code` is its best guess, and the full message has all of them.

### Errors while waiting

The helpers keep waiting through what passes on its own: `429` (`rate_limit_exceeded` and
`too_many_waits`), `502`, `503`, `504`, Cloudflare's `520`–`524`, connection errors and timeouts. They pause
for `Retry-After` (or about a second), never past the deadline, and each new request asks the server for
only the time that is left. When the deadline passes you get `WaitTimeoutError` (the last such error is
its `__cause__`), not the HTTP error. Anything else — `400`, `401`, `402`, `403`, `404` for the mailbox,
`409` — is raised at once. The same goes for the extra read of the full message in `wait_for_code` and
`wait_for_link`.

### One request: `messages.wait`

`client.messages.wait(address, timeout=30, after=..., from_=..., subject=...)` is a single long-poll
request (`timeout` whole seconds, 1–60; the HTTP read timeout is that plus 10 s). It returns the message,
or `None` when nothing arrived in time. Its errors go through the ordinary `max_retries`. The helpers above
loop over it for you.

## Reading messages

```python
page = client.messages.list(mailbox.address, size=50)  # newest first; Page[SimpleMessage]
for message in client.messages.iter(mailbox.address):  # every page
    print(message.created_at, message.subject)

full = client.messages.get(mailbox.address, message.id)  # DetailedMessage
full.html, full.text  # bodies (None if absent)
full.codes  # every code found, best first
full.links  # every link, best "confirm / sign in" first: Link(url, text)
full.attachments  # Attachment(id, content_type, file_name, size_bytes)

client.messages.delete(mailbox.address, message.id)
```

### Attachments and raw EML

```python
from pathlib import Path

downloads = Path("downloads")
for attachment in full.attachments:
    content = client.messages.attachment(mailbox.address, full.id, attachment.id)
    content.data  # bytes, decoded
    content.content_type  # "application/pdf"
    content.file_name  # "invoice.pdf" (UTF-8 names decoded; the attachment id if the email gave none)

    # The sender picks the name: keep only its last part, so "../../.bashrc" can't leave the folder.
    name = Path(content.file_name or "").name
    if name in ("", ".."):
        name = attachment.id
    (downloads / name).write_bytes(content.data)

eml: bytes = client.messages.raw(mailbox.address, full.id)

import email

parsed = email.message_from_bytes(eml)
```

A message the server could not parse has `body_state == "UNPARSED"`: its raw EML is the only way to
read it.

## Mailboxes, domains, limits

```python
client.domains.list()  # [Domain(name=..., type="PUBLIC"), ...]
client.mailboxes.create(domain="example.org")  # random address on a domain
client.mailboxes.create(local_part="ci-runner-7", domain="example.org")  # your address (plan permitting)

client.mailboxes.get(address)
client.mailboxes.list(page=0, size=20)  # Page[Mailbox], newest first

# iter() fetches pages by number: collect first, then delete, or half the mailboxes are skipped.
for mailbox in list(client.mailboxes.iter()):  # every active mailbox
    client.mailboxes.delete(mailbox.address)

limits = client.limits.get()
limits.quota.limit, limits.quota.used, limits.quota.resets_at
limits.requests_per_minute, limits.concurrent_waits
```

The server lowercases `local_part`, so `"CI-Runner-7"` gives `ci-runner-7@example.org`. A mailbox accepts
mail for 24 hours; after that it and its messages are gone and every call on it raises `NotFoundError`. An
address is never handed out twice.

## Errors

Every exception derives from `FakeEmailError`. API errors are `APIError` subclasses with `status_code`,
`code` (the server's error code, e.g. `"address_taken"`), `message`, `body`, `headers` and `rate_limit`.

| Exception | When |
|---|---|
| `BadRequestError` | 400: an invalid parameter or body |
| `AuthenticationError` | 401: missing, unknown, revoked or expired key |
| `QuotaExhaustedError` | 402: the monthly mailbox quota is used up; has `limit`, `used`, `resets_at`, `upgrade_url` |
| `PermissionDeniedError` | 403 `plan_forbidden`: the plan does not allow this (e.g. a custom `local_part`) |
| `NotFoundError` | 404: no such mailbox (or it expired), message or attachment; an unknown or unavailable `domain` on create; an `after` id that names no message |
| `ConflictError` | 409 `address_taken`: that address was already issued |
| `RateLimitError` | 429: `code` is `rate_limit_exceeded` or `too_many_waits`; has `retry_after` |
| `InternalServerError` | 5xx |
| `APIConnectionError`, `APITimeoutError` | no response: network failure or timeout |
| `WaitTimeoutError` | a `wait_for_*` helper ran out of time (also a `TimeoutError`) |

```python
from fake_email_pro import ConflictError, QuotaExhaustedError

try:
    mailbox = client.mailboxes.create(local_part="ci-runner-7", domain="example.org")
except ConflictError:
    mailbox = client.mailboxes.create(domain="example.org")
except QuotaExhaustedError as e:
    raise SystemExit(f"Quota {e.used}/{e.limit}, renews {e.resets_at:%Y-%m-%d}: {e.upgrade_url}")
```

## Retries and rate limits

The client retries up to `max_retries` times (default 2):

- `429` (rate limit, too many concurrent waits) and `503` for any request — the server refuses these
  before doing anything, so repeating is safe. A `503` whose `Retry-After` is over 5 s (no domain to issue
  an address on, say) is an outage, not a blip, and is raised at once;
- `502`, `504`, Cloudflare's `520`–`524` and connection errors for `GET` and `DELETE` only — a `POST` that
  may have created a mailbox is never repeated.

It sleeps for `Retry-After` when the server sends it (capped at 60 s), otherwise backs off
exponentially with jitter (0.5 s, 1 s, 2 s, … up to 8 s). After the last attempt the error is raised.
A `DELETE` whose response was lost (a timeout, a connection error, `502`/`504`/`52x`) may have gone
through, so a `404` on its retry counts as deleted; a `404` on the first attempt is still `NotFoundError`.

The `wait_for_*` helpers don't use `max_retries`: they retry on their own until their deadline (see
[Errors while waiting](#errors-while-waiting)).

The rate limit is requests per minute per account, shared by all your keys; `wait` requests count once
however long they are held open. `error.rate_limit` has the window state from the `X-RateLimit-*` headers
(`limit`, `remaining`, `reset_at`). Waits held open at once are capped at `limits.concurrent_waits`:
run fewer parallel workers than that, or let the wait helpers sit out the occasional `too_many_waits`.

## Configuration

```python
import httpx
from fake_email_pro import FakeEmail

client = FakeEmail(
    api_key="fep_...",  # default: FAKE_EMAIL_API_KEY
    base_url="https://api.fake-email.pro",  # default
    timeout=30.0,  # seconds per request; a wait gets its own timeout + 10 s
    max_retries=2,  # 0 disables retries
    user_agent="my-e2e-suite/1.4",  # prepended to fake-email-pro-python/<version>
    # proxies, transports, event hooks; `proxy=` needs httpx 0.26+ (older httpx: `proxies=`)
    http_client=httpx.Client(proxy="http://proxy.internal:3128"),
)
```

`AsyncFakeEmail` takes the same arguments, with `http_client=httpx.AsyncClient(...)`. A client you pass in
is not closed by `close()` — you own it. The `timeout` option is set on every request, so it wins over a
timeout configured on your `http_client`. Use the client as a context manager (`with` / `async with`) or
call `close()` to release connections.

## Requirements

Python 3.9 to 3.14, httpx 0.25 or newer and anyio 3 or newer. The package is fully typed and checked
with `mypy --strict`.

## License

[MIT](https://github.com/fake-email-pro/fake-email-python/blob/main/LICENSE) © fake-email.pro
