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
pip install mailblaze-transactional
Send an email
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:
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:
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.comis accepted. The local part must be ASCII. Write a non-ASCII domain in punycode, for examplejane@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
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. |
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
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
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 raisesValidationError(150.005) before the request, andfrom_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()andattach()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-awaredatetime. A naivedatetimeis rejected, so a time is never shifted by the server's timezone. It is sent as2026-11-17T14:57:09+08:00, with whole seconds and the UTC offset. The API holds the email until then. Omitsend_at(), or pass a time in the past, to send immediately.
List, fetch and attachments
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 anEmailPagewithrecords,count,total_pages,current_page,next_pageandprev_page.per_pageis clamped to 10–50, the range the API returns.pagemust be at least 1. A page with no emails is a success with emptyrecords, so checkrecordsrather thancode.get()returns anEmailRecordthat includesbodyandplain_text. When notext()was sent, the API generates the plain text from the HTML.attachments()returns a list ofStoredAttachment(nameand the base64data, withcontent()to decode it), or an empty list. A zero-byte file has emptydata.EmailRecord.send_atis the raw API value, such as2026-11-16 2:36:59 PM.send_at_datetime()parses it into an awaredatetime, or returnsNonewhen it does not recognise the format. The API value has no UTC offset and is read as UTC unless you pass anothertzinfo, for examplerecord.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 |
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
Authorizationheader. It does not appear inrepr()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_transactionallogger (with aNullHandlerby 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.
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:
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:
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. Before 1.0, a minor release may include breaking changes, listed in CHANGELOG.md. Support for a Python version may be dropped after it reaches end of life. Supported package versions are listed in SECURITY.md.
License
MIT. See LICENSE.
Metadata
Release files for mailblaze-transactional 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| mailblaze_transactional-0.1.0.tar.gz | 61.8 kB | With provenance | Details for mailblaze_transactional-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| mailblaze_transactional-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for mailblaze_transactional-0.1.0-py3-none-any.whl |
Total release size: 99.2 kB
Release files / mailblaze_transactional-0.1.0.tar.gz
| Download URL | mailblaze_transactional-0.1.0.tar.gz |
|---|---|
| Size | 61.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d189b27723aaefb0886de0e06d23a2681fc304152c09c015494d3a591e99dc0c
|
|
BLAKE2b-256 checksum How to use checksums |
4d6c69d378497611159c87364ad3f8dc97580efacf6b56647d65f5041fe807bc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / mailblaze_transactional-0.1.0-py3-none-any.whl
| Download URL | mailblaze_transactional-0.1.0-py3-none-any.whl |
|---|---|
| Size | 37.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
29bb43b6799a713d8e96a14d37f6b6f9778629341fb50302b00b5f025f28e8eb
|
|
BLAKE2b-256 checksum How to use checksums |
2af00b0bdd3bc84d8600b73173c5eb634a258944096a913d717a7fa0c940e841
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for mailblaze-transactional 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for mailblaze_transactional-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.