best-tempmail
v1.0.0
Published
Disposable email inboxes for automated testing. Create inboxes, wait for mail, extract verification codes.
Downloads
66
Maintainers
Readme
best-tempmail
Disposable email inboxes for automated testing. Create an inbox, wait for mail, pull out the verification code.
Built for signup flows, password resets, and anything else where a test needs to receive a real email.
npm install best-tempmailQuick start
No API key needed to try it. The free tier is keyless.
import { TempMail } from "best-tempmail";
const client = new TempMail();
const inbox = await client.createInbox();
console.log(inbox.address); // [email protected]
// trigger your signup flow with that address, then:
const message = await client.waitForMessage(inbox.address, { timeout: 55 });
console.log(message?.subject);Getting the verification code
The usual reason to receive email in a test is to read a code out of it. Rather than writing a regex for every service's format, ask for the code:
const client = new TempMail({ apiKey: process.env.BTM_API_KEY });
const inbox = await client.createInbox();
await signUpWithEmail(inbox.address);
const result = await client.waitForOtp(inbox.address, { timeout: 55 });
await enterCode(result!.code);code is null when nothing scored highly enough to be trusted. That is deliberate: a wrong code fails a test in a way that is hard to trace, so the API returns nothing rather than a guess. Check candidates if you want to see what else was considered.
Playwright example
import { test, expect } from "@playwright/test";
import { TempMail } from "best-tempmail";
const mail = new TempMail({ apiKey: process.env.BTM_API_KEY });
test("user can sign up and verify their email", async ({ page }) => {
const inbox = await mail.createInbox();
await page.goto("/signup");
await page.fill("#email", inbox.address);
await page.click("#submit");
const otp = await mail.waitForOtp(inbox.address, { timeout: 55 });
expect(otp?.code).toBeTruthy();
await page.fill("#code", otp!.code!);
await page.click("#verify");
await expect(page.locator("#welcome")).toBeVisible();
});Waiting for mail
waitForMessage holds one connection open until mail arrives, instead of polling in a loop. It returns null on timeout rather than throwing, because nothing has gone wrong: the mail just has not arrived yet.
const message = await client.waitForMessage(inbox.address, {
timeout: 55, // seconds, capped at 55 by the server
since: lastSeenId, // optional: return the first message that is not this one
});
if (message === null) {
// nothing arrived in time
}Without since, anything already in the inbox when the call starts is treated as seen, so you only get genuinely new mail.
Reading messages
const messages = await client.getMessages(inbox.address); // newest first
const full = await client.getMessage(inbox.address, messages[0].id);
full.subject;
full.text;
full.html;
full.attachments; // metadata on every planAttachments
Metadata is available on every plan. Downloading the bytes needs Pro.
const message = await client.getMessage(inbox.address, id);
for (const att of message.attachments) {
console.log(att.filename, att.size, att.downloadable);
if (att.downloadable) {
const file = await client.downloadAttachment(inbox.address, id, att.index);
fs.writeFileSync(file.filename, file.content);
}
}Attachments are addressed by index, not by id: ids are regenerated on every read and do not survive a round trip.
Webhooks
Rather than asking for mail, have it pushed to you.
const { url, secret } = await client.registerWebhook("https://your-server.com/hooks/mail");
// store `secret`: it is shown once, and you need it to verify deliveriesThen verify what arrives. Verify before trusting it. A webhook endpoint is a public URL that receives verification codes, and without a signature check anyone who learns the URL can post fabricated mail to it.
import express from "express";
import { parseWebhook } from "best-tempmail";
app.post("/hooks/mail",
express.raw({ type: "application/json" }), // keep the raw bytes
(req, res) => {
const event = parseWebhook({
payload: req.body,
signature: req.headers["x-btm-signature"] as string,
timestamp: req.headers["x-btm-timestamp"] as string,
secret: process.env.BTM_WEBHOOK_SECRET!,
});
console.log(event.address, event.message.subject);
res.sendStatus(200);
});The raw body matters: the signature covers the exact bytes that were sent, so re-serialising a parsed object will never match.
parseWebhook throws when verification fails, so an unverified payload cannot be used by accident. Use verifyWebhookSignature instead if you would rather handle the failure yourself.
Errors
Errors are typed, because the right reaction differs.
import {
RateLimitError, PaymentRequiredError,
NotFoundError, AuthenticationError, TimeoutError,
} from "best-tempmail";
try {
await client.getOtp(address, id);
} catch (err) {
if (err instanceof RateLimitError) {
await sleep((err.retryAfter ?? 60) * 1000); // worth retrying
} else if (err instanceof PaymentRequiredError) {
console.error(`Needs a higher plan. Currently on ${err.plan}.`); // retrying will not help
} else if (err instanceof NotFoundError) {
// inbox or message is gone, or expired
} else {
throw err;
}
}Network errors, timeouts, 429 and 5xx are retried automatically with backoff. Refusals (401, 402, 404) are not: the request was understood, and repeating it only wastes quota.
Rate limits
The most recent response's limits are always available:
await client.getDomains();
console.log(client.rateLimit);
// { limit: 2000, remaining: 1996, reset: 1788000000 }Plans
| | Free | Founders / Developer | Pro | | --- | :-: | :-: | :-: | | Requests/hour | 150 | 2,000 | 5,000 | | Inbox creation | 3/day per IP | unlimited | unlimited | | Inbox lifetime | 2 hours | 2 hours | 24 hours | | Polling, wait, WebSocket | yes | yes | yes | | Webhooks | no | yes | yes | | OTP extraction | no | yes | yes | | Attachment downloads | no | no | yes | | Concurrent waits | 5 | 5 | 20 | | Commercial use | no | yes | yes |
The free tier needs no key at all. See pricing.
Configuration
const client = new TempMail({
apiKey: "btm_sk_live_...", // omit for the free tier
timeout: 30000, // per request, ms
maxRetries: 2, // 0 disables retrying
headers: {}, // sent with every request
});API reference
| Method | Plan |
| --- | --- |
| getDomains() | any |
| health() | any |
| createInbox({ username?, domain? }) | any |
| getInbox(address) | any |
| deleteInbox(address) | any |
| getMessages(address, limit?) | any |
| getMessage(address, id) | any |
| waitForMessage(address, { timeout?, since? }) | any |
| getOtp(address, id) | paid |
| waitForOtp(address, { timeout? }) | paid |
| downloadAttachment(address, id, index) | Pro |
| registerWebhook(url) | paid |
| getWebhook() | paid |
| deleteWebhook() | paid |
Full API documentation: best-tempmail.com/api OpenAPI spec: api.best-tempmail.com/v1/openapi.json
Requirements
Node 18 or later, for built-in fetch.
License
MIT
