# Node.js

> Send your first email from Node.js using the global fetch and the MailBlastr API.

MailBlastr does not ship an SDK — you send email by making an HTTP request to `https://api.mailblastr.com/emails`. Node.js 18+ has a global `fetch`, so no dependencies are required.

## Prerequisites

- A MailBlastr [API key](https://www.mailblastr.com/docs/api-keys/overview).
- A [verified domain](https://www.mailblastr.com/docs/domains/managing) to send from.
- Node.js 18 or newer (for the built-in `fetch`).

## 1. Set your API key

Store your API key in a `.env` file and load it however your app already does (for example with `node --env-file=.env`, available in Node.js 20+).

**.env**

```sh
MAILBLASTR_API_KEY=mb_xxxxxxxxx
```

## 2. Send email using HTML

The easiest way to send an email is with the `html` field.

**fetch (ESM)**

```js
// server.js
const res = await fetch('https://api.mailblastr.com/emails', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.MAILBLASTR_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    from: 'Acme <onboarding@yourdomain.com>',
    to: ['delivered@example.com'],
    subject: 'Hello World',
    html: '<strong>It works!</strong>',
  }),
});

if (!res.ok) {
  console.error(await res.json());
} else {
  const { id } = await res.json();
  console.log({ id }); // { id: '49a3999c-...' }
}
```

**https (no fetch)**

```js
// server.js — for runtimes without a global fetch
import https from 'node:https';

const body = JSON.stringify({
  from: 'Acme <onboarding@yourdomain.com>',
  to: ['delivered@example.com'],
  subject: 'Hello World',
  html: '<strong>It works!</strong>',
});

const req = https.request('https://api.mailblastr.com/emails', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.MAILBLASTR_API_KEY}`,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(body),
  },
}, (res) => {
  let data = '';
  res.on('data', (chunk) => (data += chunk));
  res.on('end', () => console.log(res.statusCode, data));
});

req.write(body);
req.end();
```

## Idempotency

To make a retry safe, add an `Idempotency-Key` header so the same logical send is processed only once. See [Idempotency keys](https://www.mailblastr.com/docs/emails/idempotency).

```js
await fetch('https://api.mailblastr.com/emails', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.MAILBLASTR_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': 'welcome-user/123456789',
  },
  body: JSON.stringify({ /* ... */ }),
});
```

> **Note:** Idempotency keys are remembered for 24 hours and should be unique per logical send.
