Python · FastAPI
使用 Bird Python SDK 的异步客户端,从 FastAPI 端点发送第一封邮件。三个步骤:安装、发送、运行。
1. 安装 SDK
代码示例
python -m pip install messagebird-sdk "fastapi[standard]"需要 Python 3.10+。导入包名为 bird。
2. 发送邮件
导出你的 API 密钥。SDK 从环境变量中读取 BIRD_API_KEY,并根据 bk_us1_ / bk_eu1_ 前缀推断区域(us1 或 eu1),因此 AsyncBird() 无需任何参数:
代码示例
export BIRD_API_KEY="bk_us1_..."创建 main.py。在启动时构造一个 AsyncBird,并在请求间复用:它会池化连接,且可安全地在多个任务间共享。
代码示例
from bird import AsyncBird, APIError
from fastapi import FastAPI, HTTPException
app = FastAPI()
client = AsyncBird()
@app.post("/send", status_code=202)
async def send() -> dict[str, str]:
try:
message = await client.email.send(
from_="onboarding@messagebird.dev",
to=["delivered@messagebird.dev"],
subject="Hello from Bird",
html="<p>My first Bird email.</p>",
)
except APIError as err:
raise HTTPException(status_code=502, detail=str(err))
return {"id": message.id, "status": message.status}from_ 是 from 字段的 Python 写法(from 是保留字)。onboarding@messagebird.dev 是 Bird 的共享入门发件人(无需域名验证),delivered@messagebird.dev 是始终可送达的沙箱收件人。
SDK 会自动重试暂时性故障,并在每次尝试时复用该调用的幂等键。这可以防止重试导致消息被发送两次。
3. 试一试
代码示例
fastapi dev main.py
curl -X POST http://localhost:8000/sendBird 以 202 接受消息并异步投递;你的端点返回 em_ ID 和状态:
代码示例
{
"id": "em_01ky7ma8y2es1s2akzk53tmjn0",
"status": "accepted"
}通过 em_ ID 使用 await client.email.get(...) 获取消息,观察状态从 accepted 变为 delivered。
后续步骤
- Python SDK 邮件参考:所有方法和选项。
- 发送第一封邮件:使用 curl 的相同流程以及完整的沙箱地址列表。
- 发送域名:验证你自己的域名以用于生产环境发送。
- 邮件 API 参考:完整的请求和响应结构。
相关资源
继续查阅此主题的文档、指南和示例。资源为英文。