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.
Properties
Section titled “Properties”emailAddress
Section titled “emailAddress”emailAddress: string;The email address for this inbox. Use this address to send test emails.
Example
Section titled “Example”const inbox = await client.createInbox();console.log(`Send email to: ${inbox.emailAddress}`);
// Use in your applicationawait sendWelcomeEmail(inbox.emailAddress);inboxHash
Section titled “inboxHash”inboxHash: string;Unique identifier for this inbox. Used internally for API operations.
Example
Section titled “Example”console.log(`Inbox ID: ${inbox.inboxHash}`);expiresAt
Section titled “expiresAt”expiresAt: Date;The date and time when this inbox will expire and be automatically deleted.
Example
Section titled “Example”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`);Methods
Section titled “Methods”listEmails()
Section titled “listEmails()”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[]>Returns
Section titled “Returns”Promise<Email[]> - Array of decrypted email objects with full content (text, html, attachments, etc.)
Example
Section titled “Example”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)}...`);});listEmailsMetadataOnly()
Section titled “listEmailsMetadataOnly()”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[]>Returns
Section titled “Returns”Promise<EmailMetadata[]> - Array of email metadata objects
interface EmailMetadata { id: string; from: string; subject: string; receivedAt: Date; isRead: boolean;}Example
Section titled “Example”// Quickly list emails without fetching full contentconst 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 neededconst fullEmail = await inbox.getEmail(emails[0].id);console.log(`Body: ${fullEmail.text}`);When to Use
Section titled “When to Use”- Displaying email lists in a UI
- Checking for new emails before fetching content
- Reducing bandwidth when full content isn’t needed
getEmail()
Section titled “getEmail()”Retrieves a specific email by ID.
getEmail(emailId: string): Promise<Email>Parameters
Section titled “Parameters”emailId: The unique identifier for the email
Returns
Section titled “Returns”Promise<Email> - The decrypted email object
Example
Section titled “Example”const emails = await inbox.listEmails();const firstEmail = await inbox.getEmail(emails[0].id);
console.log(`Subject: ${firstEmail.subject}`);console.log(`Body: ${firstEmail.text}`);Errors
Section titled “Errors”EmailNotFoundError- Email does not exist
waitForEmail()
Section titled “waitForEmail()”Waits for an email matching specified criteria. This is the recommended way to handle email arrival in tests.
waitForEmail(options: WaitOptions): Promise<Email>Parameters
Section titled “Parameters”interface WaitOptions { timeout?: number; pollInterval?: number; subject?: string | RegExp; from?: string | RegExp; predicate?: (email: Email) => boolean;}| Property | Type | Default | Description |
|---|---|---|---|
timeout | number | 30000 | Maximum time to wait in milliseconds |
pollInterval | number | 2000 | Polling interval in milliseconds |
subject | string | RegExp | - | Filter by email subject |
from | string | RegExp | - | Filter by sender address |
predicate | (email: Email) => boolean | - | Custom filter function |
Returns
Section titled “Returns”Promise<Email> - The first email matching the criteria
Examples
Section titled “Examples”// Wait for any emailconst email = await inbox.waitForEmail({ timeout: 10000 });
// Wait for email with specific subjectconst email = await inbox.waitForEmail({ timeout: 10000, subject: /Password Reset/,});
// Wait for email from specific senderconst email = await inbox.waitForEmail({ timeout: 10000,});
// Wait with custom predicateconst email = await inbox.waitForEmail({ timeout: 15000,});
// Combine multiple filtersconst email = await inbox.waitForEmail({ timeout: 10000, subject: /Welcome/, from: /noreply@/, predicate: (email) => email.links.length > 0,});Errors
Section titled “Errors”TimeoutError- No matching email received within timeout period
waitForEmailCount()
Section titled “waitForEmailCount()”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>Parameters
Section titled “Parameters”count: Minimum number of emails to wait for
interface WaitForCountOptions { timeout?: number;}| Property | Type | Default | Description |
|---|---|---|---|
timeout | number | 30000 | Maximum time to wait in milliseconds |
Returns
Section titled “Returns”Promise<void> - Resolves when count is reached
Example
Section titled “Example”// Trigger multiple emailsawait sendMultipleNotifications(inbox.emailAddress, 3);
// Wait for all 3 to arriveawait inbox.waitForEmailCount(3, { timeout: 30000 });
// Now process all emailsconst emails = await inbox.listEmails();expect(emails.length).toBe(3);Errors
Section titled “Errors”TimeoutError- Required count not reached within timeout
onNewEmail()
Section titled “onNewEmail()”Subscribes to new emails in real-time. Receives a callback for each new email that arrives.
onNewEmail(callback: (email: Email) => void): SubscriptionParameters
Section titled “Parameters”callback: Function called when a new email arrives
Returns
Section titled “Returns”Subscription - Subscription object with unsubscribe() method
interface Subscription { unsubscribe(): void;}Example
Section titled “Example”const inbox = await client.createInbox();
console.log(`Monitoring: ${inbox.emailAddress}`);
// Subscribe to new emailsconst subscription = inbox.onNewEmail((email) => { console.log(`New email: "${email.subject}"`); console.log(`From: ${email.from}`);
// Process email...});
// Later, stop monitoringsubscription.unsubscribe();Best Practice
Section titled “Best Practice”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(); }});getSyncStatus()
Section titled “getSyncStatus()”Gets the current synchronization status of the inbox with the server.
getSyncStatus(): Promise<SyncStatus>Returns
Section titled “Returns”Promise<SyncStatus> - Sync status information
interface SyncStatus { emailCount: number; emailsHash: string;}Example
Section titled “Example”const status = await inbox.getSyncStatus();console.log(`Email count: ${status.emailCount}`);console.log(`Emails hash: ${status.emailsHash}`);getRawEmail()
Section titled “getRawEmail()”Gets the raw, decrypted source of a specific email (original MIME format).
getRawEmail(emailId: string): Promise<RawEmail>Parameters
Section titled “Parameters”emailId: The unique identifier for the email
Returns
Section titled “Returns”Promise<RawEmail> - Raw email source
interface RawEmail { id: string; raw: string;}Example
Section titled “Example”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 debuggingfs.writeFileSync('email.eml', raw.raw);markEmailAsRead()
Section titled “markEmailAsRead()”Marks a specific email as read.
markEmailAsRead(emailId: string): Promise<void>Parameters
Section titled “Parameters”emailId: The unique identifier for the email
Example
Section titled “Example”const emails = await inbox.listEmails();await inbox.markEmailAsRead(emails[0].id);
console.log('Email marked as read');deleteEmail()
Section titled “deleteEmail()”Deletes a specific email from the inbox.
deleteEmail(emailId: string): Promise<void>Parameters
Section titled “Parameters”emailId: The unique identifier for the email
Example
Section titled “Example”const emails = await inbox.listEmails();
// Delete first emailawait inbox.deleteEmail(emails[0].id);
console.log('Email deleted');
// Verify deletionconst updated = await inbox.listEmails();expect(updated.length).toBe(emails.length - 1);delete()
Section titled “delete()”Deletes this inbox and all its emails.
delete(): Promise<void>Example
Section titled “Example”const inbox = await client.createInbox();
// Use inbox...
// Clean upawait inbox.delete();console.log('Inbox deleted');Best Practice
Section titled “Best Practice”Always delete inboxes after tests:
afterEach(async () => { if (inbox) { await inbox.delete(); }});export()
Section titled “export()”Exports inbox data and encryption keys for backup or sharing.
export(): ExportedInboxDataReturns
Section titled “Returns”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}Example
Section titled “Example”const inbox = await client.createInbox();const data = inbox.export();
// Save for laterfs.writeFileSync('inbox-backup.json', JSON.stringify(data, null, 2));Security Warning
Section titled “Security Warning”Exported data contains private encryption keys. Store securely!
InboxMonitor
Section titled “InboxMonitor”The InboxMonitor class allows you to monitor multiple inboxes simultaneously.
Creating a Monitor
Section titled “Creating a Monitor”const inbox1 = await client.createInbox();const inbox2 = await client.createInbox();
const monitor = client.monitorInboxes([inbox1, inbox2]);Events
Section titled “Events”Emitted when a new email arrives in any monitored inbox.
on(event: 'email', listener: (inbox: Inbox, email: Email) => void): thisParameters
Section titled “Parameters”inbox: The inbox that received the emailemail: The email that was received
Example
Section titled “Example”monitor.on('email', (inbox, email) => { console.log(`Email received in ${inbox.emailAddress}`); console.log(`Subject: ${email.subject}`);});Methods
Section titled “Methods”unsubscribe()
Section titled “unsubscribe()”Stops monitoring all inboxes and cleans up resources.
unsubscribe(): voidExample
Section titled “Example”const monitor = client.monitorInboxes([inbox1, inbox2]);
// Use monitor...
// Stop monitoringmonitor.unsubscribe();Complete Example
Section titled “Complete Example”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);Complete Inbox Example
Section titled “Complete Inbox Example”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);Next Steps
Section titled “Next Steps”- Email API Reference - Work with email objects
- VaultSandboxClient API - Learn about client methods
- Waiting for Emails Guide - Best practices
- Real-time Monitoring Guide - Advanced monitoring patterns