# 用Node.js發送

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

## 前提條件

- 存儲為 `SENDTERN_API_KEY` 的 Sendtern [API 鍵](https://sendtern.com/docs/authentication)
- Node.js 18 or newer, which ships with `fetch`

1. **發送電子郵件**: Create `send.mjs`. No package is needed.

```
// send.mjs
const res = await fetch("https://sendtern.com/emails", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.SENDTERN_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify({
    from: "Acme <hello@mail.example.com>",
    to: ["you@example.com"],
    subject: "Hello from Node.js",
    html: "<p>It works!</p>",
  }),
});

if (!res.ok) throw new Error((await res.json()).message);
console.log(await res.json());
```

2. **檢查一下反應**: 成功的請求返回 `200 OK` 與電子郵件 ID。使用它以後查看電子郵件。

```
{
  "id": "47be30ca-24b7-48fb-b35d-ff287b89e66d"
}
```

```
node --env-file=.env send.mjs
```

> **tip:** 用您的 [verified domain](https://sendtern.com/docs/domains) 的地址替换示例发件人。
