> ## Documentation Index
> Fetch the complete documentation index at: https://docs.paubox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK email client

> Full reference for the Paubox Python SDK email client: composing messages, sending email, tracking delivery, and error handling.

## Instantiation

```python theme={null}
from paubox import PauboxApiClient

# Read credentials from environment variables
client = PauboxApiClient()

# Or pass credentials directly
client = PauboxApiClient(api_key='YOUR_API_KEY')
```

See [Authentication](https://docs.paubox.com/python-sdk/authentication.md) for both approaches.

## Composing a message

Use the `Mail` helper to compose messages. It handles formatting and automatically base64-encodes HTML content before sending.

```python theme={null}
from paubox.helpers.mail import Mail

mail = Mail(
    from_      = 'sender@yourdomain.com',    # required
    subject    = 'Your results are ready',   # required
    recipients = ['alice@example.com'],       # required; list of email strings
    content    = {                            # required; at least one key
        'text/plain': 'Plain text body.',
        'text/html':  '<p>HTML body.</p>'    # auto base64-encoded
    },
    optional_headers = {                      # optional
        'reply_to':               'support@yourdomain.com',
        'cc':                     ['manager@example.com'],
        'bcc':                    ['audit@example.com'],    # list of email strings
        'allowNonTLS':            False,
        'forceSecureNotification': False,
        'attachments':            [attachment]
    }
)
```

Call `mail.get()` to get the formatted dict ready for the API.

### Attachments

```python theme={null}
import base64

with open('report.pdf', 'rb') as f:
    encoded = base64.b64encode(f.read()).decode('utf-8')

attachment = {
    'fileName':    'report.pdf',
    'contentType': 'application/pdf',
    'content':     encoded
}
```

Pass attachments via the `optional_headers` dict:

```python theme={null}
optional_headers = {
    'attachments': [attachment]
}
```

## Send a message

```python theme={null}
response = client.send(mail.get())
print('Status:', response.status_code)
print('Tracking ID:', response.to_dict.get('sourceTrackingId'))
```

## Check delivery status

```python theme={null}
tracking_id = response.to_dict['sourceTrackingId']

disposition = client.get(tracking_id)
deliveries  = disposition.to_dict['data']['message']['message_deliveries']

for d in deliveries:
    print(d['recipient'], '→', d['status']['deliveryStatus'])
```

Common `deliveryStatus` values: `delivered`, `delivered via secure portal`, `soft bounced`, `hard bounced`, `processing`. Opens are reported separately in `openedStatus`.

## Scheduled send

Schedule a message for future delivery, check its status, reschedule, or cancel it.

### Schedule a message

```python theme={null}
from datetime import datetime, timedelta, timezone

scheduled_at = (datetime.now(timezone.utc) + timedelta(days=1)).isoformat()
response = client.schedule(mail.get(), scheduled_at)
print('Tracking ID:', response.to_dict.get('sourceTrackingId'))
print('Scheduled for:', response.to_dict.get('scheduledAt'))
```

`scheduled_at` must be an ISO 8601 UTC datetime string in the future and within 30 days.

### Get scheduled message status

```python theme={null}
status = client.get_scheduled(source_tracking_id)
data = status.to_dict
print('State:', data.get('state'))          # "pending", "processing", "sent", "failed", "cancelled"
print('Scheduled for:', data.get('scheduledAt'))
```

### Reschedule a message

```python theme={null}
new_time = (datetime.now(timezone.utc) + timedelta(days=2)).isoformat()
response = client.reschedule(source_tracking_id, new_time)
print('New time:', response.to_dict.get('scheduledAt'))
```

### Cancel a scheduled message

```python theme={null}
response = client.cancel_scheduled(source_tracking_id)
print('State:', response.to_dict.get('state'))  # "cancelled"
```

## The Response object

Every `PauboxApiClient` method returns a `Response` object:

| Property | Description |
| - | - |
| `.status_code` | HTTP status code |
| `.headers` | Response headers dict |
| `.text` | Raw response body as a string |
| `.content` | Raw response body as bytes |
| `.to_dict` | JSON-parsed response body, or `None` if the body is empty; raises `json.JSONDecodeError` if the body isn't JSON |

## Error handling

All client methods raise `requests.exceptions.HTTPError` on non-2xx responses. Before raising, the SDK prints the error response body to standard output. Wrap calls in a try/except block:

```python theme={null}
import requests

try:
    response = client.send(mail.get())
except requests.exceptions.HTTPError as e:
    print('API error:', e.response.status_code, e.response.text)
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.