Metadata-Version: 2.5
Name: dinasend-sdk
Version: 0.1.0
Summary: Official DinaSend Python SDK for transactional email.
Project-URL: Homepage, https://dinasend.com
Project-URL: Documentation, https://docs.dinasend.com
Project-URL: Repository, https://github.com/dinasend/dinasend-sdk-python
Project-URL: Issues, https://github.com/dinasend/dinasend-sdk-python/issues
Project-URL: Changelog, https://github.com/dinasend/dinasend-sdk-python/blob/main/CHANGELOG.md
Author: DinaSend
Maintainer-email: Laurent <stlaurentcodes@gmail.com>
License: UNLICENSED
Keywords: dinasend,email,sdk,transactional,webhooks
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
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: Programming Language :: Python :: 3.15
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.7
Requires-Dist: httpx<1,>=0.23
Requires-Dist: typing-extensions>=4.0; python_version < '3.8'
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: mypy>=1.4; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Description-Content-Type: text/markdown

# dinasend-sdk

Official Python SDK for [DinaSend](https://dinasend.com) — transactional email, sent fast.

DinaSend is a **transactional-only** email API. There are no campaigns, lists, or marketing flows. Use this SDK when you need to send receipts, password resets, login codes, notifications, and other one-to-one mail from your app.

- Documentation: [docs.dinasend.com](https://docs.dinasend.com)
- Repository: [dinasend/dinasend-sdk-python](https://github.com/dinasend/dinasend-sdk-python)
- Issues: [github.com/dinasend/dinasend-sdk-python/issues](https://github.com/dinasend/dinasend-sdk-python/issues)
- Changelog: [CHANGELOG.md](CHANGELOG.md)

## Requirements

- Python 3.7+
- A DinaSend API key (`dina_test_…` for testing, `dina_live_…` for production).

## Install

```bash
pip install dinasend-sdk
```

The PyPI distribution name is `dinasend-sdk`. Import the library as `dinasend`.

## Quickstart

```python
import os

from dinasend import DinaSend

dina = DinaSend(os.environ["DINASEND_API_KEY"])

email = dina.emails.send(
    from_="Acme <hello@example.com>",
    to="customer@example.com",
    subject="Welcome to Acme",
    html="<p>Thanks for signing up.</p>",
)

print(email["id"], email["status"])  # "em_…", "queued"
```

`from` is a reserved word in Python, so the sender argument is `from_`. Responses are plain dictionaries with the same keys the API returns.

## Async

`AsyncDinaSend` has the same methods as `DinaSend`, as coroutines.

```python
import asyncio

from dinasend import AsyncDinaSend


async def main() -> None:
    async with AsyncDinaSend() as dina:
        email = await dina.emails.send(
            from_="Acme <hello@example.com>",
            to="customer@example.com",
            subject="Welcome to Acme",
            text="Thanks for signing up.",
        )
        print(email["id"])


asyncio.run(main())
```

Both clients own an HTTP connection pool. Use them as context managers, or call `close()` / `await aclose()` when you are done. Create one client and reuse it rather than creating one per request.

## Batch sending

Batch sending requires Starter, Growth, or a paid custom plan. Free workspaces receive `403 BATCH_SEND_REQUIRES_PAID_PLAN`; individual sending and idempotency remain available.

Send 1–100 emails in one request and inspect the result for each input index:

```python
batch = dina.emails.send_batch(
    [
        {"from_": "Acme <hello@example.com>", "to": "first@example.com", "subject": "Hello", "text": "Welcome."},
        {"from_": "Acme <hello@example.com>", "to": "second@example.com", "subject": "Hello", "text": "Welcome."},
    ],
    idempotency_key="welcome:job_1042",
)

for result in batch["results"]:
    if result["success"]:
        print(result["index"], result["id"], result["status"])
    else:
        print(result["index"], result["error"]["code"], result["error"]["message"])
```

Each email in a batch is a dictionary with the same fields as `send`. HTTP 200 can include rejected entries. Individual validation occurs on the API. Daily or monthly quota exhaustion rejects the whole batch without creating emails or reserving usage. The optional key protects the entire ordered batch for 24 hours. Retrying corrected rejections uses a new key and only those rejected entries. See [Batch sending](https://docs.dinasend.com/batch-sending) for templates, attachments, scheduling, and queue recovery.

## Retry-safe sends

Pass a stable key to prevent a retry from creating another email:

```python
dina.emails.send(
    from_="Acme <hello@example.com>",
    to="customer@example.com",
    subject="Your receipt",
    text="Thanks for your purchase.",
    idempotency_key="receipt:order_1042",
)
```

Retain the same key and payload for retries of one intended send. Keys last 24 hours from acceptance within a workspace, project, and live/test environment. A changed payload with the same key returns `409 idempotency_key_conflict`. Keys may contain 1–256 letters, numbers, periods, underscores, colons, or hyphens. The SDK does not automatically retry or generate keys. See [Idempotency](https://docs.dinasend.com/idempotency).

## Sending HTML and text

You must provide at least one of `html` or `text`. Provide both for the widest client support.

```python
dina.emails.send(
    from_="Acme <hello@example.com>",
    to="customer@example.com",
    subject="Your receipt",
    html="<h1>Receipt</h1><p>Total: $42.00</p>",
    text="Receipt\nTotal: $42.00",
)
```

## Multiple recipients, cc, and bcc

`to`, `cc`, and `bcc` accept either a single address or a list. Strings are normalized to lists before being sent to the API.

```python
dina.emails.send(
    from_="Acme <hello@example.com>",
    to=["a@example.com", "b@example.com"],
    cc=["ops@example.com"],
    bcc="audit@example.com",
    reply_to="support@example.com",
    subject="Receipt",
    text="Thanks for your purchase.",
)
```

## Scheduled send

Pass `send_at` as a `datetime` or an ISO-8601 string. The SDK forwards it to the API as `send_at`.

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

dina.emails.send(
    from_="Acme <hello@example.com>",
    to="customer@example.com",
    subject="See you tomorrow",
    text="Reminder for your appointment.",
    send_at=datetime.now(timezone.utc) + timedelta(minutes=1),
)
```

A `datetime` without a timezone is treated as UTC. The response `status` will be `"scheduled"` instead of `"queued"`.

## Retrieving an email

```python
email = dina.emails.get("em_…")
print(email["status"], email["sent_at"])
```

`status` is one of `"queued"`, `"scheduled"`, `"processing"`, `"sent"`, `"delivered"`, `"bounced"`, `"complained"`, `"failed"`, or `"cancelled"`. Provider details (`provider`, `provider_message_id`) and lifecycle timestamps (`queued_at`, `processing_at`, `sent_at`, `failed_at`, `cancelled_at`) are populated as the email moves through delivery.

## Listing emails

```python
result = dina.emails.list(page=1, page_size=25)

for email in result["emails"]:
    print(email["id"], email["status"], email["subject"])

pagination = result["pagination"]
print(pagination["total"], "emails across", pagination["totalPages"], "pages")
```

Both `page` and `page_size` are optional; defaults are page 1 with 10 per page.

You can also filter the list:

```python
result = dina.emails.list(
    status=["bounced", "failed"],  # a single status or a list
    q="receipt",                   # search text
    environment="live",            # "live" or "test"
    api_key_id="key_…",
    from_="2026-10-01",            # YYYY-MM-DD (UTC day), ISO timestamp, or datetime
    to=datetime.now(timezone.utc), # inclusive
)
```

## Failed email summary

```python
summary = dina.emails.failure_summary()
print(summary["retryable"], summary["permanent"])
```

`retryable` counts failed emails that can be retried (for example, transient provider errors). `permanent` counts failures that won't succeed if retried.

## Cancelling a scheduled email

```python
cancelled = dina.emails.cancel("em_…")
print(cancelled["status"])  # "cancelled"
```

Only emails in `"scheduled"` status can be cancelled. Cancelling an email that is already `"sent"`, `"failed"`, or `"queued"` raises a `DinaSendError` with status `409`.

## Error handling

Every error raised for a failed request or invalid input is a `DinaSendError`.

```python
from dinasend import DinaSendError

try:
    dina.emails.send(...)
except DinaSendError as error:
    print(error.status)      # HTTP status (0 for client-side and network errors)
    print(error.code)        # "quota_exceeded", "rate_limited", …
    print(error.details)
    print(error.rate_limit)  # {"limit": …, "remaining": …, "reset": …, "retry_after": …}
    raise
```

Common error codes returned by the API:

- `quota_exceeded` — monthly quota reached.
- `daily_quota_exceeded` — daily quota reached.
- `domain_limit_exceeded` — sender domain limit reached.
- `rate_limited` — too many requests; see `error.rate_limit["retry_after"]`.

Codes raised by the SDK itself, always with status `0` unless noted:

- `missing_api_key` — no key was passed and `DINASEND_API_KEY` is not set.
- `invalid_input` — the request was rejected before being sent, for example a missing `html` or `text`.
- `network_error` — the request could not reach DinaSend. The underlying exception is on `error.cause`.
- `invalid_response` — DinaSend answered 2xx with a body that is not a JSON object. The status is the HTTP status.

The SDK does not implement retry logic. Wrap calls with the strategy that fits your app.

## Verifying webhooks

DinaSend signs every webhook it sends to your endpoint. Verify the signature before trusting the payload so you can reject forged or replayed requests.

```python
import os

from dinasend import DinaSendWebhookError, webhooks

# example with Flask
@app.post("/webhooks/dinasend")
def dinasend_webhook():
    try:
        event = webhooks.construct_event(
            payload=request.get_data(),
            signature=request.headers.get("dinasend-signature"),
            secret=os.environ["DINASEND_WEBHOOK_SECRET"],
        )
    except DinaSendWebhookError as error:
        return error.code, 400

    if event["type"] in ("email.sent", "email.failed"):
        ...  # event["data"] holds the payload

    return "", 200
```

`payload` must be the **raw request body** — the exact bytes (`bytes` or `str`) DinaSend sent. The signature is computed over those bytes, so a re-serialized object (`json.dumps(parsed_body)`) will not match. Read the raw body before any JSON parsing touches it (`request.get_data()` in Flask, `await request.body()` in FastAPI and Starlette, `request.body` in Django).

`construct_event` verifies the HMAC-SHA256 signature in constant time, enforces a timestamp tolerance to block replays, and returns the parsed event as a dictionary (`id`, `type`, `data`, `created_at`).

### Timestamp tolerance

The default tolerance is 5 minutes. Override it with `tolerance_seconds`:

```python
webhooks.construct_event(
    payload=raw_body,
    signature=signature,
    secret=secret,
    tolerance_seconds=600,
)
```

### Webhook error codes

Verification failures raise a `DinaSendWebhookError` with a `code`:

- `no_signature` — the signature argument was missing or empty.
- `no_secret` — the signing secret was missing or empty.
- `invalid_signature_format` — the signature header could not be parsed.
- `timestamp_too_old` — the timestamp is outside the allowed tolerance.
- `signature_mismatch` — the signature did not match the payload.
- `invalid_json` — the verified payload was not valid JSON.

## Test vs live keys

DinaSend issues two key flavours:

- `dina_test_…` — does not require a verified sender domain. Use these in development and integration tests.
- `dina_live_…` — production traffic; the sender domain must be verified.

The SDK behaves identically for both — pick the right key per environment.

## Configuration

The only thing you need is an API key. Pass it to the constructor, or set `DINASEND_API_KEY` in your environment:

```python
# reads DINASEND_API_KEY automatically
dina = DinaSend()
```

### Timeout and custom HTTP client

Requests time out after 30 seconds by default.

```python
dina = DinaSend(api_key, timeout=10.0)
```

To control certificates, connection limits, or to mock HTTP in tests, pass your own [`httpx`](https://www.python-httpx.org) client. You own its lifecycle.

```python
import httpx

dina = DinaSend(api_key, http_client=httpx.Client(verify="/etc/ssl/internal-ca.pem"))
```

Use `httpx.AsyncClient` with `AsyncDinaSend`.

## Attachments

See the [attachments guide](https://docs.dinasend.com/attachments) for REST, SDK, and dashboard usage.

Attachment limits depend on your organization's current plan:

| Plan | Files per email | Total decoded size per email |
| --- | --- | --- |
| Free | 3 | 1 MiB |
| Starter | 5 | 5 MiB |
| Growth | 10 | 10 MiB |

These are the default allowances; administrators can adjust them, up to the platform ceiling of **10 files and 10 MiB** (10,485,760 bytes). Either limit set to zero disables attachments. Custom/manual workspaces without a catalogue plan use the platform allowance.

Limits apply when a new send is accepted. Scheduled emails and retries that were already accepted retain their attachments after a downgrade. Exceeding your plan's allowance returns `403` with code `attachment_limit_exceeded` and the current plan limits in `details`.

Each attachment requires a `filename` and a non-empty base64 `content` string. You can optionally provide `contentType`; otherwise the provider infers it from the filename extension.

```python
import base64
from pathlib import Path

invoice = Path("invoice.pdf").read_bytes()

dina.emails.send(
    from_="Acme <receipts@yourdomain.com>",
    to="customer@example.com",
    subject="Your invoice",
    text="Your invoice is attached.",
    attachments=[
        {
            "filename": "invoice.pdf",
            "content": base64.b64encode(invoice).decode("ascii"),
            "contentType": "application/pdf",
        }
    ],
)
```

Send plain base64, without a data URL prefix or whitespace. Empty files, path separators, control characters, and [SES unsupported file extensions](https://docs.aws.amazon.com/ses/latest/dg/attachments.html#attachments-unsupported) are rejected. This release supports regular attachments; inline images and remote file URLs are not supported.

Attachments are preserved for scheduled delivery and retries. Retrieved email details include attachment IDs, filenames, content types, and decoded sizes; file content is not returned in activity lists or details.

The entire JSON send request must fit within **16 MiB**, including base64 content. **Test messages retain the 256 KiB sandbox request limit**, so use small attachments when testing. Test messages are captured in Sandbox and are not delivered to inboxes.

## Send with a template

Saved project templates are available on paid plans:

```python
dina.emails.send(
    template_id="tpl_…",
    to="customer@example.com",
    variables={"customerName": "Sam", "orderNumber": 1042},
)
```

Create templates in the dashboard and copy the template ID from the editor. Use `{{customerName}}` placeholders in the sender, subject, HTML, or plain text. The API key must belong to the template's project. Values may be strings, finite numbers, or booleans. All referenced values are required, and HTML replacements are escaped.

The template supplies the sender, subject, and bodies. You may override `from_` and `subject`; provide `from_` if the template has no sender. Do not combine `template_id` with `html` or `text`. Attachments and `send_at` are supported. Accepted messages store rendered content, so editing or deleting the template later does not change scheduled sends or retries.

See the [email templates guide](https://docs.dinasend.com/templates) for syntax, limits, previewing, and error codes.

## Typing

The package ships type hints (`py.typed`). Response shapes are exported from `dinasend.types` as `TypedDict`s, for example `dinasend.types.Email` and `dinasend.types.SendEmailResponse`.

## Part of DinaSend

DinaSend is a hosted transactional email service. This SDK connects your applications to the DinaSend API. Visit [dinasend.com](https://dinasend.com) to get started.

## License

This SDK is proprietary (`UNLICENSED`). All rights reserved by DinaSend.
