Metadata-Version: 2.4
Name: receiverdotemail
Version: 2.1.1
Summary: Official Python SDK for Receiver.email: programmable email inboxes for tests and AI agents, with OTP and link extraction
Author-email: "Receiver.email" <contact@receiver.email>
License-Expression: MIT
Project-URL: Homepage, https://www.receiver.email
Project-URL: Documentation, https://www.receiver.email/docs/sdks/python
Project-URL: Quick start, https://www.receiver.email/docs/quickstart
Keywords: receiver.email,receiverdotemail,email,email testing,testing,inbox api,test email,otp,2fa,magic link,email verification,e2e,pytest,playwright,selenium,test automation,qa,ai agents,asyncio,email-api,inbound-email,e2e-testing,disposable-email
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Framework :: AsyncIO
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: Topic :: Communications :: Email
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.25.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

# receiverdotemail

Official Python SDK for [Receiver.email](https://www.receiver.email), the programmable inbox API for tests, AI agents and scripts: create an address under your project, wait for the email, and get the OTP code and links already extracted.

```bash
pip install receiverdotemail
```

```python
import asyncio
from receiverdotemail import ReceiverClient

async def main():
    async with ReceiverClient() as receiver:  # reads RECEIVER_API_KEY
        inbox = await receiver.inboxes.create(prefix="signup")  # a fresh address per run
        await my_app.sign_up(inbox.address)  # your app sends the email

        # Long-polls until the email arrives; raises ReceiverTimeoutError after 60 s
        otp = await receiver.emails.wait_for_otp(
            recipient=inbox.address, since=inbox.created_at, timeout=60
        )
        print(otp.code)  # "847291"

asyncio.run(main())
```

Works the same from pytest (see [Pytest Integration](#pytest-integration)), Playwright for Python or Selenium tests, scripts and AI agents. Python 3.9+, async, typed (Pydantic models).

**Docs:** [SDK reference](https://www.receiver.email/docs/sdks/python) · [Quick start: create a project and an API key](https://www.receiver.email/docs/quickstart) · [REST API](https://www.receiver.email/docs/api-reference)

Guides: [pytest](https://www.receiver.email/docs/guides/pytest) · [Playwright](https://www.receiver.email/docs/guides/playwright) · [Selenium](https://www.receiver.email/docs/guides/selenium) · [OTP / 2FA](https://www.receiver.email/docs/guides/otp-verification) · [Magic links](https://www.receiver.email/docs/guides/magic-links) · [Password resets](https://www.receiver.email/docs/guides/password-reset)

Also available: the [TypeScript SDK](https://www.npmjs.com/package/@receiverdotemail/sdk), an [MCP server](https://www.npmjs.com/package/@receiverdotemail/mcp) for AI agents and a [CLI](https://www.npmjs.com/package/@receiverdotemail/cli).

## Features

- **Unique inboxes on demand**: mint an address per test or agent run with `inboxes.create()`
- **Waits of any length**: `wait_for` and `wait_for_otp` loop the API's 60 s long-poll for you
- **OTP extraction**: the code, plus every candidate code found, newest first
- **Live stream**: `async for` over new emails (Server-Sent Events, reconnects automatically)
- **Link extraction, filtering, pagination, webhooks**
- **Type-safe**: Pydantic models with snake_case attributes
- **Async/await** API built on `httpx`

## Authentication

Create an API key (`recv_live_...`) in the [dashboard](https://www.receiver.email/dashboard):
open your project, then Settings → API Keys. `ReceiverClient()` reads it from
`RECEIVER_API_KEY` (and the API URL from `RECEIVER_API_URL`, if set).

With an API key, `project_id` is optional on every email and inbox method: the SDK
calls `whoami()` once and caches the key's project. Pass `project_id=...` to skip that
call, or when authenticating with a dashboard session token.

## Configuration

```python
client = ReceiverClient(
    api_key="recv_live_...",                     # default: RECEIVER_API_KEY
    base_url="https://api.receiver.email/api/v1",  # default: RECEIVER_API_URL, else production
    timeout=30,                                  # HTTP timeout for ordinary requests (seconds)
    user_agent="my-tool/1.0",                    # default: receiver-sdk-py/<version>
    project_id="proj_abc123",                    # default: RECEIVER_PROJECT_ID, else looked up once via whoami()
)
```

A missing API key raises `ReceiverError` with `code == "MISSING_API_KEY"`.

## Usage

### Who am I

```python
me = await client.whoami()
print(me.auth_type)              # "apikey" or "jwt"
print(me.project.email_suffix)   # -a3kx9p2m@receiver.email
```

### Create an inbox

```python
inbox = await client.inboxes.create(prefix="reset")   # prefix is optional
print(inbox.address)     # reset-k2m9qa-a3kx9p2m@receiver.email
print(inbox.created_at)  # pass as `since` when waiting
```

Nothing is stored until mail arrives. Always build addresses this way (or from
`project.email_suffix`), never by hand.

### `since`

`since` (a `datetime` or ISO string) matches mail received **strictly after** it.
Use `inbox.created_at` for the first email, and the previous email's `received_at`
for the next one. Naive datetimes are treated as local time. When omitted, waits
look back 60 seconds and `stream()` starts from now.

### Wait for an email

```python
from receiverdotemail import ReceiverTimeoutError

try:
    email = await client.emails.wait_for(
        recipient=inbox.address,
        subject="Reset",          # substring, case-insensitive
        since=inbox.created_at,
        timeout=120,              # any length; the SDK repeats 60 s server waits
    )
    reset_link = next(link for link in email.links if "reset" in link)
except ReceiverTimeoutError as e:
    print(f"Nothing after {e.waited_seconds}s (since {e.since})")
```

`wait_for` returns an `Email` (with `text_body` and `links`) or raises
`ReceiverTimeoutError`. It never returns `None`.

### One-time codes

```python
otp = await client.emails.wait_for_otp(recipient=inbox.address, since=inbox.created_at, timeout=60)
print(otp.code, otp.code_length, otp.source)   # "123456", 6, "subject"
print([c.code for c in otp.candidates])        # every code found, newest first

# No waiting: returns None when nothing matches
otp = await client.emails.get_otp(recipient=inbox.address, code_length=6)
```

`code_length` is optional (4 to 8): without it the API auto-detects the code, and 5- and
7-digit codes are only found when you ask for them.

### Stream new emails

```python
async for event in client.emails.stream(recipient=inbox.address, subject="code"):
    print(event.email.subject, event.email.links)
    if event.otp:
        print(event.otp.code)
    break  # stop whenever you like
```

Filters: `recipient`, `sender`, `subject` (case-insensitive substring), `since` (default:
now). Each `event.email` has the same fields as a `list()` item. The server closes each connection after about 55 seconds; the SDK reconnects with
the `since` it reports, so no email is missed or repeated.

### Send a test email

```python
await client.emails.send_test(to=inbox.address)  # "Your Receiver.email test code: 123456"
```

### List, get and delete emails

```python
response = await client.emails.list(recipient=inbox.address, limit=50)
for email in response.emails:
    print(email.subject)

async for email in client.emails.list_all(sender="noreply@example.com"):
    ...

email = await client.emails.get("email_xyz789")   # or get("proj_abc123", "email_xyz789")
print(email.text_body, email.html_body, email.attachments)

# get() holds a preview of bodies over 100,000 characters; get_content reads the whole body
html = await client.emails.get_content("email_xyz789", "html")   # "text" (default), "html" or "raw"

await client.emails.delete("email_xyz789")

emails = await client.emails.find_by_sender("noreply@example.com")
resets = await client.emails.find_by_subject("Password Reset")  # case-insensitive substring
recent = await client.emails.find_by_recipient(inbox.address, since=inbox.created_at)
```

List filters: `recipient`, `sender`, `subject` (case-insensitive substring), `has_attachments`,
`since` (strictly after; `received_after` is a deprecated alias), `received_before`, `limit`
(max 100), `cursor`. With `subject` or `has_attachments` a page can hold fewer than `limit` emails
while `has_more` is still true, so page on with the cursor (`list_all()` does).

### Attachments

```python
from pathlib import Path

email = await client.emails.get("email_xyz789")
for index, attachment in enumerate(email.attachments):
    if attachment.omitted:  # over the plan's size limit, not stored
        continue
    data = await client.emails.get_attachment(email.id, index)  # bytes
    Path(attachment.filename).write_bytes(data)
```

Each attachment has `filename`, `content_type`, `size`, and either `url` (stored) or
`omitted == "too_large"`. `url`, `text_body_uri` and `html_body_uri` are API URLs that need the
same `Authorization` header as every other request, so they don't open in a browser;
`get_attachment()` and `get_content()` fetch them for you.

### Webhooks (dashboard session only)

Webhook management needs a dashboard session token; API keys get `403`.

```python
hook = await client.webhooks.create("proj_abc123", "https://ci.example.com/hooks/receiver")
print(hook.secret)  # whsec_..., shown once

hooks = await client.webhooks.list("proj_abc123")                   # List[Webhook]
hook = await client.webhooks.get("proj_abc123", hook.id)
hook = await client.webhooks.update("proj_abc123", hook.id, url="https://ci.example.com/hooks/v2")  # url and/or events
delivery = await client.webhooks.test("proj_abc123", hook.id)
deliveries = await client.webhooks.deliveries("proj_abc123", hook.id)  # last 50
await client.webhooks.delete("proj_abc123", hook.id)

rotated = await client.webhooks.rotate_secret("proj_abc123", hook.id)
print(rotated.secret)  # the new whsec_..., shown once
```

`rotate_secret()` takes effect at once: new deliveries are signed with the new secret (retries
already under way keep the old one). Deliveries your receiver rejects before it has the new
secret are not resent, so deploy it promptly.

Verify each delivery in your receiver with the raw request body:

```python
from receiverdotemail import verify_webhook_signature

if not verify_webhook_signature(secret, request.headers["Receiver-Signature"], raw_body):
    return 400
```

### Projects, organizations and API keys

Everything here except `projects.get` and `projects.list` needs a dashboard session token; an API key gets `403`. With an API key, `projects.list` returns only the key's own project.

```python
from datetime import datetime, timedelta, timezone

projects = await client.projects.list("org_abc123")
project = await client.projects.get("proj_abc123")
await client.projects.create(organization_id="org_abc123", name="CI Tests")

orgs = await client.organizations.list()

response = await client.api_keys.create(
    project_id="proj_abc123",
    name="CI Pipeline",
    expires_at=datetime.now(timezone.utc) + timedelta(days=90),  # optional, at most 365 days
)
print(response.key)  # Full key, only shown once!
await client.api_keys.revoke("proj_abc123", "key_xyz789")
```

## Error Handling

```python
from receiverdotemail import (
    ReceiverError,
    ReceiverTimeoutError,
    RateLimitError,
    AuthenticationError,
    NotFoundError,
)

try:
    email = await client.emails.wait_for(recipient=inbox.address, timeout=30)
except ReceiverTimeoutError as e:
    print(e.since, e.waited_seconds)
except RateLimitError as e:
    print(f"Rate limited. Retry at: {e.reset_at}")
except AuthenticationError:
    print("Invalid API key")
except NotFoundError:
    print("Not found")
except ReceiverError as e:
    print(e.message, e.status_code, e.code)
```

All errors derive from `ReceiverError`. `ReceiverTimeoutError` has `status_code == 408`
and `code == "WAIT_TIMEOUT"`.

With a dashboard session, a project or organization you aren't a member of raises
`NotFoundError` (`404`), the same as one that doesn't exist. An API key used on any project
other than its own, existing or not, gets `403`. Plan limits (projects, webhooks per project,
members, free organizations) answer `403` with `code == "LIMIT_REACHED"`.

## Pytest Integration

Async tests and fixtures need [pytest-asyncio](https://pypi.org/project/pytest-asyncio/)
with `asyncio_mode = "auto"` (in `pyproject.toml` under `[tool.pytest.ini_options]`).

```python
import pytest
from receiverdotemail import ReceiverClient

@pytest.fixture
async def receiver():
    async with ReceiverClient() as client:  # RECEIVER_API_KEY from the environment
        yield client

async def test_signup_email(receiver):
    inbox = await receiver.inboxes.create(prefix="signup")
    await my_app.signup(inbox.address)

    email = await receiver.emails.wait_for(
        recipient=inbox.address,
        subject="Confirm your email",
        since=inbox.created_at,
        timeout=60,
    )
    assert any("confirm" in link for link in email.links)
```

## Upgrading from 1.x

`wait_for` raises `ReceiverTimeoutError`
instead of returning `None`, `wait_for_otp` raises instead of returning `None`, and
`received_after` on waits is now `since` (the old name still works).

## Development

```bash
pip install -e ".[dev]"
pytest
mypy receiverdotemail
```

Or from the repo root: `./scripts/test.sh python-sdk`.

## License

MIT

## Support

- **Documentation**: https://www.receiver.email/docs/sdks/python
- **FAQ**: https://www.receiver.email/docs/faq
- **Email**: contact@receiver.email
