Skip to main content

unitpost

Official Unitpost SDK for Python. Send email and manage contacts, segments, campaigns, templates, domains, suppressions, and webhooks.

Install

pip install unitpost

Requires Python 3.8+.

Quick start

from unitpost import Unitpost

unitpost = Unitpost()  # reads UNITPOST_API_KEY (or pass Unitpost("up_..."))

result = unitpost.email.send({
    "from": "Acme <you@yourdomain.com>",  # bare address works too
    "to": "customer@example.com",
    "subject": "Hello",
    "html": "<p>It works!</p>",
})

if result.error:
    print(result.error.code, result.error.message)
else:
    print("sent", result.data["id"])

Every method returns a Result with .data and .error. An API-level failure populates .error (a UnitpostError) instead of raising.

Authentication

Pass the key to Unitpost(...), or set UNITPOST_API_KEY. Create a key at unitpost.com → Settings → API keys.

Organization keys

A platform that gives each of its customers a workspace uses an organization key (ok_live_...) with the second client, UnitpostOrganization. It takes the key and the organization's id (org_...), and reads UNITPOST_ORG_KEY and UNITPOST_ORGANIZATION_ID when you leave them out:

from unitpost import Unitpost, UnitpostOrganization

org = UnitpostOrganization()  # or UnitpostOrganization("ok_live_...", "org_...")

workspace = org.workspaces.create({"name": "Acme Bakery", "external_id": "cust_42"}).data
minted = org.workspace_keys.create(workspace["id"], {"name": "Production", "scope": "sending"}).data

# Work inside that workspace with its own key.
acme = Unitpost(minted["key"])
Accessor Covers
workspaces list() (external_id filter), list_all(), create() (takes an idempotency key), get(), update(), close(), restore()
workspace_keys create(workspace_id, body): mint a workspace key; the secret is in that answer only
webhooks The organization's endpoints (events from every workspace, each with workspace_id and external_id): list(), list_all(), create(), get(), update(), delete(), rotate_secret(), test(), list_deliveries() (needs organizations:write), list_all_deliveries(), replay_delivery(), flush(), verify()
usage list(period=...), list_all(): usage per workspace for its billing period
plan_quotes Change a workspace's plan: create() prices it, get(), confirm() applies and charges it (takes an idempotency key)
shared_plan The organization's shared plan: get(), list_workspaces(), add_workspace(), update_workspace() (its cap), remove_workspace() (adding and removing take an idempotency key)

Each client takes one kind of key: the organization client only calls /organizations/{id}/... routes, and the API answers 401 to an organization key on any other route. An Owner or Admin makes the key in the dashboard under Organization → API.

Client surface

Accessor Covers
email Send, batch, list, get, update, stats, one email's delivery events (list_events()), inbound (received_*; the original .eml with received_raw()), retry a failed email (retry(), takes an idempotency key), batches (list_batches(), get_batch(), cancel_batch())
email.topics Topics + contact topic prefs
email.campaigns Draft, schedule, send, pause/resume, results (stats(), list_stats()), who a send would reach (list_recipients()), quality-pause recovery (list_affected(), remove_affected(), request_review())
email.templates Template CRUD, duplicate(), add from the gallery (from_library()), what uses it (usage()), history (list_versions(), restore_version()), render it without sending (render(), which lists missing_variables)
email.domains Domains + verify, diagnose(), saved From addresses (list_senders(), create_sender(), get_sender(), update_sender(), delete_sender())
email.threads Inbox conversations: list() (q; page with next_cursor), get(), delete(), reply() (reply, reply all or forward; takes an idempotency key)
sms Send, get, list, make the sender of a received text a contact (add_contact(), which needs contacts:write), brands(), a brand (create_brand(), which takes an idempotency key, get_brand(), update_brand(); the writes need sms:manage), numbers(), one number (get_number()), a toll-free verification carriers sent back (resubmit_number(), takes an idempotency key), release a number (release_number(), PERMANENT: its fee ends and it can't be had back; {"force": True} releases it although campaigns are scheduled on it or texts are queued through it; takes an idempotency key and needs sms:manage), a number's text-to-join keywords (list_join_keywords(), add_join_keyword(), remove_join_keyword(); the writes need sms:manage), a brand's documents (list_brand_documents(), add_brand_document() with a file_id or text (takes an idempotency key), get_brand_document(), remove_brand_document(), brand_document_url(), a 5-minute signed link), contact SMS consent, request_sms_opt_in() (reply-YES confirmation). Available on paid plans: on the free plan send returns a 403 with code limit_reached, while the reads keep working.
sms.templates Template CRUD, what uses it (usage()), one test text to a simulator number or a verified number from sms.test_destinations (test_send(), billed like any text; takes an idempotency key)
sms.messaging_programs What a sender registration says your texts are for: list() (archived=True includes archived ones), create() and duplicate() (each takes an idempotency key), get(), update(), delete() (archives). The writes need sms:manage
sms.test_destinations Verified test numbers: list(), delete() (needs sms:manage). Adding and verifying one stays in the dashboard
sms.consent_setups Where and how people opt in to your texts: list()
sms.billing Recurring SMS charges: list_resources()
sms.registrations Carrier registrations and their review state: list(), get(), a 10DLC campaign carriers sent back (resubmit()), a failed number whose fee is committed (request_number()), take down a 10DLC setup with no number (remove()), archive an approved brand registration to register it again (replace()); the writes take an idempotency key and need sms:manage
sms.quotes Buy carrier resources (register a 10DLC brand, vet it, register a campaign, order a number): create() prices the order and returns a single-use confirm_token; confirm() places it (takes an idempotency key; one is generated when you don't pass one). The confirm needs sms:purchase, which no key preset includes, and the owner's monthly cap for SMS purchases by API. Show the person the price first. Release a number with sms.release_number()
contacts CRUD, list filters, import jobs (start, cancel, retry), addresses, recent activity, the segments it is in (list_segments(); add or remove it with segments.add_member() / segments.remove_member()), export to CSV (export(), a background job)
contact_fields Custom field definitions
segments Segments + membership, opt a member in or out (update_member()), who it reaches (preview(), and preview_filter() for an unsaved filter), the managed all-contacts segment (all_contacts())
brand_kits Brand Kit profiles: list(), get(), create(), update(), delete(), reset(), set_default(), add_graphic(), and imports from a website or the brand's own words (import_(), get_import(), accept_import(), cancel_import()). The writes and starting, accepting or canceling an import need the branding:write capability, which no key preset grants
library_images The image library templates embed (/img/… paths): list(), list_all(), create() (takes an idempotency key), get(), update(), delete() (force=True deletes an image in use)
files Files handed to the API for one purpose and used by file_id (a brand document, SMS opt-in evidence, an image): list() (purpose filters), create() (a url, base64 data, or an upload session; takes an idempotency key), get(), delete(), and upload(path_or_bytes, purpose=..., content_type=...), which sends up to 3 MB inline and a larger file through an upload session. A file expires 24 hours after it is created
branding The email footer and unsubscribe page look: get(), update(), set_logo(), remove_logo(). The writes need the branding:write capability, which no key preset grants
workspace Who is calling and what it may do (whoami(), any credential), the activity log (list_activity(), list_all_activity(); needs activity:read), and the workspace's name and image: update(), set_image(), remove_image(). Those three need branding:write. No key preset grants either capability
webhooks Endpoints + verify(), the delivery log (list_deliveries()), replay one delivery (replay_delivery()), deliver the backlog (flush())
api_keys list() and a key's last 24 hours (usage()), which need apikeys:read (on no key preset); create() and delete() need a dashboard session
logs The API request log, newest first: list() (each call's method, path, status, duration, key and request id; never the IP or a body; kept 30 days). Filters: status, api_key_id, method, path_prefix, request_id, created_after / created_before. Needs apikeys:read (on no key preset)
suppressions Suppression list
jobs Background jobs: list(), get(), cancel(), retry(), a finished job's file (download())
usage Billing-period usage snapshot
spend_caps get(), update(): the monthly spend cap on SMS purchases made with a key or an app and what it counted this month; update() needs spend_caps:write, which no key preset grants

Pagination

for contact in unitpost.contacts.list_all():
    print(contact["email"])

Suppressions

The suppression list holds addresses excluded from every send — single, batch, and campaign, including cc/bcc — case-insensitively. Hard bounces and spam complaints are added automatically; you can also add your own:

# Suppress one address, or many in a single call (idempotent — re-adding is a no-op).
unitpost.suppressions.create({"email": "bounced@example.com", "reason": "manual"})
unitpost.suppressions.create({"emails": ["a@example.com", "b@example.com"]})

# Look one up by id or email; list your own; un-suppress.
unitpost.suppressions.get("bounced@example.com")
for s in unitpost.suppressions.list_all():
    print(s["email"], s["reason"])
unitpost.suppressions.delete("bounced@example.com")

reason accepts manual, import, or api — the engine-written bounce and complaint reasons are read-only. Unitpost-wide (platform) entries are visible but can't be removed via the API.

Verifying webhooks

from unitpost import verify_webhook

event = verify_webhook(
    payload=raw_body,          # the raw request body (str or bytes)
    secret=os.environ["UNITPOST_WEBHOOK_SECRET"],
    headers=request.headers,
)

Or from the client:

event = client.webhooks.verify(payload=raw_body, secret=secret, headers=request.headers)

Receive a text and answer it

US toll-free, 10DLC and Canadian numbers take replies (two_way: True on sms.numbers()). Subscribe a webhook to sms.received, skip STOP and texts Unitpost already answered, read the conversation with participant, and answer without from so the reply leaves from the number they texted.

import os
from unitpost import Unitpost, verify_webhook

unitpost = Unitpost()  # reads UNITPOST_API_KEY

# Your webhook endpoint, subscribed to sms.received. Pass the RAW body.
def on_webhook(raw_body: bytes, headers: dict) -> None:
    event = verify_webhook(
        payload=raw_body,
        secret=os.environ["UNITPOST_WEBHOOK_SECRET"],  # whsec_…
        headers=headers,
    )
    if event["type"] != "sms.received":
        return
    reply = event["data"]
    if reply["keyword"] == "OPT_OUT" or reply["auto_replied"]:
        return  # STOP, or already answered

    # The whole conversation with this person, both directions, newest first.
    # Other filters: direction, status, from_ (sent as `from`), to, contact_id,
    # campaign_id, created_after, created_before.
    history = unitpost.sms.list(participant=reply["from"], limit=20)
    answer = your_agent(history.data["data"], reply["body"] or "")

    # No "from": the answer goes out from the number they texted.
    unitpost.sms.send({"to": reply["from"], "body": answer})

Idempotency

email.send and email.batch are safe to retry by default — if you don't pass idempotency_key, the SDK generates one so an automatic retry can't double-send. Pass your own to dedupe across separate calls:

unitpost.email.send({...}, idempotency_key="...")
unitpost.email.batch([...], idempotency_key="...")

The server dedupes on (workspace, idempotency key) for 24h and replays the original result instead of re-sending (the email id for a send, the full list envelope for a batch).

Retries

Transient failures are retried automatically: 429, 5xx, and transport errors (timeouts / network) retry up to max_retries times (default 2). A 429/503 Retry-After is honored; otherwise exponential backoff with full jitter is used. Client errors (401/403/404/409/422) are never retried. Only requests safe to replay are retried: GETs and writes carrying an idempotency key (which email.send and email.batch always do); any other keyless write is never auto-retried.

# Defaults shown; set max_retries=0 to disable.
unitpost = Unitpost(max_retries=2, retry_base_delay=0.5, max_retry_delay=20.0)

Resources

Docs + API reference https://www.unitpost.com/docs
Product guides https://www.unitpost.com/guides
SMTP https://www.unitpost.com/docs/smtp
OpenAPI JSON https://www.unitpost.com/api/v1/openapi.json
LLM index https://www.unitpost.com/llms.txt
Dashboard / API keys https://www.unitpost.com
Email components (@unitpost/email) https://www.unitpost.com/components
Template gallery https://www.unitpost.com/templates/gallery
Playground https://www.unitpost.com/playground
Migration Assistant https://www.unitpost.com/migration
MCP + Agent Skills https://www.unitpost.com/docs/ai/mcp · https://www.unitpost.com/docs/ai/skills
Support support@unitpost.com

License

MIT

Metadata

Release files for unitpost 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for unitpost 0.6.0
File Size Uploaded Provenance Actions
unitpost-0.6.0.tar.gz 73.4 kB Without provenance Details for unitpost-0.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for unitpost 0.6.0
File Interpreter ABI Platform Actions
unitpost-0.6.0-py3-none-any.whl Python 3 none any Details for unitpost-0.6.0-py3-none-any.whl

Total release size: 137.0 kB

Release files / unitpost-0.6.0.tar.gz

Download URL unitpost-0.6.0.tar.gz
Size 73.4 kB
Tags Source
SHA-256 checksum
How to use checksums
5921f4d4713d7ab343a57277cfbbe0f38ddd10ea788075434c758e0abc1a56d4
BLAKE2b-256 checksum
How to use checksums
fbd06402422303eab1359a38c6797178fe4144363ec8b0adc2ca166b4325e4ab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / unitpost-0.6.0-py3-none-any.whl

Download URL unitpost-0.6.0-py3-none-any.whl
Size 63.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
37fa8d4381da9a6f2532118e28ebbb264de09570415ceadd221a647606196ba4
BLAKE2b-256 checksum
How to use checksums
171c2dddaf934b5c6df37892a99c144e6e5be4d10e219b965dd268ed1df9a039
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for unitpost 0.6.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page