mailcue
v0.2.0
Published
Official MailCue SDK for Node.js
Maintainers
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 mailcueRequires 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
