# Send email with Node.js (/docs/guides/send-email-nodejs)

The `coss` package sends email from Node.js 22 or later over HTTPS. It has zero dependencies, is
ESM-only (use `import`), and returns `{ data, error }` instead of throwing.

## Install the SDK [#install-the-sdk]

```package-install
coss
```

Create an API key in the dashboard, in your project's **Development** environment, and make it
available as `COSS_API_KEY`, for example in a `.env` file that you load with
`node --env-file=.env`:

```sh title=".env"
COSS_API_KEY=coss_test_...
```

`npx coss-cli init` does both steps for you: it approves a development key in the dashboard, writes
it to `.env` and installs the SDK ([CLI](/docs/cli#set-a-project-up)).

## Create the client [#create-the-client]

`new Coss()` reads `COSS_API_KEY` from the environment. Create one client and reuse it:

```ts twoslash title="coss.mjs"
import { Coss } from "coss";

export const coss = new Coss();
// or: new Coss({ apiKey: process.env.COSS_API_KEY })
```

## Send an email [#send-an-email]

```ts twoslash title="send.mjs"
import { Coss } from "coss";

const coss = new Coss();

const { data, error } = await coss.email.send({
  from: "Acme <hello@acme.com>",
  to: "ada@example.com",
  subject: "Your order has shipped",
  html: "<p>Your order is on its way.</p>",
  text: "Your order is on its way.",
});

if (error) {
  console.error(error.code, error.message);
} else {
  console.log(data.id, data.status);
}
```

`to`, `cc`, `bcc` and `reply_to` take one address or an array, as `"ada@example.com"` or
`"Ada Lovelace <ada@example.com>"`. The email comes back `queued` and is handed to the delivery
provider moments later. API and network failures are returned as `error`, never thrown, and the
SDK retries the temporary ones itself ([errors and retries](/docs/sdk/errors)).

## Test with a development key, send live from your domain [#test-with-a-development-key-send-live-from-your-domain]

Development keys start with `coss_test_`: emails are recorded but never delivered, any `from`
address works, and `bounce@simulator.amazonses.com` simulates a bounce
([sandbox behaviour](/docs/environments#sandbox-behaviour)). To deliver real email, use a
`coss_live_` key from the **Production** environment and send from a domain your organization has
[verified](/docs/email/domains). Sending from any other domain returns `domain_not_verified`.

## Send attachments [#send-attachments]

Attachments are base64 in `attachments`. coss.com never fetches files from a URL, so read them
yourself:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
import { readFile } from "node:fs/promises";

const pdf = await readFile("invoice-1042.pdf");

const { data, error } = await coss.email.send({
  from: "Acme Billing <billing@acme.com>",
  to: "ada@example.com",
  subject: "Invoice 1042",
  text: "Your invoice is attached.",
  attachments: [{ filename: "invoice-1042.pdf", content: pdf.toString("base64") }],
});
```

Every `filename` needs an extension, and `content_type` defaults from it. A `content_id` makes an
attachment inline, for `<img src="cid:…">` in `html`. See [attachments](/docs/email/sending#attachments)
for the limits and blocked file types.

## Schedule an email [#schedule-an-email]

Pass `scheduled_at`, an ISO 8601 timestamp with a time zone offset, up to 30 days ahead:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000);

const { data: email } = await coss.email.send({
  from: "Acme <hello@acme.com>",
  to: "ada@example.com",
  subject: "Your trial ends tomorrow",
  text: "Pick a plan to keep your projects.",
  scheduled_at: tomorrow.toISOString(),
});

// Changed your mind?
if (email) await coss.email.cancel(email.id);
```

Until it is sent, move it with `coss.email.reschedule(id, { scheduled_at })` or cancel it. See
[scheduling](/docs/email/sending#scheduling-rescheduling-and-cancellation).

## Send emails in a batch [#send-emails-in-a-batch]

`coss.email.sendBatch()` sends up to 100 emails in one request, each with its own sender,
recipients and content:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const users = [
  { name: "Ada", email: "ada@example.com" },
  { name: "Grace", email: "grace@example.com" },
];

const { data, error } = await coss.email.sendBatch(
  users.map((user) => ({
    from: "Acme <notifications@acme.com>",
    to: user.email,
    subject: "Your weekly summary",
    html: `<p>Hi ${user.name}, here is your week.</p>`,
  })),
  { idempotencyKey: "weekly-summary-2026-11-16" },
);

console.log(data?.data.map((email) => email.id));
```

A batch is all or nothing: if one email is invalid, none is sent, and `error.issues` names it by
position, such as `emails.1.to`. For larger lists, send several batches, each with its own key.

## Send email from an Express route [#send-email-from-an-express-route]

Call the SDK from your handler and answer once the email is accepted:

```ts twoslash title="server.mjs"
// @filename: node_modules/express/index.d.ts
declare namespace express {
  interface Request {
    body: any;
  }
  interface Response {
    status(code: number): Response;
    json(body: unknown): void;
  }
  interface Application {
    use(handler: unknown): void;
    post(path: string, handler: (req: Request, res: Response) => unknown): void;
    listen(port: number): void;
  }
  function json(): unknown;
}
declare function express(): express.Application;
export default express;
// @filename: server.ts
// ---cut---
import express from "express";
import { Coss } from "coss";

const app = express();
const coss = new Coss();
app.use(express.json());

app.post("/password-reset", async (req, res) => {
  const { email, token } = req.body;

  const { error } = await coss.email.send(
    {
      from: "Acme <security@acme.com>",
      to: email,
      subject: "Reset your password",
      text: `Reset your password: https://acme.com/reset?token=${token}`,
      category: "account",
    },
    { idempotencyKey: `password-reset-${token}` },
  );

  if (error) {
    console.error(error.code, error.request_id);
    return res.status(502).json({ error: "Could not send the email" });
  }
  res.status(202).json({ ok: true });
});

app.listen(3000);
```

The idempotency key makes a retried request safe: for 24 hours, a send with the same key returns
the original email instead of sending another ([idempotency](/docs/api-reference/idempotency)).

## Already using Nodemailer? [#already-using-nodemailer]

Keep your `sendMail` calls and swap the transport for `coss/nodemailer`. It sends over HTTPS, so it
also works where outgoing SMTP ports are blocked:

```ts twoslash
import nodemailer from "nodemailer";
import { cossTransport } from "coss/nodemailer";

const transporter = nodemailer.createTransport(cossTransport());

await transporter.sendMail({
  from: '"Acme" <hello@acme.com>',
  to: "ada@example.com",
  subject: "Your receipt",
  text: "Thanks for your order.",
});
```

See [Nodemailer](/docs/integrations/nodemailer) for options and the supported fields.

## Check delivery [#check-delivery]

Each recipient has its own delivery status. Read it with `coss.email.get()`, or add a
[webhook endpoint](/docs/webhooks) to be told when it changes:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data: email } = await coss.email.get("email_01k7c8m4q2f3e9v6t5r1n0p8yz");

for (const recipient of email?.recipients ?? []) {
  console.log(recipient.address, recipient.status);
}
```

## Next steps [#next-steps]

- [Sending email](/docs/email/sending): every send option, including tags, categories and React Email
- [Delivery status](/docs/email/delivery): what each email and recipient status means
- [Verifying webhooks](/docs/sdk/webhooks) with `verifyWebhook`
- [Templates](/docs/email/templates): keep subjects and bodies in coss.com
- [Send email from Next.js](/docs/guides/send-email-nextjs)
