How to Receive Email in Node.js: Read the Inbox, Save Attachments and Handle Webhooks

Receive email in Node.js and read it without IMAP: create an address, await a message, save attachments, and handle new mail in an Express webhook.

By · · 12 min read

Node.js code that waits for a message in a Mailcycle inbox with the TypeScript SDK

You want to receive email in Node.js: read a supplier’s invoice and save the PDF, pick a sign-in code out of a verification email in an end-to-end test, or hand a customer’s reply to your app. Nodemailer is the usual email package in Node, and it sends. Receiving means adding an IMAP client and a real mailbox with its password, or running an SMTP server of your own and parsing what it accepts. If what you want is “give my code an address and let it read what arrives”, an email API is shorter.

This tutorial shows how to receive and read email in Node.js with Mailcycle’s JavaScript and TypeScript SDK, the mailcycle-sdk package. You’ll create an address, list and open messages, save attachments to disk, await the next email, and then get new mail pushed to an Express route by webhook.

It is the receiving half of How to send email from Node.js and TypeScript, which covers sending, HTML, attachments you send and threaded replies. This one goes deep on the inbox.

Quick answer: how to receive email in Node.js

Install the package, sign in with your recovery phrase, create an address, and await waitFor(). It resolves when a message arrives, parsed and decrypted, with the sender, subject, text, HTML and attachments as plain properties.

npm install mailcycle-sdk
import { Mailcycle } from 'mailcycle-sdk';

const mc = await Mailcycle.signIn({ phrase: process.env.MAILCYCLE_PHRASE! });

const address = await mc.addresses.create({ prefix: 'inbound', label: 'Node inbox' });
console.log('Send an email to', address.emailAddress);

const message = await mc.messages.waitFor({ inboxId: address.id, timeoutMs: 300_000 });
console.log(message.from, message.subject);
console.log(message.text);

Save it as inbox.mjs or inbox.ts, run it, send an email to the address it prints from any mail app, and the script prints what you sent. The rest of this guide is what a real app needs around that: paging, attachments, push and errors.

Flow: a sender writes to your address, Mailcycle encrypts the mail on arrival, the TypeScript SDK lists, waits for or receives it by webhook, and your Node.js code reads the message
Mail sent to a Mailcycle address is encrypted on arrival, then your Node.js code reads it with the TypeScript SDK, by waiting for it or from a webhook.

Prerequisites

  • Node.js 20 or later, and 22 or later is recommended. Check with node --version.
  • A Mailcycle account. Receiving works on every plan when your code signs in with the recovery phrase. API keys and webhooks start at Operator. Pricing has the plans.
  • Your recovery phrase, in an environment variable named MAILCYCLE_PHRASE, for any process that opens mail.
  • Express, only for the webhook section: npm install express. Next.js, Hono and Fastify work the same way.

Step 1: Install the package

npm install mailcycle-sdk

Version 0.11.0 is current at the time of writing. It has no dependencies and ships its own type definitions, so your editor completes message. and TypeScript catches a misspelt field. It works the same from plain JavaScript.

Step 2: Sign in and create an address

Mailcycle.signIn({ phrase }) works on every plan. With an Operator plan or above you can also use an API key:

// client.ts
import { Mailcycle } from 'mailcycle-sdk';

const phrase = process.env.MAILCYCLE_PHRASE!;
const apiKey = process.env.MAILCYCLE_API_KEY;

export const mc = apiKey
  ? await Mailcycle.withApiKey({ apiKey, phrase })
  : await Mailcycle.signIn({ phrase });

An address that receives mail needs a public key the mail server can encrypt to. addresses.create() derives that key from your phrase and uploads only the public half, so it needs a client built with the phrase.

const address = await mc.addresses.create({
  prefix: 'invoices',
  label: 'Supplier invoices',
  retentionDays: 30,
});
console.log(address.emailAddress, address.id);

for (const existing of await mc.addresses.list()) {
  console.log(existing.emailAddress, existing.label, existing.receives ? 'receives' : 'no key yet');
}

The options on addresses.create():

  • prefix: 'invoices' gives invoices- plus a random ending on a shared domain.
  • style ('person', 'business', 'team' or 'neutral') rolls a name in that style, and mc.addresses.rollNames({ style }) lists some to choose from.
  • localPart asks for an exact name. Any name you type needs Scale or above, and so does domain with your own domain.
  • label is encrypted on your machine, so the server stores it as ciphertext.
  • retentionDays is 1 to 90, and 7 by default.

Save address.id, the ibx_... id: every reading call takes it.

Step 3: List and read emails in the inbox

mc.messages.list() returns one page of a folder, newest first:

const page = await mc.messages.list(address.id, { limit: 20 });
for (const message of page.messages) {
  const flag = message.read ? ' ' : '*';
  console.log(flag, message.receivedAt, message.from, message.subject);
}

if (page.nextCursor) {
  const older = await mc.messages.list(address.id, { limit: 20, cursor: page.nextCursor });
  console.log(older.messages.length, 'older messages on the next page');
}

limit goes up to 200, and 50 by default. nextCursor is opaque: pass it back as cursor as it came, and it is null on the last page. To walk a whole folder, a small generator does the paging:

// inbox.ts
import type { Message } from 'mailcycle-sdk';
import { mc } from './client.js';

export async function* inbox(addressId: string, folder: 'inbox' | 'sent' | 'junk' | 'trash' | 'starred' = 'inbox'): AsyncGenerator<Message> {
  let cursor: string | null = null;
  do {
    const page = await mc.messages.list(addressId, { folder, limit: 100, cursor });
    yield* page.messages;
    cursor = page.nextCursor;
  } while (cursor);
}

const invoices: Message[] = [];
for await (const message of inbox(process.env.MAILCYCLE_ADDRESS_ID!)) {
  if (message.subject.toLowerCase().includes('invoice') && message.attachments.length > 0) {
    invoices.push(message);
  }
}
console.log(invoices.length, 'invoices with files attached');

Message content is encrypted, so you decrypt and then filter in JavaScript, as above.

What is in a Message

Each Message is a plain object, already parsed from MIME and decrypted:

Property What it holds
id, inboxId The message’s msg_... id and the address it arrived at.
receivedAt When it arrived, as an ISO 8601 string in UTC.
from, fromName The sender’s address and display name.
replyTo Where a reply should go: the Reply-To header if set, otherwise From.
to, subject The recipient and the subject line.
text The plain-text body.
html The HTML body exactly as sent. Do not render this one.
safeHtml The HTML with remote images, trackers and embeds removed.
attachments An array of AttachmentInfo: index, filename, mimeType, size, contentId, stored.
messageId The sender’s Message-ID header, used to thread a reply.
read, starred, folder The message’s state.
opened false if it could not be decrypted: no phrase, or the wrong one.

A message that does not open comes back with opened set to false and empty content rather than throwing, so one bad message never hides the rest of a page.

Read the email body in Node.js: text, html and safeHtml

Most mail carries a plain-text and an HTML part. Use text for anything you parse, such as codes, order numbers or a reply to hand to a model. If you show the HTML anywhere, use safeHtml:

import { writeFile } from 'node:fs/promises';
import { mc } from './client.js';

const message = await mc.messages.get('msg_91be02c4a7d1');

if (!message.opened) {
  throw new Error('This message did not open: check the recovery phrase.');
}

console.log(message.text || '(no plain-text part)');

if (message.safeHtml) {
  await writeFile('preview.html', message.safeHtml, 'utf8');
}

messages.get() fetches one message by id, from any folder. safeHtml is the HTML the Mailcycle apps show: remote images, tracking pixels and embeds are taken out, so opening it does not tell the sender when you read it. If you embed it in a page of your own, put it in a sandboxed <iframe>.

Download email attachments in Node.js

Attachments are listed on the message and fetched one at a time. Their bodies are encrypted like the message, and mc.messages.attachment() opens them on your machine. This module saves a message’s files safely:

// attachments.ts
import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import type { Message } from 'mailcycle-sdk';
import { mc } from './client.js';

function safeName(filename: string): string {
  const name = path.basename(filename.replaceAll('\\', '/')).replace(/[^\w.\- ]/g, '_').trim();
  return name || 'attachment';
}

export async function saveAttachments(message: Message, folder = 'downloads'): Promise<string[]> {
  const target = path.join(folder, message.id);
  const saved: string[] = [];
  for (const attachment of message.attachments) {
    if (!attachment.stored) continue; // an empty part: nothing to fetch
    if (attachment.contentId) continue; // an image the HTML shows inline, like a logo

    const bytes = await mc.messages.attachment(message, attachment.index); // opened on this machine
    await mkdir(target, { recursive: true });
    const file = path.join(target, `${attachment.index}-${safeName(attachment.filename)}`);
    await writeFile(file, bytes);
    saved.push(file);
  }
  return saved;
}

Then process every unread message that has files, and mark each one read so the next run skips it:

import { saveAttachments } from './attachments.js';
import { mc } from './client.js';
import { inbox } from './inbox.js';

for await (const message of inbox(process.env.MAILCYCLE_ADDRESS_ID!)) {
  if (message.read || message.attachments.length === 0) continue;

  for (const file of await saveAttachments(message)) {
    console.log('saved', file);
  }
  await mc.messages.markRead(message.id);
}

The details that matter with real mail:

  • The file name comes from the sender. A name like ../../.env is a classic path-traversal trick. path.basename keeps the last path component, the character filter keeps the rest tame, and the index prefix keeps two files called invoice.pdf apart.
  • stored is false for a part that had no body. Skip it.
  • contentId marks an inline image, the kind HTML shows with <img src="cid:logo">. Most pipelines want the PDF, not the logo.
  • mimeType and size let you keep only application/pdf, or refuse anything over a size, before you download it.
  • Treat files as untrusted. Scan them, or open them in a sandbox, before anything else touches them.

That is the job a Node.js email parser does for attachments, without walking a MIME tree or decoding base64.

Wait for the next email in Node.js

mc.messages.waitFor() resolves when a matching message arrives, opened. It is the shortest way to read a verification email in an end-to-end test, or to wait for a reply:

import { MailcycleError } from 'mailcycle-sdk';
import { mc } from './client.js';

const started = new Date(); // take the time before the email is triggered

// ...trigger the email here: submit a sign-up form, call your own API...

try {
  const message = await mc.messages.waitFor({
    inboxId: address.id,
    subject: 'verify',
    since: started,
    timeoutMs: 120_000,
  });

  const code = message.text.match(/\b(\d{6})\b/)?.[1];
  console.log(code ? `code: ${code}` : `No code in: ${message.text.slice(0, 200)}`);
} catch (error) {
  if (error instanceof MailcycleError && error.code === 'timeout') {
    console.log('No verification email within two minutes.');
  } else {
    throw error;
  }
}

How it behaves:

  • since is the important one. Mail received from that moment on counts, even if it landed before the wait began. Take the time before you trigger the email, so a fast delivery cannot slip past. It defaults to now.
  • from and subject match text the sender or subject contains, ignoring case. inboxId limits the wait to one address.
  • timeoutMs is 60 seconds by default. When it runs out the promise rejects with a MailcycleError whose code is timeout.
  • signal takes an AbortSignal, so a test runner or a shutdown handler can stop the wait early.

For a test suite, give each test its own address and delete it afterwards with mc.addresses.delete(address.id). In Playwright, Vitest or Jest that is a beforeEach with create and an afterEach with delete. The same pattern in a browser test is in Test email verification with Playwright.

Mark as read, star, move and delete

These calls change state only, so they do not open any content:

Call What it does
mc.messages.markRead(id) Marks read. markRead(id, false) marks unread.
mc.messages.star(id) Stars it. star(id, false) unstars.
mc.messages.move(id, 'junk') Moves to 'inbox', 'junk' or 'trash'. 'restore' takes it back out of the trash.
mc.messages.delete(id) Deletes it now.
mc.messages.emptyTrash() Deletes everything in the trash and returns how many.

Get new email pushed to Express with a webhook

Mailcycle can tell your app the moment mail arrives. A message.received event carries the message’s id and its address’s id. Your code fetches the message by id and opens it locally, so the phrase stays on your machine.

Add a webhook in the app under API, on the Webhooks tab, or from Node.js with a signed-in session:

const { webhook, secret } = await mc.webhooks.create({
  url: 'https://example.com/hooks/mailcycle',
  events: ['message.received'],
  name: 'Inbound mail',
});
console.log(webhook.id, secret); // whsec_..., shown once: store it as MAILCYCLE_WEBHOOK_SECRET

The URL must be HTTPS. For local development, expose your dev server through a tunnel. Then the receiving route:

// server.ts
import express from 'express';
import { verifyWebhookSignature } from 'mailcycle-sdk';
import { saveAttachments } from './attachments.js';
import { mc } from './client.js';

const app = express();
const SECRET = process.env.MAILCYCLE_WEBHOOK_SECRET!;
const seen = new Set<string>(); // one process only: use Redis or a table with a unique key in production

async function handleMessage(messageId: string): Promise<void> {
  const message = await mc.messages.get(messageId); // fetched by id, opened here
  if (!message.opened) return;

  const saved = await saveAttachments(message);
  console.log(`${message.from}: ${message.subject} (${saved.length} files)`);
  await mc.messages.markRead(message.id);
}

// express.raw keeps the exact bytes, which the signature is computed over.
app.post('/hooks/mailcycle', express.raw({ type: 'application/json' }), async (req, res) => {
  const raw = (req.body as Buffer).toString('utf8');

  if (!(await verifyWebhookSignature(SECRET, raw, req.header('Mailcycle-Signature')))) {
    res.sendStatus(401);
    return;
  }

  const eventId = req.header('Mailcycle-Event-Id');
  if (eventId) {
    if (seen.has(eventId)) {
      res.sendStatus(204); // a retry of an event already handled
      return;
    }
    seen.add(eventId);
  }

  res.sendStatus(204); // answer fast, then do the work

  const event = JSON.parse(raw);
  if (event.type === 'message.received') {
    handleMessage(event.payload.messageId).catch((error) => console.error(error));
  }
});

app.listen(3000);

saveAttachments is the module from the attachments section. What each part is for:

  • The signature is an HMAC-SHA256 of the timestamp and the raw body, keyed with your whsec_ secret. verifyWebhookSignature checks it and refuses a timestamp more than five minutes old. Check the body as it arrived: a body that was parsed and re-serialised will not match, which is why the route uses express.raw() rather than express.json().
  • Answer fast. Mailcycle waits 10 seconds for a 2xx. The route replies first and does the fetching and saving afterwards.
  • Deduplicate. An event can arrive more than once, and Mailcycle-Event-Id is the same on every attempt. The Set suits one process. With several instances, insert the id into a table with a unique constraint, or SET NX it in Redis.
  • Fetch-style frameworks such as Next.js route handlers, Hono and Cloudflare Workers read the body with await request.text() and pass it straight to verifyWebhookSignature.

Retries, the delivery log and every event type are in the webhooks guide, and Receive email with a webhook walks through the receiver in more depth.

Nodemailer, an IMAP client and an email API in Node.js

Nodemailer sends through an SMTP transport you provide. To read a mailbox you add an IMAP client such as imapflow, a host, port 993 and credentials, then parse each message’s source with a MIME parser. That is the right tool when the mail already lives in a mailbox you own, like a shared support inbox, and your code needs to read it where it is.

An email API fits when your code needs addresses of its own: one per customer, per test run or per agent, created in code, with mail pushed to you as it arrives.

IMAP client such as imapflow Mailcycle Node.js SDK
Install npm install imapflow plus a MIME parser npm install mailcycle-sdk
You need An IMAP mailbox and its credentials A recovery phrase, plus an API key if you want one
New addresses Made at your mail provider mc.addresses.create() in code
Parsing Raw MIME, parsed by you Parsed fields: text, html, attachments
Tracker-free HTML Strip it yourself safeHtml
Attachments Walk the MIME parts mc.messages.attachment(message, index)
New-mail push IMAP IDLE Webhooks and mc.events.stream()
Wait for one email Write the loop yourself waitFor()
Runs on Node.js Node.js, Deno, Bun, Cloudflare Workers and browsers
Mail at rest Depends on the provider Encrypted with keys from your recovery phrase

Fan out with Promise.all

Node waits on I/O without blocking, so many addresses can be waited on at once with no threads to manage. Create one address per job, trigger each email, then await all the messages together.

const jobs = ['alpha', 'bravo', 'charlie'];
const results = await Promise.all(
  jobs.map(async (job) => {
    const address = await mc.addresses.create({ prefix: job, retentionDays: 1 });
    const since = new Date();
    await triggerEmail(job, address.emailAddress);
    const message = await mc.messages.waitFor({ inboxId: address.id, since, timeoutMs: 60_000 });
    return [job, message.text.match(/\b\d{6}\b/)?.[0]] as const;
  }),
);
console.log(Object.fromEntries(results));

If you start hundreds, limit the concurrency with a small helper or a package such as p-limit, so you stay inside the API rate limit.

A Vitest test for a sign-up email

Vitest and Jest both support async tests and beforeEach hooks, so the address lifecycle is a few lines:

import { beforeEach, afterEach, expect, test } from 'vitest';

let address: Awaited<ReturnType<typeof mc.addresses.create>>;
beforeEach(async () => { address = await mc.addresses.create({ prefix: 'vitest', retentionDays: 1 }); });
afterEach(async () => { await mc.addresses.delete(address.id); });

test('sign-up sends a six digit code', async () => {
  const since = new Date();
  await signUp(address.emailAddress);
  const message = await mc.messages.waitFor({ inboxId: address.id, since, subject: 'verify', timeoutMs: 60_000 });
  expect(message.text).toMatch(/\b\d{6}\b/);
}, 90_000);

Raise the test timeout above the wait timeout, as the last argument does, so the wait fails with a clear timeout error before the runner gives up.

A Next.js route handler for incoming mail

If your app runs on Next.js, the webhook receiver is a route handler. Read the raw body with await request.text(), check the signature against it, then fetch and open the message by id.

export async function POST(request: Request) {
  const raw = await request.text();
  if (!(await verifyWebhookSignature(SECRET, raw, request.headers.get('Mailcycle-Signature')))) {
    return new Response(null, { status: 401 });
  }
  const event = JSON.parse(raw);
  if (event.type === 'message.received') {
    const message = await mc.messages.get(event.payload.messageId);
    await enqueue(message.subject);
  }
  return new Response(null, { status: 200 });
}

Return a 200 quickly and do the slow work on a queue, so Mailcycle does not retry a delivery that already succeeded.

Edge runtimes and Bun

The SDK has no dependencies and uses fetch and WebCrypto, so the same code runs in Deno, Bun and Cloudflare Workers as well as Node 20 or later. In a Worker, keep the phrase in a secret binding and build the client per request or cache it in module scope. Everything above except the Vitest file works unchanged.

Streams and async iteration

For a service that processes mail as it arrives, an async generator keeps the loop readable. Each pass waits for the next message after the last one handled, and the since value moves forward with it.

async function* incoming(address: { id: string }) {
  let since = new Date();
  while (true) {
    try {
      const message = await mc.messages.waitFor({ inboxId: address.id, since, timeoutMs: 55_000 });
      since = new Date(message.receivedAt);
      yield message;
    } catch (error) {
      if (!(error instanceof MailcycleError && error.code === 'timeout')) throw error;
    }
  }
}

for await (const message of incoming(address)) {
  await handle(message);
}

A timeout is the quiet case, so the loop swallows it and waits again. Stop the loop with a break, or pass an AbortSignal through your own wrapper, when the process shuts down. For a pure push model, use the webhook route above instead of holding a wait open.

Troubleshooting

  • A webhook is retried and handled twice. Answer within 10 seconds and queue the slow work, then ignore an event id you have already seen.
  • A script finds the wrong email. Take since before the action that sends the mail, never after it.
  • Messages have opened set to false and empty fields. The client has no phrase, or a phrase from a different account. Build it with Mailcycle.signIn({ phrase }).
  • Nothing arrives at a new address. Check address.receives in mc.addresses.list(), and check the sender used the exact address, since prefixed names have a random ending.
  • MailcycleError with code of rate_limited (429). You are reading too much too fast. Back off, read only what is new, or switch to webhooks.
  • A 404 fetching an attachment. The part has stored set to false. Skip it.
  • The webhook route returns 401 for real deliveries. You are verifying a parsed body, or the wrong secret. Use express.raw() and the whsec_ secret of this webhook.

Every error code is listed in Errors.

Reply from Node.js, or hand the inbox to an agent

To answer a message in the same thread, pass it as replyTo to mc.messages.send(). Sending email from Node.js covers that, along with the plans that send.

If an AI agent should read the inbox, Mailcycle also runs as an MCP server with tools such as wait_for_message, read_message and read_attachment, for Claude Code, Cursor, Codex or any other MCP client. Start with Give your AI agent its own email inbox.

Next steps

FAQ

How do I receive email in Node.js?

Give your code an address that receives mail, then read it with a client. With Mailcycle, run npm install mailcycle-sdk, sign in with Mailcycle.signIn({ phrase }), create an address with mc.addresses.create(), and await mc.messages.waitFor(). The message comes back parsed and decrypted: sender, subject, text, HTML and attachments.

Can Nodemailer receive email?

Nodemailer sends mail through an SMTP transport and does not read a mailbox. To receive in Node.js you add an IMAP client and a real mailbox, run an SMTP server of your own, or use an email API. With Mailcycle you create an address in code and read what arrives over HTTPS.

How do I read emails from an inbox in Node.js?

Call mc.messages.list(address.id, { limit: 20 }) for one page, newest first, and pass nextCursor back as cursor for the next. Each Message has from, subject, text, safeHtml, attachments and read. Pass folder: 'junk', 'trash', 'sent' or 'starred' to read another folder.

How do I download email attachments in Node.js?

Each Message lists its files in message.attachments, with filename, mimeType, size and index. Call mc.messages.attachment(message, attachment.index) to get a Uint8Array, opened on your machine, and write it with fs.writeFile. Clean the file name first with path.basename, because it comes from the sender.

How can a Node.js script wait for a new email?

Call await mc.messages.waitFor({ inboxId, subject, since, timeoutMs }). It resolves with the first matching message. If nothing matches in time it rejects with a MailcycleError whose code is timeout, and an AbortSignal stops the wait early.

How do I get notified when an email arrives in an Express app?

Add a webhook for message.received, point it at a route that reads the raw body with express.raw(), and check each delivery with verifyWebhookSignature(). The event carries the message id, so fetch the message with mc.messages.get(). Webhooks are on the Operator plan and above.

Does it work on Cloudflare Workers, Deno and Bun?

Yes. The package needs only fetch and WebCrypto and has no dependencies, so the same code runs on Node.js 20 or later, Deno, Bun, Cloudflare Workers and in browsers.

Why does the Node.js client need my recovery phrase?

Mail is encrypted the moment it arrives, with keys from your recovery phrase. The client derives the same keys on your machine with WebCrypto and opens each message in your process. A message that does not open comes back with opened set to false.

Receive email in code