Skip to content

SDKs and toolsPython SDK

Python SDK

The official shipmail package has a sync client and an async client. It needs Python 3.10 or later.

Last updated

Installation

uv add shipmail

Member roles and mailbox access

members = client.members.list({"limit": 25})
member = client.members.get("mem_alice")
print(member["role"], member["mailbox_access"])

# With AsyncShipmail:
member = await client.members.get("mem_alice")

# Needs members:write
invitation = client.members.invite(
    {"email": "sam@acme.com", "role": "member", "mailbox_ids": ["mbx_123"]},
    {"idempotency_key": "invite-sam"},
)
pending = client.members.list_invitations()
client.members.cancel_invitation(invitation["id"])
client.members.grant_mailbox_access("mem_alice", "mbx_123")
client.members.revoke_mailbox_access("mem_alice", "mbx_123")

Roles are owner, admin, or member. mailbox_access contains a scope of all or selected and a mailbox_ids array, empty for all.

With selected access, you only see the mailbox IDs your key can reach, so the list may be incomplete. An empty selected list may mean no grants or no visible grants. A key with only members:read has no mail reach and returns no selected mailbox IDs.

Inviting people and sharing mailboxes need members:write, which no preset includes (an All access key does). The invitee receives an email and creates their own account; you never receive their credentials. See the Members API for who may grant which mailboxes.

Quick start

from shipmail import Shipmail

client = Shipmail("sm_live_...")

message = client.messages.send({
    "from": "hello@yourdomain.com",
    "to": ["recipient@example.com"],
    "subject": "Hello from Shipmail",
    "text": "It works.",
    "client_reference": "crm-123",
    "metadata": {"campaign": "onboarding"},
    "source_rfc_message_id": "<crm-123@yourdomain.com>",
})

same_message = client.messages.list({"client_reference": "crm-123"})
client.mailboxes.suspend("mbx_123")
client.mailboxes.resume("mbx_123")
forwarding = client.mailboxes.create_forwarding("mbx_123", {
    "destination": "owner@example.net",
})
forwarding_list = client.mailboxes.list_forwarding("mbx_123")
app_password = client.mailboxes.create_app_password("mbx_123", {
    "name": "Desktop mail",
    "expires_at": "2026-10-01T00:00:00Z",
})
app_passwords = client.mailboxes.list_app_passwords("mbx_123")
client.mailboxes.revoke_app_password("mbx_123", app_password["id"])
smtp_credential = client.smtp_credentials.create({
    "from": "notifications@notify.example.com",
    "name": "Supabase Auth",
})
client.smtp_credentials.list({"from": "notifications@notify.example.com"})
client.smtp_credentials.revoke(smtp_credential["id"])
tx_domain = client.transactional_domains.create({
    "root_domain": "example.com",
    "subdomain": "notify",
})
# Publish tx_domain["dns_records"], then check until status is "verified"
client.transactional_domains.verify(tx_domain["id"])
sender = client.transactional_senders.create({
    "domain_id": tx_domain["id"],
    "mailbox_id": "mbx_123",
    "local_part": "notifications",
    "display_name": "Acme",
})
client.transactional_senders.update(sender["id"], {"refuse_disposable": True})
rules = client.mailboxes.get_rules("mbx_123")
client.mailboxes.update_rules("mbx_123", {"rules": rules["rules"]})
mailbox_export = client.mailboxes.create_export("mbx_123")
export_status = client.mailboxes.get_export("mbx_123", mailbox_export["id"])
print(message["id"], same_message["data"][0]["id"], forwarding["status"], len(forwarding_list["data"]))

Attach files from disk

attachment_from_path reads a file into an inline attachment for messages.send. The filename is the file's name and the content type comes from its extension, or application/octet-stream when it is unknown. Pass filename= or content_type= to set them. It is a plain function, so it works with both Shipmail and AsyncShipmail.

The whole email can be 10 MB with encoding, which leaves about 7 MB for files. A transactional sender takes inline files only. For larger files, stage each one with mailboxes.stage_attachment and send its ID in staged_attachment_ids.

from shipmail import attachment_from_path

client.messages.send({
    "mailbox_id": "mbx_123",
    "to": ["customer@example.com"],
    "subject": "Invoice",
    "text": "Attached.",
    "attachments": [
        attachment_from_path("invoice.pdf"),
        attachment_from_path("export", filename="export.csv", content_type="text/csv"),
    ],
})

Email held for review

An API key can hold email to outside addresses for review. With such a key, messages.send, messages.reply and threads.reply return a held message instead of a message when a recipient is outside your domains. Nothing was sent: the email waits in the mailbox's Drafts for a person to send. Check the result with is_held_message.

from shipmail import Shipmail, is_held_message

result = client.messages.send({
    "from": "hello@yourdomain.com",
    "to": ["client@example.com"],
    "subject": "Proposal",
    "text": "Here is the proposal.",
})

if is_held_message(result):
    print("Saved as draft", result["draft_id"], "for", result["external_recipients"])
else:
    print("Sent", result["id"])

client_reference, metadata and track_reply stay with a held draft and apply to the message the person sends.

Batch sends and reply state

messages.send_batch sends up to 50 messages in one request and returns one result per item. Check each with is_held_message and is_message_batch_item_error. Thread objects carry attention_state and attention_since, and threads.list filters by them and by batch_id.

from shipmail import is_held_message, is_message_batch_item_error

batch = client.messages.send_batch(
    {
        "messages": [
            {
                "from": "sales@yourdomain.com",
                "to": [lead["email"]],
                "subject": "Quick question",
                "text": f"Hi {lead['name']}, ...",
                "client_reference": lead["id"],
                "metadata": {"campaign": "q4"},
                "track_reply": True,
            }
            for lead in leads
        ]
    },
    {"idempotency_key": "q4-outreach-1"},
)

for item in batch["data"]:
    if is_message_batch_item_error(item):
        print("Refused", item["index"], item["error"]["message"])
    elif is_held_message(item):
        print("Held", item["client_reference"], item["draft_id"])
    else:
        print("Sent", item["client_reference"], item["id"])

silent = client.threads.list({
    "batch_id": batch["batch_id"],
    "attention_state": ["waiting_on_them"],
    "before": "2026-11-05T00:00:00Z",
})

Direct newsletter media uploads

Uploads take three steps. Prepare the upload with the file's exact SHA-256 digest, PUT the bytes straight to storage, then call the completion URL, which needs no API key. For a video, the response also has a second PUT for the JPEG poster.

prepared = client.newsletters.assets.prepare_upload({
    "filename": filename,
    "content_type": content_type,
    "size": len(data),
    "sha256": sha256,
})

httpx.put(
    prepared["upload_url"],
    headers=prepared["upload_headers"],
    content=data,
).raise_for_status()

# For prepared["kind"] == "video", upload a JPEG poster with the thumbnail_* fields first.
asset = httpx.post(prepared["complete_url"]).raise_for_status().json()

Sandbox

With an sm_test_... key you can fake outbound results and call mailboxes.inject_sandbox_inbound(). See the sandbox guide.

Async client

Use AsyncShipmail with async/await. Open it in an async with block and it cleans up after itself when the block ends.

from shipmail import AsyncShipmail

async with AsyncShipmail("sm_live_...") as client:
    message = await client.messages.send({
        "from": "hello@yourdomain.com",
        "to": ["recipient@example.com"],
        "subject": "Hello",
        "text": "Hi there",
    })

Configuration

client = Shipmail(
    "sm_live_...",
    base_url="https://shipmail.to/api/v1",  # default
    max_retries=2,      # default
    timeout=30.0,       # seconds, default
)
OptionDefaultDescription
api_keyrequiredYour sm_live_... key.
base_urlhttps://shipmail.to/api/v1API base URL.
max_retries2Retry count for eligible requests; 0 disables retries.
timeout30.0Request timeout in seconds.

Resources

Each API resource is a property on the client:

PropertyMethods
client.organizationaccess: plan, access, trial and mailbox capacity. See GET /v1/organization/access. get, update, get_ai_settings, update_ai_settings: the default time zone and AI switches.
client.domainscreate, list, get, get_dns_records, get_health, update, delete, verify, search, register
client.mailboxescreate, list, get, update, delete, list_folders, create_folder, update_folder, delete_folder, list_identities, list_inbox_messages, get_inbox_message, list_inbox_threads, get_inbox_thread, update_inbox_thread_attention, download_inbox_message_raw, create_inbox_draft, get_inbox_draft, update_inbox_draft, delete_inbox_draft, create_inbox_reply_draft, list_inbox_reply_drafts, get_inbox_reply_draft, update_inbox_reply_draft, delete_inbox_reply_draft, send_inbox_reply_draft, reply_to_inbox_message, reply_to_inbox_thread, update_inbox_message, move_inbox_message, delete_inbox_message, download_inbox_attachment, reset_password, get_rules, update_rules, list_aliases, create_alias, delete_alias, list_forwarding, create_forwarding, delete_forwarding, update_auto_reply, create_export, get_export, create_import, list_imports, get_import, cancel_import, resume_import, restore_import, undo_import, create_import_upload
client.reply_scanscreate, get, list_results
client.messagessend (with a template or your own content), send_batch, list (by mailbox, client reference or batch), get, reply, respond_to_invitation
client.templateslist, list_auto_paginating, create, get, update, delete, publish, render, list_versions, get_version, restore_version
client.memberslist, list_auto_paginating, get, list_invitations, invite, cancel_invitation, grant_mailbox_access, revoke_mailbox_access
client.threadslist (by mailbox or batch, filtered by attention state), get, reply
client.webhookscreate, list, get, update, delete, rotate_secret, test, list_deliveries
client.event_queuescreate, list, list_auto_paginating, get, delete, list_events, ack
client.smtp_credentialslist (filter by from), create (returns the password once), revoke
client.transactional_domainslist, create, get, verify, delete
client.transactional_senderslist (filter by domain_id), create, get, update
client.suppressionscreate, list (filter by scope), remove, remove_batch, resubscribe (lift a newsletter opt-out)
client.customerslist, get, create, update, remove, upsert_by_external_id, list_service_levels, list_fields
client.audiencescreate, list, get, update, delete
client.automationscreate, list, get, update, run, test
client.audiences.subscribersadd, add_batch, list, get, get_by_email, update, unsubscribe (scope organization or audience), resubscribe, resend_confirmation, remove
client.audiences.feedsget, update, rotate, revoke
client.audiences.segmentslist, create, get, update, delete
client.newsletterscreate, create_from_changelog, list, get, update, preview, preflight, send_test, schedule, cancel, resume
client.newsletters.domainslist
client.newsletters.assetslist, upload, register_from_url
client.calendar.eventscreate, list, get, update, delete
client.calendaravailability
client.booking_pagescreate, list, get, update, delete
client.booking_linkscreate, list, get, update, revoke
client.statusget

Paginated list methods also have a list_auto_paginating variant that loops over every page.

Calendar invitation language

created = client.calendar.events.create({
    "mailbox": "hello@yourdomain.com",
    "operation_key": "calendar-create-01",
    "send_invitations": True,
    "title": "Intro call",
    "start": "2026-08-07T08:30:00",
    "timezone": "Europe/Paris",
    "duration": "PT1H",
    "invitation_language": "fr",
    "attendees": [{"email": "guest@example.com"}],
})

Use en, fr, or es. Later update and cancellation messages for that event use the same language.

Reuse operation_key only to retry the exact same payload. Mutation responses expose per-recipient invitation_outcomesand the compatibility invitation_failures list. Read revision from an event and pass it as expected_revision on updates; send_guest_updates controls scheduling messages.

Answer a calendar invitation

answer = client.messages.respond_to_invitation(
    "msg_123",
    {"response": "accepted"},  # or "tentative", "declined"
)
answer["replied"]  # True when the organizer got the answer by email
answer["calendar_event_id"]

The message.received webhook carries the invitation as data["invitation"], typed WebhookInvitation | None. Needs calendar:write.

Email templates

template = client.templates.create({
    "name": "Welcome",
    "subject": "Welcome, {{first_name}}",
    "html": "<p>Hi {{first_name}}, your plan is {{plan}}.</p>",
    "fallbacks": {"plan": "Free"},  # first_name has no fallback, so every send must pass it
    "publish": True,
})

preview = client.templates.render(template["id"], {"variables": {"first_name": "Ada"}})

client.messages.send({
    "from": "hello@yourdomain.com",
    "to": ["ada@example.com"],
    # Omit subject, html and text when sending a template.
    "template": {"id": template["id"], "variables": {"first_name": "Ada"}},
})

client.templates.update(template["id"], {"subject": "Hello, {{first_name}}"})  # draft only
client.templates.publish(template["id"])  # version 2
client.templates.restore_version(template["id"], 1)  # copies version 1 into the draft

The async client has the same methods. A send naming an unknown template raises NotFoundError. A template that was never published, a required variable left out, or a variable the template does not use raises ValidationError, whose details[].code is template_not_published, missing_variable or unknown_variable. See the Templates API.

Automations

definition = {
    "trigger": {"type": "scheduled", "cron": "0 8 * * *", "time_zone": "Europe/Lisbon"},
    "conditions": [],
    "actions": [{"type": "generate_mail_report", "metric": "received", "lookback_minutes": 1440}],
    "mode": "draft",
    "scope": {"mailbox_ids": ["mbx_123"], "calendar_addresses": []},
}

automation = client.automations.create({
    "name": "Daily brief",
    "definition": definition,
})

client.automations.update(automation["id"], {"status": "paused"})

The sync and async clients have the same methods. You write out the whole definition, and create turns it on in one step. See the Automations API.

Audience feed settings

feed = client.audiences.feeds.update("aud_123", {
    "canonical_url": "https://example.com/feed.xml",
    "entry_limit": 25,
})

print(feed["canonical_url"], feed["entry_limit"])

# AsyncShipmail accepts the same fields.
await async_client.audiences.feeds.update("aud_123", {
    "canonical_url": None,
    "entry_limit": None,
})

The entry limit is a whole number from 10 to 100. Leave a key out to keep its current value. A null in the response means null is what's stored, not that a default was filled in.

Check a subscriber list before importing

check = client.audiences.subscribers.add_batch("aud_123", {
    "subscribers": [{"email_address": "jane@example.com"}, {"email_address": "alex@gamil.com"}],
    "dry_run": True,
})

for row in check["results"]:
    if row["outcome"] == "skipped_invalid":
        print(row["email_address"], row["reason"], row.get("suggestion"))

Pass "dry_run": True to see what an import would do; the async client takes the same call with await. Each row gets the outcome it would have, and nothing is added, charged or sent. A skipped_invalid row carries a reason code, and a typo carries the corrected address in suggestion. A dry run does not check the subscriber limit, the monthly add quota or the API key's recipient limits.

Booking page conferencing

page = client.booking_pages.create({
    "name": "Intro call",
    "mailbox": "hello@yourdomain.com",
    "slug": "intro",
    "duration_minutes": 30,
    "availability_days": [1, 2, 3, 4, 5],
    "window_start_minutes": 540,
    "window_end_minutes": 1020,
    "timezone": "America/New_York",
    "conferencing_provider": "zoom",
})

client.booking_pages.update(page["id"], {
    "conferencing_provider": None,
})

The provider is off until you set it, and it must already be connected to the booking page's mailbox. Use None to stop creating meeting links. See conferencing setup.

Booking page slots

result = client.booking_pages.slots("bkp_123", {
    "from": "2026-11-09T00:00:00Z",
    "to": "2026-11-16T00:00:00Z",
    "duration": 60,
})

Returns the open slots the page offers, exactly as its public page shows them, as UTC instants, with the page's timezone. Both bounds are optional: the window runs from now to the end of the page's booking horizon, at most 62 days. duration picks one of the lengths the page offers and defaults to its duration_minutes. Needs the calendar:read scope.

Booking page hours and lengths

client.booking_pages.update("bkp_123", {
    "duration_minutes": 30,
    "duration_options": [15, 30, 60],
    "weekly_hours": [
        {"day": 1, "start_minutes": 540, "end_minutes": 720},
        {"day": 1, "start_minutes": 780, "end_minutes": 1020},
    ],
    "max_bookings_per_day": 4,
    "reminder_minutes_before": 1440,
})

weekly_hours allows up to 4 ranges a day, so a day can have a break, and replaces availability_days and the window. date_overrides sets time off and special hours. Set a limit or an email field to None to turn it off. See the booking pages API for every field.

Newsletter workflow

Build newsletters you want to edit later out of blocks. Paragraph, quote, callout, list-item, and column bodies accept bare text or sanitized inline HTML. Use p and br for line breaks. Use body_html or custom_html only when you need raw HTML.

# Set up sending once: publish domain["dns_records"], then verify until status is "verified".
domain = client.newsletters.domains.create({
    "root_domain": "example.com",
    "reply_to_address": "hello@example.com",
})
client.newsletters.domains.verify(domain["id"])
client.newsletters.sender_identities.create({
    "newsletter_domain_id": domain["id"],
    "from_name": "Acme",
    "business_name": "Acme Ltd.",
})

sender_identities = client.newsletters.sender_identities.list({"limit": 25})
assets = client.newsletters.assets.list({
    "kind": "image",
    "q": "feature",
    "limit": 25,
})
for asset in client.newsletters.assets.list_auto_paginating(
    kind="image", q="feature", limit=25
):
    print(asset["filename"])
with open("feature.png", "rb") as f:
    image = client.newsletters.assets.upload({
        "filename": "feature.png",
        "content_type": "image/png",
        "data": f.read(),
    })
existing_image = client.newsletters.assets.register_from_url({
    "url": "https://cdn.shipmail.to/newsletter-images/org_123/demo.png",
    "filename": "demo.png",
})

newsletter = client.newsletters.create({
    "audience_id": "aud_...",
    "sender_identity_id": sender_identities["data"][0]["id"],
    "name": "July changelog",
    "subject": "What shipped in July",
    "preview_text": "A quick product update",
    "blocks": [
        {"type": "heading", "level": 1, "text": "July updates"},
        {
            "type": "callout",
            "variant": "info",
            "title": "Quick note",
            "body": "A <strong>short</strong> intro.",
        },
        {
            "type": "paragraph",
            "body": 'Read the <a href="https://example.com/launch">full announcement</a>.',
        },
        {"type": "image", "url": image["url"], "alt": "Product screenshot"},
        {"type": "image", "url": existing_image["url"], "alt": "Existing CDN screenshot"},
        {
            "type": "columns",
            "ratio": "50-50",
            "left": {"title": "For teams", "image_url": image["url"], "image_fit": "natural"},
            "right": {"title": "For agents", "image_url": existing_image["url"], "image_fit": "contain"},
        },
    ],
})

client.newsletters.preview(newsletter["id"])
client.newsletters.send_test(newsletter["id"], {
    "recipient_email": "owner@example.com",
})
client.newsletters.preflight(newsletter["id"])
client.newsletters.schedule(newsletter["id"], {
    "scheduled_at": "2026-08-01T09:00:00.000Z",
})

Preflight lists every URL in the issue. Too many clickable destinations is an error. A high number of remote resources (links, images, video thumbnails) is a warning.

Pass limit to send to the most engaged subscribers first, then send to the others with send_to_more. Set subject_b on create or update to test a second subject.

client.newsletters.update(newsletter["id"], {
    "subject_b": "July: three things you asked for",
    "track_engagement": True,
})
client.newsletters.schedule(newsletter["id"], {
    "scheduled_at": "2026-08-01T09:00:00.000Z",
    "limit": 500,
})

# A website-only issue: published on the newsletter website at the scheduled time, no email.
client.newsletters.update(newsletter["id"], {"publish_target": "website"})
client.newsletters.send_to_more(newsletter["id"], {"count": 1000})

# No View in browser link in this issue, or by default in new dashboard issues of the audience.
client.newsletters.update(newsletter["id"], {"view_in_browser": False})
client.audiences.update("aud_123", {"view_in_browser_default": False})

# Track opens and clicks by default in new issues; skip the last-chance email in list cleanup.
client.audiences.update(
    "aud_123", {"track_engagement_default": True, "cleanup_send_last_chance": False}
)

# New dashboard issues of the audience go to the website only, with UTM tags and a feed title link.
client.audiences.update(
    "aud_123",
    {
        "publish_target_default": "website",
        "add_utm_tags_default": True,
        "feed_entry_url_default": "https://example.com/blog",
    },
)

Retries

The SDK retries eligible requests after connection errors, 429 responses, and retryable 5xx errors. GET, HEAD and OPTIONS requests retry on their own. POST, PATCH and PUT retry only when you pass an explicit idempotency_key method option or an Idempotency-Key header. Use the same key for every try of the same operation. DELETE requests and errors marked non-retryable are never retried.

max_retries defaults to 2, for up to 3 total attempts, and must be a non-negative integer. Set it to 0 to disable retries. A valid Retry-After header, in seconds or HTTP-date format, wins over the rate-limit error body's retry_after. Without either, the SDK waits with exponential backoff and jitter. If the server asks for more than 60 seconds, the SDK returns the error instead of waiting. Retry yourself once that time has passed.

Error handling

API errors raise typed subclasses of ShipmailError. Each error exposes status, type, request_id, and retryable. When the organization owner can fix a refusal in Shipmail, the error also sets reason and action_url; send the link to the owner, then retry with a new idempotency key. When a plan, trial or fixed limit causes the refusal, it also sets limit, a dict with resource, used, limit and scope. Newsletter guardrail failures on test-send and schedule are ValidationErrors with preflight fields in details.

from shipmail import (
    ShipmailError,
    ValidationError,
    RateLimitError,
    APIConnectionError,
)

try:
    client.messages.send({...})
except ValidationError as err:
    print(err.details)     # field-level errors
except RateLimitError as err:
    print(err.retry_after) # seconds to wait
except ShipmailError as err:
    print(err.status)      # HTTP status code
    print(err.request_id)  # request ID for support
ClassStatus
AuthenticationError401
AuthorizationError403
ValidationError422
NotFoundError404
ConflictError409
RateLimitError429
InternalServerError500
APIConnectionErrorNetwork failure

Pagination

To page through yourself, pass the cursor from the last page:

page = client.domains.list({"limit": 10})
for domain in page["data"]:
    print(domain["name"])

if page["pagination"]["has_more"]:
    next_page = client.domains.list({
        "cursor": page["pagination"]["next_cursor"],
    })

Or let the SDK fetch every page for you:

# Sync
for domain in client.domains.list_auto_paginating(limit=25):
    print(domain["name"])

# Async
async for domain in client.domains.list_auto_paginating(limit=25):
    print(domain["name"])

Webhook verification

The SDK exports a standalone verify_webhook function. You don't need a client to call it.

from shipmail import verify_webhook, WebhookVerificationError

try:
    event = verify_webhook(raw_body, headers, webhook_secret)
    print(event["event_type"])  # "message.received"
except WebhookVerificationError:
    pass  # invalid signature

Raises WebhookVerificationError if the signature is invalid or the timestamp is more than 5 minutes off. Pass tolerance_in_seconds=600 to change the window.

Per-request options

Every method accepts an optional options argument that overrides settings for that one request:

client.domains.create(
    {"name": "example.com"},
    {
        "idempotency_key": "550e8400-...",
        "timeout": 10.0,
    },
)