Most email API tutorials end at the send call. You fire off a request, get a 200 back, and hope for the best. But in production, sending is the easy part. The hard part is knowing what happened next: Did it deliver? Did the recipient open it? Did it bounce? Did your domain get flagged?

In this tutorial, we will build a full-stack batch email dashboard that sends up to 1,000 emails in a single HTTP request and tracks every delivery lifecycle event in a real-time dashboard. By the end, you will have a working application with live KPI cards, a progress bar, a filterable event timeline, and a success/failure scenario toggle.

What We Will Build

The application has two parts:

  1. A Node.js server that calls the Telnyx Email API batch endpoint, stores events in SQLite, and pushes updates to connected browsers via Server-Sent Events.
  2. A browser dashboard that displays delivery rate, open rate, click rate, and bounce rate as live-updating KPI cards, with a timeline of individual events.

Here is the architecture:

 Dashboard (browser) | v +----------------+ POST /v2/email_messages/batch +------------------+ | Express API | ---------------------------------> | Telnyx Email | | + SQLite | <---------- webhooks -------------- | API | +-------+--------+ +------------------+ | +---> SSE stream ---> browser updates KPIs in real time 

The Telnyx Email API is part of the Telnyx AI Communications Infrastructure platform, which provides email, SMS, voice, and networking APIs through a single account and API key.

Prerequisites

  • Node.js 22+ (required for the built-in node:sqlite module)
  • A Telnyx account with an API key (sign up free)
  • ngrok (optional, for webhook delivery -- the app works without it via polling)

Step 1: Clone and Configure

git clone https://github.com/team-telnyx/telnyx-code-examples.git cd telnyx-code-examples/email-batch-send-nodejs cp .env.example .env 

Open .env and add your credentials:

TELNYX_API_KEY=KEY_your_api_key_here FROM_EMAIL=onboarding@msgtelnyx.com TO_EMAIL=your-verified-email@example.com PORT=3000 

Every Telnyx account has access to a shared sending domain (onboarding@msgtelnyx.com). It can send to your account's verified email address. If you have a verified custom domain, you can send to any recipient.

Step 2: Install and Run

npm install npm start 

That is it. One dependency (express). The server starts on http://localhost:3000 and prints your masked credentials:

Email Batch Demo running on http://localhost:3000 From: onboarding@msgtelnyx.com To: y***@e***.com Key: KEY_01234567... 

Step 3: Send a Batch

Open http://localhost:3000 in your browser. You will see the dashboard with a batch size input, a scenario toggle (success/failure), and a Send button.

Set the count to 10 and click Send Batch. The server builds a messages array and calls the Telnyx batch endpoint:

const response = await fetch("https://api.telnyx.com/v2/email_messages/batch", { method: "POST", headers: { Authorization: `Bearer ${TELNYX_API_KEY}`, "Content-Type": "application/json", "Idempotency-Key": batchId, }, body: JSON.stringify({ messages }), }); 

The API returns a 207 Multi-Status response. The data array contains accepted messages; the errors array contains rejections. This is the key difference from single-send endpoints -- you get per-message results in one response.

Step 4: Watch Events Stream In

As emails move through the delivery pipeline, events arrive via two paths:

  1. Webhooks (if configured): Telnyx posts events to POST /webhooks/email on your server
  2. Polling (always active): Every 5 seconds, the server checks GET /v2/email_messages/:id/events for pending messages

Both paths feed into the same event processor, which updates SQLite and publishes to SSE subscribers. The dashboard updates in real time -- you will see the delivery rate climb, then opens and clicks appear as you interact with the delivered emails.

How the Code Works

The entire server is a single server.js file. Let me walk through the key parts.

The Batch Endpoint

The POST /api/send-batch route accepts a count (1-1,000), a subject line, and a scenario toggle. It builds the messages array with open and click tracking enabled:

const messages = []; for (let i = 1; i <= count; i++) { messages.push({ from: { email: FROM_EMAIL, name: "Telnyx Email Batch Demo" }, to: [{ email: recipient }], subject: `${subject} (#${i} of ${count})`, html_body: `<h2>${subject}</h2><p>Message #${i} of ${count}</p>`, tracking_settings: { open_tracking: true, click_tracking: true }, tags: ["batch-demo", `batch-${batchId}`], }); } 

The Idempotency-Key header ensures that retrying the same batch UUID does not send duplicate emails. This matters in production when network failures cause ambiguous responses.

The Event State Machine

Email events have a natural ordering: queued -> sent -> delivered -> opened -> clicked. Terminal states (bounced, failed, complained) override everything. The server enforces this with a priority map:

const STATUS_PRIORITY = { queued: 0, sent: 1, delivered: 2, opened: 3, clicked: 4, bounced: 99, failed: 99, complained: 99, }; function shouldUpdateStatus(current, incoming) { const cur = STATUS_PRIORITY[current] ?? -1; const inc = STATUS_PRIORITY[incoming] ?? -1; if (cur >= 99) return false; // terminal -- no further updates return inc > cur; } 

This prevents out-of-order webhook delivery from regressing a message's status. If a "delivered" event arrives after an "opened" event (which happens more than you might expect), the message stays at "opened."

Server-Sent Events

SSE is the right tool here because the data flow is unidirectional -- server to client. No handshake upgrade, works through proxies, and the browser reconnects automatically on disconnect:

app.get("/stream", (req, res) => { res.set({ "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Accel-Buffering": "no", }); res.flushHeaders(); subscribers.push(res); const keepalive = setInterval(() => { res.write(": keepalive\n\n"); }, 30_000); req.on("close", () => { clearInterval(keepalive); subscribers.splice(subscribers.indexOf(res), 1); }); }); 

The 30-second keepalive comment frame prevents reverse proxies (nginx, Cloudflare) from closing idle connections.

The Polling Fallback

Webhooks require a publicly reachable URL, which is inconvenient during local development. The polling loop removes that requirement:

async function pollMessageStatuses() { const pending = db.prepare( "SELECT id, status FROM messages WHERE status NOT IN ('delivered','bounced','failed','complained') LIMIT 50" ).all(); for (const msg of pending) { const resp = await fetch( `https://api.telnyx.com/v2/email_messages/${msg.id}/events`, { headers: { Authorization: `Bearer ${TELNYX_API_KEY}` } } ); // process new events... } } setInterval(pollMessageStatuses, 5_000); 

It only polls messages that have not reached a terminal state, and it deduplicates against existing events in the database. When both webhooks and polling are active, you do not get double-counted events.

Historical Sync

The POST /api/sync endpoint pages through the Telnyx GET /v2/email_events API to backfill events that occurred before the server started. It auto-creates batch and message records for previously unknown messages, grouping them by subject line. This means you can restart the server and recover the full event history.

Failure Tracking

Toggle the scenario to "failure" and send a batch. The first message is addressed to bounce-test@invalid.example, which triggers a rejection. The dashboard shows the failed message alongside successful deliveries, so you can see how the system handles mixed results.

The 207 Multi-Status response separates successes from failures at the API level. Failed messages are recorded with synthetic IDs and appear in the event timeline immediately, before any webhook or poll cycle.

SQLite and Node 22

This demo uses the node:sqlite module that shipped in Node 22. It is a synchronous API (DatabaseSync) backed by the SQLite C library compiled into Node itself -- no native addon, no npm install step for the database. WAL (Write-Ahead Logging) mode enables concurrent reads while the event processor writes, which matters when the dashboard is polling for aggregate stats during a large batch.

import { DatabaseSync } from "node:sqlite"; const db = new DatabaseSync(path.join(dataDir, "email_batch.db")); db.exec("PRAGMA journal_mode = WAL"); 

The database file lives in ./data/ and survives server restarts. Delete it to start fresh.

FAQ

How many emails can I send in one batch?

The Telnyx batch endpoint accepts up to 1,000 messages per call. The demo caps input at 1,000 to match this limit.

Do I need to configure webhooks?

No. The polling fallback works without any webhook configuration. Webhooks are faster (sub-second event delivery vs. 5-second poll interval) but not required.

Can I send to multiple recipients?

Yes, but the shared domain (onboarding@msgtelnyx.com) can only send to your account's verified email. With a verified custom domain, you can send to any address.

What happens if I restart the server?

The SQLite database persists. Use the Sync button in the dashboard to backfill any events that arrived while the server was down.

Can I use this in production?

The code is production-safe in terms of error handling and idempotency. For production scale, you would want to add webhook signature verification, a job queue for large batches, and monitoring. The Telnyx Email API is production-ready -- the Telnyx AI Communications Infrastructure platform handles email delivery, reputation management, and compliance at scale.

Resources