# 使用 Node.js 发送

> 使用内置的 fetch 功能,从任何 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) 上的地址。
