Sign inGet Started

TypeScript · Next.js

使用 @messagebird/sdk 从 Next.js App Router Server Action 发送邮件。你需要一个 Bird API 密钥:在 Developers > API keys 中创建一个(发送你的第一封邮件有详细步骤),然后将它放入 .env.local 并命名为 BIRD_API_KEY。

1. 安装

代码示例
npx create-next-app@latest my-app --yes --ts --eslint --no-tailwind --app --no-src-dir --use-npm --disable-git
cd my-app
npm install @messagebird/sdk

2. 发送

创建 app/actions/send-welcome.ts。"use server" 指令确保它(以及你的 API 密钥)只在服务器端运行:
代码示例
"use server";

import { BirdClient } from "@messagebird/sdk";

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

export async function sendWelcome() {
  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 { id: msg.id, status: msg.status };
}
onboarding@messagebird.dev 是 Bird 的共享入门发件人,delivered@messagebird.dev 是一个始终可送达的沙盒收件人:无需域名验证。SDK 根据密钥的 bk_us1_ / bk_eu1_ 前缀推断区域(无需配置 base URL),并为每次调用自动生成一个 Idempotency-Key,因此重试发送是安全的。

3. 试一试

在 app/page.tsx 中将 action 绑定到表单,然后点击按钮:
代码示例
import { sendWelcome } from "./actions/send-welcome";

export default function Home() {
  return (
    <form action={sendWelcome}>
      <button type="submit">Send email</button>
    </form>
  );
}
运行 npm run dev,打开 http://localhost:3000,然后提交。Bird 以 202 接受邮件并异步投递;运行开发服务器的终端会输出 em_ ID 和状态:
代码示例
em_01ky7ma8y2es1s2akzk53tmjn0 accepted

后续步骤