Metadata-Version: 2.5
Name: mailblaze-transactional
Version: 0.1.0
Summary: Official Python client for the Mail Blaze transactional email API
Project-URL: Homepage, https://www.mailblaze.com
Project-URL: Documentation, https://github.com/mailblaze/mailblaze-transactional-python-sdk#readme
Project-URL: Issues, https://github.com/mailblaze/mailblaze-transactional-python-sdk/issues
Project-URL: Changelog, https://github.com/mailblaze/mailblaze-transactional-python-sdk/blob/master/CHANGELOG.md
Project-URL: Source, https://github.com/mailblaze/mailblaze-transactional-python-sdk
Author-email: Mail Blaze <support@mailblaze.com>
License-Expression: MIT
License-File: LICENSE
Keywords: api,email,mailblaze,sdk,transactional
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Communications :: Email
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# Mail Blaze transactional email for Python

`mailblaze-transactional` is the official Python client for the Mail Blaze transactional email API. You pass strings, bytes and files. The client sends the JSON the API expects.

- Python 3.11 or newer. No runtime dependencies.
- Fully typed (`py.typed`).
- Invalid input is rejected before any request is made.

## Install

```bash
pip install mailblaze-transactional
```

## Send an email

```python
import os

from mailblaze_transactional import Client, Email

with Client(os.environ["MAILBLAZE_API_KEY"]) as client:
    result = client.emails.send(
        Email()
        .to("jane@example.com", "Jane Doe")
        .from_("billing@example.com", "Acme")
        .subject("Your receipt")
        .html("<p>Thanks for your order.</p>")
        .text("Thanks for your order.")
    )

print(result.email_uid)
```

A successful send means the API accepted and queued the email, not that it was delivered. `result.email_uid` identifies it for `get()` and `attachments()`.

`to()`, `from_()` (with an underscore, because `from` is a Python keyword) and `subject()` are required. Exactly one of `html()` and `template_id()` is required. `text()` is optional and only valid with `html()`. `html()` and `text()` take `str`, or `bytes` encoded as UTF-8. The client base64-encodes them.

`from_()` must use an address on a domain you have verified in Mail Blaze. An unverified domain raises `DomainNotVerifiedError` (`150.010`).

### The builder is immutable

Each `Email` method returns a new `Email` and leaves the original unchanged, so a base email can be shared:

```python
base = Email().from_("billing@example.com", "Acme").subject("Your receipt")
for_jane = base.to("jane@example.com", "Jane Doe").html("<p>Hi Jane</p>")
for_john = base.to("john@example.com", "John Doe").html("<p>Hi John</p>")
```

Always use the returned value. A call whose result is discarded has no effect:

```python
for_jane = for_jane.cc("ops@example.com")  # not just for_jane.cc(...)
```

### Input checks

The builder raises `ValidationError` as soon as a method is called with invalid input, before any request:

- A subject, display name, category or template id is empty, or contains a line break, a control character (including tab), a bidirectional override or an invisible character such as U+200B. Direction marks used in Hebrew and Arabic text (U+200E, U+200F, U+061C) and zero-width joiners (U+200C, U+200D) are allowed. Leading and trailing spaces are trimmed. Subject length is not limited.
- An email address is not a single valid address. Only one address per value is accepted, and commas, semicolons and angle brackets are rejected. A quoted local part such as `"jane"@example.com` is accepted. The local part must be ASCII. Write a non-ASCII domain in punycode, for example `jane@xn--exmple-cua.example`.
- A merge tag name does not match `[A-Z0-9_]`, or a merge tag value contains a line break or another control character, including tab.
- Text cannot be encoded as UTF-8, for example a string with a lone surrogate.
- An attachment filename includes a path (`/` or `\`), a line break, a control character or a hidden or formatting character (including direction marks), is empty, or is longer than 255 UTF-8 bytes.

## Client options

```python
import os

from mailblaze_transactional import Client

client = Client(
    os.environ["MAILBLAZE_API_KEY"],
    base_url="https://control.mailblaze.com/api",
    timeout=10.0,
    get_retry_limit=2,
    retry_delay_ms=200,
    allow_http=False,
    ssl_context=None,
    transport=None,
)
```

| Option | Default | Notes |
| --- | --- | --- |
| `api_key` | required | Your Mail Blaze public API key. It is sent as the raw `Authorization` header, never in the URL. The client does not read environment variables. |
| `base_url` | `https://control.mailblaze.com/api` | Must be `https://`. Private, link-local and reserved IP addresses are rejected. |
| `timeout` | `10.0` | Seconds allowed for the whole request, up to `120`. Raise it for large attachments. |
| `get_retry_limit` | `2` | How many times a GET is retried (0–5). A send is never retried. |
| `retry_delay_ms` | `200` | Delay before each GET retry, multiplied by the attempt number (0–5000). |
| `allow_http` | `False` | Allows `http://` for a local development host: `localhost`, `127.0.0.1`, `[::1]`, `host.docker.internal` or a `.local` name. Public hosts always use HTTPS. |
| `ssl_context` | `None` | An `ssl.SSLContext` for the built-in transport, for example with a custom CA bundle. It must verify certificates and host names. There is no option to turn verification off. |
| `transport` | `None` | A custom transport. See [Custom transports](#custom-transports). |

An invalid option raises `ConfigurationError`, a subclass of `ValueError`, when the client is created.

The client reuses connections. Use it as a context manager, or call `client.close()`, to release them. One client can be shared between threads.

## Send a template

```python
result = client.emails.send(
    Email()
    .to("jane@example.com", "Jane Doe")
    .from_("billing@example.com", "Acme")
    .subject("Your order")
    .template_id("ab123456-1234-1234-1234-123456789abc")
    .merge_tags({"NAME": "Jane", "ORDER_ID": 1001})
)
```

`template_id()` cannot be combined with `html()` or `text()`. `merge_tags()` adds to the tags already set. Names must match `[A-Z0-9_]`. `MAILBLAZE_PREHEADER` sets the preheader. A template that uses a tag you did not pass raises `ValidationError` (`150.014`), and an unknown template raises `NotFoundError` (`150.013`).

Values can be `str`, `int`, `float`, `bool` (sent as `"1"` or `"0"`) or `None` (sent as an empty string). A template can place a merge tag in a single-line field such as the subject, so string values must not contain line breaks, tabs or other control characters. Unicode text, spaces and empty values are allowed and are sent without trimming. Put line breaks for the body in the template, or pass HTML such as `<br>` in the value.

## Attachments, copies and scheduling

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

from mailblaze_transactional import Attachment

email = (
    Email()
    .to("jane@example.com", "Jane Doe")
    .from_("billing@example.com", "Acme")
    .subject("Invoice")
    .html("<p>Invoice attached.</p>")
    .reply_to("accounts@example.com", "Accounts")
    .cc("manager@example.com")
    .bcc("archive@example.com")
    .category("invoices")
    .send_at(datetime.now(timezone.utc) + timedelta(hours=1))
    .attach(Attachment.from_path("/tmp/invoice.pdf"))
    .attach(Attachment.from_bytes("notes.txt", b"Thanks!"))
)
```

- `Attachment.from_path()` reads a local file and uses its base name. `Attachment.from_bytes(name, data)` takes the filename and the bytes. An attachment can be up to 10 MiB of base64, about 7.5 MiB of file bytes. A larger file raises `ValidationError` (`150.005`) before the request, and `from_path()` checks the size before reading the file. The API detects each attachment's content type from its bytes. Attachments work with HTML and template emails.
- `cc()`, `bcc()` and `attach()` add to the values already set. Several Cc or Bcc addresses are sent as one comma-separated string.
- Bcc recipients receive the email, and their addresses are not shown to the other recipients.
- `send_at()` takes a timezone-aware `datetime`. A naive `datetime` is rejected, so a time is never shifted by the server's timezone. It is sent as `2026-11-17T14:57:09+08:00`, with whole seconds and the UTC offset. The API holds the email until then. Omit `send_at()`, or pass a time in the past, to send immediately.

## List, fetch and attachments

```python
page = client.emails.list(page=1, per_page=10)
for summary in page.records:
    print(summary.email_uid, summary.status)

record = client.emails.get(result.email_uid)
print(record.subject, record.plain_text)

for file in client.emails.attachments(result.email_uid):
    data = file.content()  # bytes
```

- `list()` returns an `EmailPage` with `records`, `count`, `total_pages`, `current_page`, `next_page` and `prev_page`. `per_page` is clamped to 10–50, the range the API returns. `page` must be at least 1. A page with no emails is a success with empty `records`, so check `records` rather than `code`.
- `get()` returns an `EmailRecord` that includes `body` and `plain_text`. When no `text()` was sent, the API generates the plain text from the HTML.
- `attachments()` returns a list of `StoredAttachment` (`name` and the base64 `data`, with `content()` to decode it), or an empty list. A zero-byte file has empty `data`.
- `EmailRecord.send_at` is the raw API value, such as `2026-11-16 2:36:59 PM`. `send_at_datetime()` parses it into an aware `datetime`, or returns `None` when it does not recognise the format. The API value has no UTC offset and is read as UTC unless you pass another `tzinfo`, for example `record.send_at_datetime(ZoneInfo("Africa/Johannesburg"))`.

All responses are frozen dataclasses. Ids such as `email_uid` are opaque strings.

## Errors and retries

Every error is a `MailBlazeError` with `http_status`, `error_code` (only an `NNN.NNN` code, or `None`) and `error_message` (the API's text with the API key removed, at most 500 bytes).

| Exception | When |
| --- | --- |
| `AuthenticationError` | `150.001` (sending is turned off for the account), HTTP 401/403 without a more specific code, or HTTP 400 `Invalid API key` |
| `QuotaError` | `150.015`, not enough credits |
| `DomainNotVerifiedError` | `150.010`, the from domain is not verified |
| `ValidationError` | Input rejected by the builder, `100.001`, `150.002`–`150.006`, `150.011`, `150.012`, `150.014`, or another HTTP 400/422 |
| `NotFoundError` | HTTP 404, `150.009` or `150.013` |
| `SendFailedError` | `150.007` or `150.016` |
| `ApiError` | `150.008`, any other HTTP 4xx/5xx (including 429), a redirect, or an unexpected response |
| `TransportError` | The request did not complete: timeout, DNS, TLS or connection failure, or a body that could not be read |
| `UnconfirmedSendError` | A send returned HTTP 2xx but its body could not be read. The email may already have been accepted |
| `ConfigurationError` | The client was created with an invalid option. It subclasses `ValueError`, so `except MailBlazeError` does not catch it |

```python
from mailblaze_transactional import MailBlazeError, TransportError, UnconfirmedSendError

try:
    result = client.emails.send(email)
except UnconfirmedSendError:
    ...  # may have been accepted: check client.emails.list() before sending again
except TransportError as error:
    print(error.reason)  # "timeout", "dns", "tls", "connect", "client", "response" or "unknown"
except MailBlazeError as error:
    print(error.http_status, error.error_code, error.error_message)
```

`UnconfirmedSendError` subclasses `TransportError`, so catch it first when you handle it differently.

**Sends are never retried**, including after a timeout, HTTP 429 or a 5xx response, because the API has no idempotency key and a retry could send the same email twice. After a `TransportError` or `UnconfirmedSendError` on send, check `list()` or `get()` before sending that email again.

A GET is tried once, then retried up to `get_retry_limit` times after a connection failure, HTTP 500, 502, 503 or 504, or a body that could not be read, was empty or was truncated. Other statuses, including 401, 404 and 429, and authentication, quota and validation errors, are not retried.

## Security

- The API key is sent only in the `Authorization` header. It does not appear in `repr()` of the client, in exception messages or in log records, and the client cannot be pickled.
- When the HTTP layer fails, the exception's `__cause__` is a stand-in that keeps the original class name and message with the API key removed. The original exception and its traceback are not attached. The SDK does not keep the plain key in the local variables of the frames an exception passes through, so tools that capture traceback locals do not record it.
- TLS certificates are always verified. Redirects are never followed, so the key cannot be sent to another host. A response body larger than 16 MiB is rejected.
- The client logs to the `mailblaze_transactional` logger (with a `NullHandler` by default): the method, path, attempt, status and failure reason. It never logs the API key, headers or message content.

To report a vulnerability, see [SECURITY.md](https://github.com/mailblaze/mailblaze-transactional-python-sdk/blob/master/SECURITY.md).

## Custom transports

The built-in transport uses only the standard library and does not read proxy environment variables. To route requests through your own HTTP stack, pass an object with `send(request) -> HttpResponse` and `close()` methods:

```python
import os

from mailblaze_transactional import Client, HttpRequest, HttpResponse


class MyTransport:
    def send(self, request: HttpRequest) -> HttpResponse:
        # request.method, request.url, request.all_headers(), request.body, request.timeout
        ...

    def close(self) -> None: ...


client = Client(os.environ["MAILBLAZE_API_KEY"], transport=MyTransport())
```

A custom transport must send the headers from `request.all_headers()`, which adds the `Authorization` header (`request.headers` leaves it out and `request.api_key` holds the key with a redacted repr). It must verify TLS certificates, must not follow redirects, should apply `request.timeout`, and must return the whole body. When it receives a status but cannot read the body, it should raise `TransportError(..., reason="response", http_status=status)`. Any other exception is wrapped in a `TransportError`. The same transport is useful in tests.

## asyncio

The client is synchronous. In asyncio code, run a call in a worker thread:

```python
import asyncio

result = await asyncio.to_thread(client.emails.send, email)
```

## SMTP

This package does not speak SMTP. Mail Blaze SMTP is `smtp.mailblaze.net`, port `587`, with STARTTLS, authenticated with your API key. The SMTP username and login method are to be confirmed; check with Mail Blaze support before relying on them.

## Not included

Batch send, webhooks, idempotency keys and Django, Flask or FastAPI email backends are not part of this package.

## Versioning

This package follows [Semantic Versioning](https://semver.org/). Before 1.0, a minor release may include breaking changes, listed in [CHANGELOG.md](https://github.com/mailblaze/mailblaze-transactional-python-sdk/blob/master/CHANGELOG.md). Support for a Python version may be dropped after it reaches end of life. Supported package versions are listed in [SECURITY.md](https://github.com/mailblaze/mailblaze-transactional-python-sdk/blob/master/SECURITY.md).

## License

MIT. See [LICENSE](https://github.com/mailblaze/mailblaze-transactional-python-sdk/blob/master/LICENSE).
