Metadata-Version: 2.4
Name: receiverdotemail
Version: 2.0.0
Summary: Official Python SDK for Receiver.email: programmable email inboxes for tests and AI agents, with OTP and link extraction
Author-email: "Receiver.email" <support@receiver.email>
License-Expression: MIT
Project-URL: Homepage, https://receiver.email
Project-URL: Documentation, https://receiver.email/docs/sdks/python
Project-URL: Repository, https://github.com/BUW91/mailingestion/tree/main/packages/python-sdk
Project-URL: Issues, https://github.com/BUW91/mailingestion/issues
Keywords: receiverdotemail,receiver.email,email,email-testing,email-api,inbound-email,otp,2fa,magic-link,testing,test-automation,e2e-testing,pytest,playwright,ai-agents,disposable-email
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.9
Description-Content-Type: text/markdown
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"

# receiverdotemail

Official Python SDK for [Receiver.email](https://receiver.email): programmable email inboxes for end-to-end tests, AI agents and scripts. Create a unique address per test, trigger your sign-up, login or password-reset email, and get the OTP code or magic link back with one call. Built for pytest, Playwright for Python and CI.

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

## 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`

## Installation

```bash
pip install receiverdotemail
```

## Quick Start

```python
import asyncio
from receiverdotemail import ReceiverClient

async def main():
    # Reads RECEIVER_API_KEY (and RECEIVER_API_URL, if set) from the environment
    async with ReceiverClient() as receiver:
        inbox = await receiver.inboxes.create(prefix="signup")
        await my_app.sign_up(inbox.address)

        otp = await receiver.emails.wait_for_otp(
            recipient=inbox.address,
            since=inbox.created_at,
            timeout=60,
        )
        print(otp.code)

asyncio.run(main())
```

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)
```

### Stream new emails

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

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)

await client.emails.delete("email_xyz789")

emails = await client.emails.find_by_subject("Password Reset")
```

### 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]
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)
```

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

```python
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")
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"`.

## Pytest Integration

```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

See [CHANGELOG.md](CHANGELOG.md). In short: `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://docs.receiver.email
- **Email**: support@receiver.email
- **Issues**: https://github.com/receiverdotemail/sdk-python/issues
