Sign inGet Started

TypeScript · Hono

使用 @messagebird/sdk 从 Node.js 上的 Hono POST 处理程序发送邮件。你需要 Node.js 20.3 或更高版本,以及一个 Bird API 密钥。在 Developers > API keys 中创建密钥(发送第一封邮件有详细步骤),然后将其导出为 BIRD_API_KEY。

1. 安装

代码示例
npm create hono@latest my-app -- --template nodejs --pm npm --install
cd my-app
npm install @messagebird/sdk

2. 发送

在 src/index.ts 中添加路由:
代码示例
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { BirdClient } from "@messagebird/sdk";

const bird = new BirdClient({ apiKey: process.env.BIRD_API_KEY! });
const app = new Hono();

app.post("/send", async (c) => {
  const msg = await bird.email.send({
    from: "onboarding@messagebird.dev",
    to: ["delivered@messagebird.dev"],
    subject: "Hello from Bird",
    html: "<p>My first Bird email.</p>",
  });

  console.log(msg.id, msg.status); // "em_…", "accepted"
  return c.json({ id: msg.id, status: msg.status });
});

serve({
  fetch: app.fetch,
  port: 3000,
});
onboarding@messagebird.dev 是 Bird 的共享入门发件人,delivered@messagebird.dev 是一个始终能送达的沙盒收件人,无需域名验证。SDK 根据密钥的 bk_us1_ / bk_eu1_ 前缀推断区域(无需配置 base URL),并在每次调用时自动生成 Idempotency-Key,因此重试发送是安全的。

3. 试一试

启动开发服务器并向路由发送 POST 请求:
代码示例
npm run dev
curl -X POST http://localhost:3000/send
Bird 以 202 接受邮件并异步投递;你的路由返回 em_ ID 和状态:
代码示例
{
  "id": "em_01ky7ma8y2es1s2akzk53tmjn0",
  "status": "accepted"
}

后续步骤