Skip to content

Inbox API

The Inbox class represents a single email inbox in VaultSandbox. It provides methods for managing emails, waiting for new messages, and monitoring in real-time.

emailAddress: string;

The email address for this inbox. Use this address to send test emails.

const inbox = await client.createInbox();
console.log(`Send email to: ${inbox.emailAddress}`);
// Use in your application
await sendWelcomeEmail(inbox.emailAddress);

inboxHash: string;

Unique identifier for this inbox. Used internally for API operations.

console.log(`Inbox ID: ${inbox.inboxHash}`);

expiresAt: Date;

The date and time when this inbox will expire and be automatically deleted.

const inbox = await client.createInbox();
console.log(`Inbox expires at: ${inbox.expiresAt.toISOString()}`);
const timeUntilExpiry = inbox.expiresAt.getTime() - Date.now();
console.log(`Time remaining: ${Math.round(timeUntilExpiry / 1000)}s`);

Lists all emails in the inbox with full content. Emails are automatically decrypted. This method fetches all email content in a single efficient API call.

listEmails(): Promise<Email[]>

Promise<Email[]> - Array of decrypted email objects with full content (text, html, attachments, etc.)

const emails = await inbox.listEmails();
console.log(`Inbox has ${emails.length} emails`);
emails.forEach((email) => {
console.log(`- ${email.subject} from ${email.from}`);
console.log(` Body: ${email.text?.substring(0, 100)}...`);
});

Lists all emails in the inbox with metadata only (no content). Use this for efficient listing when you only need basic email information.

listEmailsMetadataOnly(): Promise<EmailMetadata[]>

Promise<EmailMetadata[]> - Array of email metadata objects

interface EmailMetadata {
id: string;
from: string;
subject: string;
receivedAt: Date;
isRead: boolean;
}
// Quickly list emails without fetching full content
const emails = await inbox.listEmailsMetadataOnly();
console.log(`Inbox has ${emails.length} emails`);
emails.forEach((email) => {
console.log(`- ${email.subject} from ${email.from}`);
console.log(` Received: ${email.receivedAt.toISOString()}`);
console.log(` Read: ${email.isRead}`);
});
// Fetch full content for a specific email if needed
const fullEmail = await inbox.getEmail(emails[0].id);
console.log(`Body: ${fullEmail.text}`);
  • Displaying email lists in a UI
  • Checking for new emails before fetching content
  • Reducing bandwidth when full content isn’t needed

Retrieves a specific email by ID.

getEmail(emailId: string): Promise<Email>
  • emailId: The unique identifier for the email

Promise<Email> - The decrypted email object

const emails = await inbox.listEmails();
const firstEmail = await inbox.getEmail(emails[0].id);
console.log(`Subject: ${firstEmail.subject}`);
console.log(`Body: ${firstEmail.text}`);
  • EmailNotFoundError - Email does not exist

Waits for an email matching specified criteria. This is the recommended way to handle email arrival in tests.

waitForEmail(options: WaitOptions): Promise<Email>
interface WaitOptions {
timeout?: number;
pollInterval?: number;
subject?: string | RegExp;
from?: string | RegExp;
predicate?: (email: Email) => boolean;
}
PropertyTypeDefaultDescription
timeoutnumber30000Maximum time to wait in milliseconds
pollIntervalnumber2000Polling interval in milliseconds
subjectstring | RegExp-Filter by email subject
fromstring | RegExp-Filter by sender address
predicate(email: Email) => boolean-Custom filter function

Promise<Email> - The first email matching the criteria

// Wait for any email
const email = await inbox.waitForEmail({ timeout: 10000 });
// Wait for email with specific subject
const email = await inbox.waitForEmail({
timeout: 10000,
subject: /Password Reset/,
});
// Wait for email from specific sender
const email = await inbox.waitForEmail({
timeout: 10000,
});
// Wait with custom predicate
const email = await inbox.waitForEmail({
timeout: 15000,
predicate: (email) => email.to.includes('[email protected]'),
});
// Combine multiple filters
const email = await inbox.waitForEmail({
timeout: 10000,
subject: /Welcome/,
from: /noreply@/,
predicate: (email) => email.links.length > 0,
});
  • TimeoutError - No matching email received within timeout period

Waits until the inbox has at least the specified number of emails. More efficient than using arbitrary timeouts when testing multiple emails.

waitForEmailCount(count: number, options?: WaitForCountOptions): Promise<void>
  • count: Minimum number of emails to wait for
interface WaitForCountOptions {
timeout?: number;
}
PropertyTypeDefaultDescription
timeoutnumber30000Maximum time to wait in milliseconds

Promise<void> - Resolves when count is reached

// Trigger multiple emails
await sendMultipleNotifications(inbox.emailAddress, 3);
// Wait for all 3 to arrive
await inbox.waitForEmailCount(3, { timeout: 30000 });
// Now process all emails
const emails = await inbox.listEmails();
expect(emails.length).toBe(3);
  • TimeoutError - Required count not reached within timeout

Subscribes to new emails in real-time. Receives a callback for each new email that arrives.

onNewEmail(callback: (email: Email) => void): Subscription
  • callback: Function called when a new email arrives

Subscription - Subscription object with unsubscribe() method

interface Subscription {
unsubscribe(): void;
}
const inbox = await client.createInbox();
console.log(`Monitoring: ${inbox.emailAddress}`);
// Subscribe to new emails
const subscription = inbox.onNewEmail((email) => {
console.log(`New email: "${email.subject}"`);
console.log(`From: ${email.from}`);
// Process email...
});
// Later, stop monitoring
subscription.unsubscribe();

Always unsubscribe when done to avoid memory leaks:

let subscription;
beforeEach(async () => {
inbox = await client.createInbox();
subscription = inbox.onNewEmail((email) => {
// Handle email
});
});
afterEach(async () => {
if (subscription) {
subscription.unsubscribe();
}
if (inbox) {
await inbox.delete();
}
});

Gets the current synchronization status of the inbox with the server.

getSyncStatus(): Promise<SyncStatus>

Promise<SyncStatus> - Sync status information

interface SyncStatus {
emailCount: number;
emailsHash: string;
}
const status = await inbox.getSyncStatus();
console.log(`Email count: ${status.emailCount}`);
console.log(`Emails hash: ${status.emailsHash}`);

Gets the raw, decrypted source of a specific email (original MIME format).

getRawEmail(emailId: string): Promise<RawEmail>
  • emailId: The unique identifier for the email

Promise<RawEmail> - Raw email source

interface RawEmail {
id: string;
raw: string;
}
const emails = await inbox.listEmails();
const raw = await inbox.getRawEmail(emails[0].id);
console.log('Raw MIME source:');
console.log(raw.raw);
// Save to file for debugging
fs.writeFileSync('email.eml', raw.raw);

Marks a specific email as read.

markEmailAsRead(emailId: string): Promise<void>
  • emailId: The unique identifier for the email
const emails = await inbox.listEmails();
await inbox.markEmailAsRead(emails[0].id);
console.log('Email marked as read');

Deletes a specific email from the inbox.

deleteEmail(emailId: string): Promise<void>
  • emailId: The unique identifier for the email
const emails = await inbox.listEmails();
// Delete first email
await inbox.deleteEmail(emails[0].id);
console.log('Email deleted');
// Verify deletion
const updated = await inbox.listEmails();
expect(updated.length).toBe(emails.length - 1);

Deletes this inbox and all its emails.

delete(): Promise<void>
const inbox = await client.createInbox();
// Use inbox...
// Clean up
await inbox.delete();
console.log('Inbox deleted');

Always delete inboxes after tests:

afterEach(async () => {
if (inbox) {
await inbox.delete();
}
});

Exports inbox data and encryption keys for backup or sharing.

export(): ExportedInboxData

ExportedInboxData - Serializable inbox data including sensitive keys

interface ExportedInboxData {
version: number; // Export format version (currently 1)
emailAddress: string;
inboxHash: string;
expiresAt: string; // ISO 8601 timestamp
serverSigPk: string; // ML-DSA-65 public key (base64url)
secretKey: string; // ML-KEM-768 secret key (base64url)
exportedAt: string; // ISO 8601 timestamp
}
const inbox = await client.createInbox();
const data = inbox.export();
// Save for later
fs.writeFileSync('inbox-backup.json', JSON.stringify(data, null, 2));

Exported data contains private encryption keys. Store securely!

The InboxMonitor class allows you to monitor multiple inboxes simultaneously.

const inbox1 = await client.createInbox();
const inbox2 = await client.createInbox();
const monitor = client.monitorInboxes([inbox1, inbox2]);

Emitted when a new email arrives in any monitored inbox.

on(event: 'email', listener: (inbox: Inbox, email: Email) => void): this
  • inbox: The inbox that received the email
  • email: The email that was received
monitor.on('email', (inbox, email) => {
console.log(`Email received in ${inbox.emailAddress}`);
console.log(`Subject: ${email.subject}`);
});

Stops monitoring all inboxes and cleans up resources.

unsubscribe(): void
const monitor = client.monitorInboxes([inbox1, inbox2]);
// Use monitor...
// Stop monitoring
monitor.unsubscribe();
import { VaultSandboxClient } from '@vaultsandbox/client';
async function monitorMultipleInboxes() {
const client = new VaultSandboxClient({ url, apiKey });
// Create multiple inboxes
const inbox1 = await client.createInbox();
const inbox2 = await client.createInbox();
console.log(`Inbox 1: ${inbox1.emailAddress}`);
console.log(`Inbox 2: ${inbox2.emailAddress}`);
// Monitor both inboxes
const monitor = client.monitorInboxes([inbox1, inbox2]);
monitor.on('email', (inbox, email) => {
console.log(`\nNew email in ${inbox.emailAddress}:`);
console.log(` Subject: ${email.subject}`);
console.log(` From: ${email.from}`);
});
// Wait for emails to arrive...
await new Promise((resolve) => setTimeout(resolve, 60000));
// Clean up
monitor.unsubscribe();
await inbox1.delete();
await inbox2.delete();
}
monitorMultipleInboxes().catch(console.error);
import { VaultSandboxClient } from '@vaultsandbox/client';
async function completeInboxExample() {
const client = new VaultSandboxClient({
url: process.env.VAULTSANDBOX_URL,
apiKey: process.env.VAULTSANDBOX_API_KEY,
});
try {
// Create inbox
const inbox = await client.createInbox();
console.log(`Created: ${inbox.emailAddress}`);
console.log(`Expires: ${inbox.expiresAt.toISOString()}`);
// Subscribe to new emails
const subscription = inbox.onNewEmail((email) => {
console.log(`Received: ${email.subject}`);
});
// Trigger test email
await sendTestEmail(inbox.emailAddress);
// Wait for specific email
const email = await inbox.waitForEmail({
timeout: 10000,
subject: /Test/,
});
console.log(`Found email: ${email.subject}`);
console.log(`Body: ${email.text}`);
// Mark as read
await inbox.markEmailAsRead(email.id);
// Get all emails
const allEmails = await inbox.listEmails();
console.log(`Total emails: ${allEmails.length}`);
// Export inbox
const exportData = inbox.export();
fs.writeFileSync('inbox.json', JSON.stringify(exportData));
// Clean up
subscription.unsubscribe();
await inbox.delete();
} finally {
await client.close();
}
}
completeInboxExample().catch(console.error);