Metadata-Version: 2.4
Name: mailgent-sdk
Version: 0.6.2
Summary: Official Python SDK for the Mailgent API — identity, mail, vault, calendar, and buyer x402 payments for AI agents
Author: Mailgent
License: MIT
Project-URL: Homepage, https://mailgent.dev
Project-URL: Documentation, https://docs.mailgent.dev
Project-URL: Repository, https://github.com/mailgent-dev/mailgent-python
Project-URL: Issues, https://github.com/mailgent-dev/mailgent-python/issues
Keywords: mailgent,ai,agent,email,mcp,did,vault,sdk,x402,usdc,payments
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: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: respx>=0.21; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Dynamic: license-file

# Mailgent Python SDK

The official Python SDK for the [Mailgent API](https://mailgent.dev) -- identity, mail, vault, calendar, and **Mailgent Pay** for AI agents.

[![PyPI version](https://img.shields.io/pypi/v/mailgent-sdk.svg)](https://pypi.org/project/mailgent-sdk/)
[![Python 3.9+](https://img.shields.io/pypi/pyversions/mailgent-sdk.svg)](https://pypi.org/project/mailgent-sdk/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

## Installation

```bash
pip install mailgent-sdk
```

> The distribution is `mailgent-sdk` on PyPI, but the import name is `mailgent`.

## Buyer payments (x402)

Pay any x402-protected URL from your project's wallet. Mailgent drives the
full handshake — discover the 402 challenge, enforce mandate caps, sign
EIP-3009, retry, and record — then returns a discriminated result.

```python
result = client.payments.pay(url="https://api.example.com")
if result["ok"]:
    print(result["txHash"], result["cost"]["amountUsdc"])
else:
    print(result["code"], result["hint"])
```

Spend policy lives at `client.payments.mandates`. Requires the
`payments:spend` scope on the API key. See the
[full payments guide](https://docs.mailgent.dev/payments).

### Webhook signature verification

Mailgent sends `X-Mailgent-Signature: sha256=<hex>` (HMAC-SHA256 of the raw
request body) along with `X-Mailgent-Event` / `X-Mailgent-Idempotency-Key`.
The signing secret is generated by Mailgent when you register an endpoint
in the Console and shown to you exactly once.

```python
import os
from fastapi import FastAPI, HTTPException, Request
from mailgent.webhook import verify_webhook

app = FastAPI()

@app.post("/webhooks/mailgent")
async def webhook(request: Request):
    raw = await request.body()
    ok = verify_webhook(
        raw,
        request.headers.get("x-mailgent-signature"),
        os.environ["MAILGENT_WEBHOOK_SECRET"],
    )
    if not ok:
        raise HTTPException(400, "invalid signature")
    # de-dupe on x-mailgent-idempotency-key, then handle the event.
    # Today the only event type is `payment.received`.
```

## Quick start

```python
from mailgent import Mailgent

client = Mailgent(api_key="loid-...")

me = client.identity.whoami()
print(me.email)

client.mail.send(
    to=["colleague@example.com"],
    subject="Hello from my agent",
    text="Sent via the Mailgent Python SDK.",
)
```

## Async usage

```python
from mailgent import AsyncMailgent

async with AsyncMailgent(api_key="loid-...") as client:
    me = await client.identity.whoami()
    await client.mail.send(
        to=["colleague@example.com"],
        subject="Hello",
        text="Sent asynchronously.",
    )
```

## Authentication

Pass your API key directly, or set the `MAILGENT_API_KEY` environment variable:

```python
# Explicit
client = Mailgent(api_key="loid-...")

# From environment
import os
os.environ["MAILGENT_API_KEY"] = "loid-..."
client = Mailgent()
```

Both `Mailgent` and `AsyncMailgent` support context managers for automatic resource cleanup:

```python
with Mailgent() as client:
    me = client.identity.whoami()
```

## Usage

### Identity

```python
me = client.identity.whoami()
print(me.email, me.display_name)
```

### Vault

The vault is password-manager-style encrypted secret storage (AES-256-GCM at rest). Use `client.vault.store()` for arbitrary types, or the typed helpers below.

```python
# Simple API key
client.vault.store_api_key("stripe", "sk_live_...")

# OAuth-style client credentials (client id + secret)
client.vault.store_api_key("twitter", {
    "clientId": "abc123",
    "secret": "def456",
})

# Credit card (encrypted at rest — this is a secret vault, not a payment processor)
client.vault.store_card("personal-visa", {
    "cardholder": "Jane Doe",
    "number": "4242 4242 4242 4242",
    "expMonth": "12",
    "expYear": "2029",
    "cvc": "123",
    "zip": "94103",
}, metadata={"brand": "Visa"})

# Shipping address
client.vault.store_shipping_address("home", {
    "name": "Autonomous Agent",
    "line1": "1 Demo Way",
    "city": "San Francisco",
    "state": "CA",
    "postcode": "94103",
    "country": "US",
})
```

Supported credential types: `LOGIN`, `API_KEY`, `OAUTH`, `TOTP`, `SSH_KEY`, `DATABASE`, `SMTP`, `AWS`, `CERTIFICATE`, `CARD`, `SHIPPING_ADDRESS`, `CUSTOM`.

### More resources

The SDK also exposes `client.mail`, `client.calendar`, `client.logs`, and `client.did`. See the full reference at **[docs.mailgent.dev](https://docs.mailgent.dev)** for request/response shapes, pagination, and end-to-end examples.

## Error handling

All API errors raise `MailgentApiError` with structured fields:

```python
from mailgent import MailgentApiError

try:
    client.mail.send(to=["a@b.com"], subject="Hi", text="Hello")
except MailgentApiError as e:
    print(e.status)   # HTTP status code
    print(e.code)     # Error code string
    print(e.message)  # Human-readable message
```

## Types

The SDK returns typed dataclasses, not raw dictionaries. API responses are automatically converted from camelCase to snake_case.

| Type | Description |
|------|-------------|
| `IdentityResponse` | Agent identity details |
| `MessageResponse` | Email message |
| `ThreadResponse` | Thread summary |
| `ThreadDetailResponse` | Thread with messages |
| `CredentialMetadata` | Vault credential metadata |
| `CredentialWithData` | Credential with decrypted data |
| `ActivityLog` | Single activity log entry |
| `LogsStats` | Aggregated log statistics |
| `TotpResponse` | Generated TOTP code |
| `DidDocument` | DID document |

> **Note:** The `from` field in message responses is exposed as `from_addrs` since `from` is a reserved keyword in Python.

## Requirements

- Python 3.9+
- [`httpx`](https://www.python-httpx.org/) (installed automatically)

## Links

- [Documentation](https://docs.mailgent.dev)
- [Console](https://console.mailgent.dev)
- [Website](https://mailgent.dev)
- [PyPI](https://pypi.org/project/mailgent-sdk/)

## License

MIT
