TypeScript Examples
Using the mail-catcher API with TypeScript and fetch.
These examples use the built-in fetch API available in Node.js 18+, Bun, and Deno.
Setup
const API_URL = process.env.API_URL!;
const TOKEN = process.env.TOKEN!;
const headers = {
Authorization: `Bearer ${TOKEN}`,
};List emails in an inbox
const response = await fetch(
`${API_URL}/v1/emails?inbox=test`,
{ headers }
);
const { emails, nextCursor, hasMore } = await response.json();
console.log(`Found ${emails.length} emails`);Wait for an email (long-poll)
const response = await fetch(
`${API_URL}/v1/emails?inbox=test&wait=true&timeout=15`,
{ headers }
);
const { emails } = await response.json();
if (emails.length > 0) {
console.log(`Received: ${emails[0].subject}`);
} else {
console.log("No emails arrived within timeout");
}Find a specific email by subject
const response = await fetch(
`${API_URL}/v1/emails?inbox=test&subject=Verify&wait=true`,
{ headers }
);
const { emails } = await response.json();
const verification = emails.find((e: { subject: string }) =>
e.subject.includes("Verify your account")
);
if (verification) {
const match = verification.htmlBody.match(/href="([^"]+)"/);
const verificationUrl = match?.[1];
console.log(`Verification URL: ${verificationUrl}`);
}Paginate through all emails
async function getAllEmails(inbox: string) {
const all: unknown[] = [];
let cursor: string | undefined;
do {
const url = new URL(`${API_URL}/v1/emails`);
url.searchParams.set("inbox", inbox);
url.searchParams.set("limit", "100");
if (cursor) url.searchParams.set("cursor", cursor);
const response = await fetch(url, { headers });
const data = await response.json();
all.push(...data.emails);
cursor = data.nextCursor;
} while (cursor);
return all;
}
const emails = await getAllEmails("test");
console.log(`Total: ${emails.length} emails`);Delete all emails in an inbox
const response = await fetch(
`${API_URL}/v1/emails?inbox=test`,
{ method: "DELETE", headers }
);
const { deleted } = await response.json();
console.log(`Deleted ${deleted} emails`);Download raw email
const response = await fetch(
`${API_URL}/v1/emails/abc123@mail.example.com/raw`,
{ headers, redirect: "follow" }
);
const emlContent = await response.text();
console.log(emlContent);Error handling
async function fetchEmails(inbox: string) {
const response = await fetch(
`${API_URL}/v1/emails?inbox=${inbox}`,
{ headers }
);
if (!response.ok) {
const { error } = await response.json();
throw new Error(`API error: ${error} (${response.status})`);
}
return response.json();
}