コンテンツにスキップ

Python

SpacePost はシンプルな JSON API なので、どの HTTP クライアントでも使えます。公式の Python パッケージはありません。OpenAPI 仕様からクライアントを生成してください。

ターミナルウィンドウ
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>"))

429 が返ったら、retry-after ヘッダーの秒数だけ待機し、同じ Idempotency-Key で再試行します。詳しくはレート制限と冪等キーをご覧ください。

Django、Flask などのフレームワークでは、SMTP リレーも利用できます。