送出例子

用Node.js發送

使用內建的取件功能,從任何 Node.js 18+ 項目發送電子郵件。

前提條件

  • 存儲為 SENDTERN_API_KEY 的 Sendtern API 鍵
  • Node.js 18 or newer, which ships with fetch
  1. 1

    發送電子郵件

    Create send.mjs. No package is needed.

    1// send.mjs
    2const res = await fetch("https://sendtern.com/emails", {
    3  method: "POST",
    4  headers: {
    5    Authorization: `Bearer ${process.env.SENDTERN_API_KEY}`,
    6    "Content-Type": "application/json",
    7    "Idempotency-Key": crypto.randomUUID(),
    8  },
    9  body: JSON.stringify({
    10    from: "Acme <hello@mail.example.com>",
    11    to: ["you@example.com"],
    12    subject: "Hello from Node.js",
    13    html: "<p>It works!</p>",
    14  }),
    15});
    16
    17if (!res.ok) throw new Error((await res.json()).message);
    18console.log(await res.json());
    
  2. 2

    檢查一下反應

    成功的請求返回 200 OK 與電子郵件 ID。使用它以後查看電子郵件。

    1{
    2  "id": "47be30ca-24b7-48fb-b35d-ff287b89e66d"
    3}
    
1node --env-file=.env send.mjs

用您的 verified domain 的地址替换示例发件人。