npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mailcue

v0.2.0

Published

Official MailCue SDK for Node.js

Readme

mailcue

Official Node.js / TypeScript SDK for MailCue, the open-source email testing and production server.

Build against MailCue locally in test mode, then point at your production deployment by changing one option. No code changes required.

Install

npm install mailcue

Requires Node.js 18 or newer (for native fetch). No runtime dependencies.

Quick start

import { Mailcue } from 'mailcue';

const mc = new Mailcue({
  apiKey: 'mc_your_api_key',
  baseUrl: 'http://localhost:8088',
});

const { messageId } = await mc.emails.send({
  from: '[email protected]',
  to: ['[email protected]'],
  subject: 'Welcome',
  html: '<h1>Hi</h1>',
});

console.log('queued', messageId);

Authentication

Either pass an API key (preferred for server-to-server) or a JWT bearer token:

const mc = new Mailcue({ apiKey: 'mc_...' });
// or
const mc = new Mailcue({ bearerToken: '...' });

Sending mail

import { readFileSync } from 'node:fs';

await mc.emails.send({
  from: '[email protected]',
  fromName: 'Example',
  to: ['[email protected]'],
  cc: ['[email protected]'],
  replyTo: '[email protected]',
  subject: 'Your invoice',
  html: '<p>Thanks for your order.</p>',
  attachments: [
    {
      filename: 'invoice.pdf',
      contentType: 'application/pdf',
      content: readFileSync('./invoice.pdf'),
    },
  ],
});

content accepts Buffer, Uint8Array, or string (UTF-8). The SDK base64-encodes it for you.

Reading mail

const inbox = await mc.emails.list({
  mailbox: '[email protected]',
  page: 1,
  pageSize: 50,
});

for (const summary of inbox.emails) {
  const detail = await mc.emails.get(summary.uid, { mailbox: summary.mailbox });
  console.log(detail.subject, detail.textBody);
}

await mc.emails.delete(inbox.emails[0].uid, { mailbox: '[email protected]' });

Waiting for an email (CI)

waitFor polls a mailbox until matching messages arrive, or rejects with a TimeoutError after timeoutMs. Filters (subject, from, to) are case-insensitive substrings on top of the server-side search.

const found = await mc.emails.waitFor({
  mailbox: '[email protected]',
  subject: 'Welcome',
  timeoutMs: 10000,
});
console.log(found.length);

Email validation and catch-all risk

const result = await mc.emails.validate('[email protected]');
console.log(result.provider?.name, result.mailbox.selectiveRecipientValidation);
console.log(result.catchAllRisk?.score, result.catchAllRisk?.recommendedAction);

A catch-all domain accepts every recipient at RCPT time, so no probe can prove that a mailbox exists. catchAllRisk.score is therefore a hard-bounce probability rather than a verdict: it starts from the receiving provider's rate, is refined by outcomes seen at that provider and domain, and is then adjusted for the local part and passive domain signals. contributions itemises every adjustment.

Validate a list together rather than one address at a time. Addresses sharing a domain reveal that domain's naming convention and any generated name variants, and targetBounceRate returns the largest subset whose blended expected bounce rate stays under the ceiling receivers actually judge you on.

const batch = await mc.emails.validateBatch({
  emails: addresses,
  targetBounceRate: 0.015,
});
console.log(batch.summary.catchAll, batch.selection?.projectedBounceRate);
const sendTo = batch.selection?.included ?? [];

Feed outcomes back so the estimates improve. A raw bounce can be handed over whole instead of being summarised by hand.

await mc.emails.recordValidationFeedback({
  email: '[email protected]',
  outcome: 'hard_bounce',
  smtpCode: 550,
  enhancedStatus: '5.1.1',
});
await mc.emails.ingestBounce(rawDsnMessage);

// Check that the published probabilities held up.
const report = await mc.emails.validationCalibration({ days: 90 });
console.log(report.brierScore, report.observedRate);

Staged sending

A message cannot be recalled once it leaves the MTA, so the only way to bound exposure on a catch-all domain is to not commit the whole batch at once. A staged send delivers a small sample first, watches the bounce window, and releases the rest only if the sample survived.

const canary = await mc.emails.createSendCanary({
  recipients: addresses,
  fromAddress: '[email protected]',
  subject: 'Quarterly update',
  body: '...',
  sampleSize: 2,
  holdMinutes: 15,
});
const state = await mc.emails.getSendCanary(canary.id);
console.log(state.status, state.decisionReason);

Mailboxes, domains, aliases, GPG, API keys, system

await mc.mailboxes.create({
  username: 'delivery-check',
  password: 'use-a-long-random-password',
  domain: 'example.com',
  purpose: 'deliverability',
});

const report = await mc.emails.scoreDeliverability('42', {
  mailbox: '[email protected]',
  folder: 'INBOX',
});
console.log(report.score, report.topRecommendations);
const run = await mc.emails.runDeliverabilityChecks('42', {
  mailbox: '[email protected]',
  checks: ['dns', 'links', 'visual'],
});
const history = await mc.deliverability.history('[email protected]');
await mc.deliverability.setBaseline(history.reports[0].id);
const stats = await mc.mailboxes.stats('[email protected]');

await mc.domains.create({ name: 'example.com' });
const dns = await mc.domains.verifyDns('example.com');

await mc.aliases.create({ sourceAddress: '[email protected]', destinationAddress: '[email protected]' });

const key = await mc.gpg.generate({ mailboxAddress: '[email protected]' });
const armored = await mc.gpg.exportPublic('[email protected]');

const created = await mc.apiKeys.create({ name: 'ci' });
console.log('save this once', created.key);

const health = await mc.system.health();

Streaming events (SSE)

for await (const event of mc.events.stream()) {
  if (event.type === 'email.received') {
    console.log('new mail in', event.data);
  }
}

Auto-reconnects with exponential backoff on disconnect. Pass an AbortSignal to cancel:

const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 60_000);

for await (const event of mc.events.stream({ signal: ctrl.signal })) {
  // ...
}

Errors

All errors extend MailcueError. Use instanceof to handle them granularly:

import { Mailcue, RateLimitError, ValidationError, AuthenticationError } from 'mailcue';

try {
  await mc.emails.send({ /* ... */ });
} catch (err) {
  if (err instanceof RateLimitError) {
    console.warn('rate limited, retry after', err.retryAfter, 'seconds');
  } else if (err instanceof ValidationError) {
    console.warn('bad input', err.body);
  } else if (err instanceof AuthenticationError) {
    console.error('check your api key');
  } else {
    throw err;
  }
}

Exported error classes: MailcueError, AuthenticationError, AuthorizationError, NotFoundError, ConflictError, ValidationError, RateLimitError, ServerError, NetworkError, TimeoutError.

Each carries status, code, requestId (when available), and the parsed response body.

Pointing at production

The baseUrl is the only thing that changes between environments:

const mc = new Mailcue({
  apiKey: process.env.MAILCUE_API_KEY!,
  baseUrl: process.env.MAILCUE_URL ?? 'http://localhost:8088',
});

Configuration

| Option | Default | Notes | | ------------- | ------------------------ | ---------------------------------------------- | | apiKey | (none) | Either this or bearerToken is required. | | bearerToken | (none) | JWT alternative to apiKey. | | baseUrl | http://localhost:8088 | Your MailCue server. | | timeout | 30000 | Per-request timeout in ms. | | maxRetries | 3 | Retries on 502 / 503 / 504 and network errors. | | fetch | globalThis.fetch | Inject a custom fetch (testing, proxies). | | userAgent | mailcue-node/<version> | Override the User-Agent header. |

License

MIT. See LICENSE. Source: https://github.com/Olib-AI/mailcue