# Gửi email giao dịch từ Node.js và Next.js

Cài `@hatang/sdk`, xác minh tên miền gửi một lần, rồi gọi `emails.send` từ code phía server. API tương thích Resend, và dùng được cả SMTP.

```bash
npm install @hatang/sdk
```

```ts
import { Hatang } from "@hatang/sdk";

const hatang = new Hatang(); // đọc HATANG_API_KEY

const { data, error } = await hatang.emails.send(
  {
    from: "Acme <orders@example.com>", // tên miền đã xác minh ở Email → Tên miền
    to: "lan@example.net",
    subject: "Đơn hàng #1024 đã được xác nhận",
    html: "<p>Chào Lan, đơn hàng <strong>#1024</strong> của bạn đã được xác nhận.</p>",
    text: "Chào Lan, đơn hàng #1024 của bạn đã được xác nhận.",
  },
  { idempotencyKey: "order-1024-confirmation" }, // gửi lại không bao giờ thành hai email
);
if (error) throw new Error(`${error.name}: ${error.message}`);
console.log(data.id);
```

Trong Next.js, gọi từ Server Action hoặc Route Handler, không bao giờ từ client component: API key là bí mật.

## Các bước

1. Tạo API key có scope `email:send` ở **Cài đặt → API Keys** và đặt vào `HATANG_API_KEY`.
2. Thêm và xác minh tên miền: thêm các bản ghi DKIM, SPF và return-path được liệt kê. Xem [Tên miền](https://hatang.dev/vi/docs/guides/email/domains.md).
3. Gửi. Theo dõi trạng thái bằng `emails.get(id)` hoặc [webhook](https://hatang.dev/vi/docs/guides/getting-started/webhooks.md) `email.delivered`, `email.bounced`.

## Tìm hiểu thêm

- Mọi trường, tệp đính kèm, hẹn giờ và gửi hàng loạt: [Gửi email](https://hatang.dev/vi/docs/guides/email/sending.md)
- Template dùng lại có biến: [Template](https://hatang.dev/vi/docs/guides/email/templates.md)
- Component React Email: truyền `react: <WelcomeEmail />` thay cho `html` ([SDK Node.js](https://hatang.dev/vi/docs/guides/sdks/node.md))
- Chuyển từ Resend, SendGrid hay Postmark: [Chuyển từ Resend](https://hatang.dev/vi/docs/guides/email/migrate-from-resend.md)

Source: https://hatang.dev/vi/docs/guides/recipes/send-email-nodejs
