dinasend-sdk
Official Python SDK for DinaSend — 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
- Repository: dinasend/dinasend-sdk-python
- Issues: github.com/dinasend/dinasend-sdk-python/issues
- Changelog: CHANGELOG.md
Requirements
- Python 3.7+
- A DinaSend API key (
dina_test_…for testing,dina_live_…for production).
Install
pip install dinasend-sdk
The PyPI distribution name is dinasend-sdk. Import the library as dinasend.
Quickstart
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.
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:
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 for templates, attachments, scheduling, and queue recovery.
Retry-safe sends
Pass a stable key to prevent a retry from creating another email:
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.
Sending HTML and text
You must provide at least one of html or text. Provide both for the widest client support.
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.
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.
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
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
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:
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
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
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.
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; seeerror.rate_limit["retry_after"].
Codes raised by the SDK itself, always with status 0 unless noted:
missing_api_key— no key was passed andDINASEND_API_KEYis not set.invalid_input— the request was rejected before being sent, for example a missinghtmlortext.network_error— the request could not reach DinaSend. The underlying exception is onerror.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.
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:
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:
# reads DINASEND_API_KEY automatically
dina = DinaSend()
Timeout and custom HTTP client
Requests time out after 30 seconds by default.
dina = DinaSend(api_key, timeout=10.0)
To control certificates, connection limits, or to mock HTTP in tests, pass your own httpx client. You own its lifecycle.
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 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.
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 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:
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 for syntax, limits, previewing, and error codes.
Typing
The package ships type hints (py.typed). Response shapes are exported from dinasend.types as TypedDicts, 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 to get started.
License
This SDK is proprietary (UNLICENSED). All rights reserved by DinaSend.
Metadata
Release files for dinasend-sdk 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 |
|---|---|---|---|---|
| dinasend_sdk-0.1.0.tar.gz | 19.0 kB | With provenance | Details for dinasend_sdk-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dinasend_sdk-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for dinasend_sdk-0.1.0-py3-none-any.whl |
Total release size: 35.2 kB
Release files / dinasend_sdk-0.1.0.tar.gz
| Download URL | dinasend_sdk-0.1.0.tar.gz |
|---|---|
| Size | 19.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
034d7595f7d67eb4c874fadd285e4821831f55c54723179bb2f1e496e5143f7a
|
|
BLAKE2b-256 checksum How to use checksums |
045e1e8773cd4ba8ebde9e934db0ce4d4a47b248e76688a547ee2da0912531d2
|
| 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 5, 2026.
Transparency logRelease files / dinasend_sdk-0.1.0-py3-none-any.whl
| Download URL | dinasend_sdk-0.1.0-py3-none-any.whl |
|---|---|
| Size | 16.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
38d95f6b59dcc2cbd494c9cf9689d5b9a149edb04299b346786f7176d0986e7e
|
|
BLAKE2b-256 checksum How to use checksums |
05b89f14eaa9931f5a55ab8cc522dd39af5b8be303394cd2f2ac1b2149022c60
|
| 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 5, 2026.
Transparency logSecurity for dinasend-sdk 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 dinasend_sdk-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 5, 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.