Skip to content

Python

SpacePost is a plain JSON API, so any HTTP client works. There is no official Python package; use the OpenAPI spec to generate one.

Terminal window
pip install requests
send.py
import os
import requests
API = "https://api.spacepost.dev"
HEADERS = {"Authorization": f"Bearer {os.environ['SPACEPOST_API_KEY']}"}
def send_email(to: str, subject: str, html: str, idempotency_key: str | None = None) -> dict:
headers = dict(HEADERS)
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
r = requests.post(
f"{API}/emails",
headers=headers,
json={"from": "Acme <hello@acme.com>", "to": [to], "subject": subject, "html": html},
timeout=15,
)
body = r.json()
if not r.ok:
# {"statusCode": 422, "name": "validation_error", "message": "..."}
raise RuntimeError(f"{body['name']}: {body['message']}")
return body # {"id": "..."}
if __name__ == "__main__":
print(send_email("delivered@test.spacepost.dev", "Hello from Python", "<p>It works.</p>"))

Handle 429 by sleeping for the retry-after header and retrying with the same Idempotency-Key. See Rate limits and Idempotency keys.

For Django, Flask and other frameworks you can also use the SMTP relay.