Python
SpacePost はシンプルな JSON API なので、どの HTTP クライアントでも使えます。公式の Python パッケージはありません。OpenAPI 仕様からクライアントを生成してください。
pip install requestsimport osimport 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>"))pip install httpximport asyncioimport osimport httpx
async def main() -> None: async with httpx.AsyncClient( base_url="https://api.spacepost.dev", headers={"Authorization": f"Bearer {os.environ['SPACEPOST_API_KEY']}"}, timeout=15, ) as client: r = await client.post( "/emails", json={ "from": "Acme <hello@acme.com>", "to": ["delivered@test.spacepost.dev"], "subject": "Hello from httpx", "html": "<p>It works.</p>", }, ) r.raise_for_status() print(r.json())
asyncio.run(main())429 が返ったら、retry-after ヘッダーの秒数だけ待機し、同じ Idempotency-Key で再試行します。詳しくはレート制限と冪等キーをご覧ください。
Django、Flask などのフレームワークでは、SMTP リレーも利用できます。