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`);emailAuth
Section titled “emailAuth”emailAuth: boolean;Whether email authentication checks (SPF/DKIM/DMARC/PTR) are enabled for this inbox.
Example
Section titled “Example”const inbox = await client.createInbox({ emailAuth: false });console.log(`Email auth enabled: ${inbox.emailAuth}`); // false
// When emailAuth is false, auth results will show "skipped" statusconst email = await inbox.waitForEmail({ timeout: 10000 });console.log(email.authResults.spf?.result); // "skipped"encrypted
Section titled “encrypted”encrypted: boolean;Whether this inbox uses end-to-end encryption. When true, emails are encrypted at rest and the serverSigPk property is available.
Example
Section titled “Example”const inbox = await client.createInbox();console.log(`Inbox encrypted: ${inbox.encrypted}`);
if (inbox.encrypted) { // Inbox uses end-to-end encryption // Emails are automatically decrypted by the SDK}spamAnalysis
Section titled “spamAnalysis”spamAnalysis?: boolean;Whether spam analysis is enabled for this inbox. This property reflects the spam analysis setting that was requested at inbox creation time.
true- Spam analysis is enabled for emails to this inboxfalse- Spam analysis is disabled for this inboxundefined- Using server default setting
Example
Section titled “Example”// Create inbox with spam analysis enabledconst inbox = await client.createInbox({ spamAnalysis: true });console.log(`Spam analysis enabled: ${inbox.spamAnalysis}`); // true
// Check if spam analysis is activeif (inbox.spamAnalysis) { const email = await inbox.waitForEmail({ timeout: 10000 }); if (email.spamAnalysis?.status === 'analyzed') { console.log(`Spam score: ${email.getSpamScore()}`); }}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, from: 'noreply@example.com',});
// Wait with custom predicateconst email = await inbox.waitForEmail({ timeout: 15000, predicate: (email) => email.to.includes('user@example.com'),});
// 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!
Webhook Methods
Section titled “Webhook Methods”The Inbox class provides methods for managing webhooks that receive HTTP callbacks when events occur.
createWebhook()
Section titled “createWebhook()”Creates a new webhook for this inbox.
createWebhook(options: CreateWebhookOptions): Promise<WebhookData>Parameters
Section titled “Parameters”interface CreateWebhookOptions { url: string; events: WebhookEventType[]; template?: 'slack' | 'discord' | 'teams' | 'simple' | 'notification' | 'zapier' | 'default' | CustomTemplate; filter?: FilterConfig; description?: string;}
type WebhookEventType = 'email.received' | 'email.stored' | 'email.deleted';Returns
Section titled “Returns”Promise<WebhookData> - The created webhook including the secret for signature verification
Example
Section titled “Example”const webhook = await inbox.createWebhook({ url: 'https://your-app.com/webhook/emails', events: ['email.received'], description: 'Production email notifications',});
console.log(`Webhook ID: ${webhook.id}`);console.log(`Secret: ${webhook.secret}`); // Save this!listWebhooks()
Section titled “listWebhooks()”Lists all webhooks for this inbox.
listWebhooks(): Promise<WebhookListResponse>Returns
Section titled “Returns”Promise<WebhookListResponse> - List of webhooks and total count
interface WebhookListResponse { webhooks: WebhookData[]; total: number;}Example
Section titled “Example”const { webhooks, total } = await inbox.listWebhooks();
console.log(`Total webhooks: ${total}`);webhooks.forEach((wh) => { console.log(`- ${wh.id}: ${wh.url}`);});getWebhook()
Section titled “getWebhook()”Retrieves a specific webhook by ID.
getWebhook(webhookId: string): Promise<WebhookData>Parameters
Section titled “Parameters”webhookId: The unique identifier for the webhook
Returns
Section titled “Returns”Promise<WebhookData> - The webhook data
interface WebhookData { id: string; url: string; events: WebhookEventType[]; scope: 'global' | 'inbox'; inboxEmail?: string; enabled: boolean; secret?: string; template?: unknown; filter?: FilterConfig; description?: string; createdAt: string; updatedAt?: string; lastDeliveryAt?: string; lastDeliveryStatus?: 'success' | 'failed'; stats?: WebhookStats;}Example
Section titled “Example”const webhook = await inbox.getWebhook('webhook-id');
console.log(`URL: ${webhook.url}`);console.log(`Enabled: ${webhook.enabled}`);console.log(`Last delivery: ${webhook.lastDeliveryAt || 'Never'}`);Errors
Section titled “Errors”WebhookNotFoundError- Webhook does not exist
updateWebhook()
Section titled “updateWebhook()”Updates a specific webhook.
updateWebhook(webhookId: string, options: UpdateWebhookOptions): Promise<WebhookData>Parameters
Section titled “Parameters”webhookId: The unique identifier for the webhook
interface UpdateWebhookOptions { url?: string; events?: WebhookEventType[]; template?: string | CustomTemplate | null; filter?: FilterConfig | null; description?: string; enabled?: boolean;}Returns
Section titled “Returns”Promise<WebhookData> - The updated webhook data
Example
Section titled “Example”const updated = await inbox.updateWebhook('webhook-id', { url: 'https://your-app.com/webhook/v2/emails', enabled: false,});
console.log(`Updated URL: ${updated.url}`);Errors
Section titled “Errors”WebhookNotFoundError- Webhook does not exist
deleteWebhook()
Section titled “deleteWebhook()”Deletes a specific webhook.
deleteWebhook(webhookId: string): Promise<void>Parameters
Section titled “Parameters”webhookId: The unique identifier for the webhook
Example
Section titled “Example”await inbox.deleteWebhook('webhook-id');console.log('Webhook deleted');Errors
Section titled “Errors”WebhookNotFoundError- Webhook does not exist
testWebhook()
Section titled “testWebhook()”Tests a webhook by sending a test payload.
testWebhook(webhookId: string): Promise<TestWebhookResponse>Parameters
Section titled “Parameters”webhookId: The unique identifier for the webhook
Returns
Section titled “Returns”Promise<TestWebhookResponse> - The test result
interface TestWebhookResponse { success: boolean; statusCode?: number; responseTime?: number; responseBody?: string; error?: string; payloadSent?: unknown;}Example
Section titled “Example”const result = await inbox.testWebhook('webhook-id');
if (result.success) { console.log(`Test passed! Status: ${result.statusCode}`); console.log(`Response time: ${result.responseTime}ms`);} else { console.error(`Test failed: ${result.error}`);}Errors
Section titled “Errors”WebhookNotFoundError- Webhook does not exist
rotateWebhookSecret()
Section titled “rotateWebhookSecret()”Rotates the secret for a webhook. The old secret remains valid for a grace period.
rotateWebhookSecret(webhookId: string): Promise<RotateSecretResponse>Parameters
Section titled “Parameters”webhookId: The unique identifier for the webhook
Returns
Section titled “Returns”Promise<RotateSecretResponse> - The new secret and grace period
interface RotateSecretResponse { id: string; secret: string; previousSecretValidUntil: string;}Example
Section titled “Example”const result = await inbox.rotateWebhookSecret('webhook-id');
console.log(`New secret: ${result.secret}`);console.log(`Old secret valid until: ${result.previousSecretValidUntil}`);Errors
Section titled “Errors”WebhookNotFoundError- Webhook does not exist
Chaos Methods
Section titled “Chaos Methods”The Inbox class provides methods for configuring chaos engineering features to test email resilience. Chaos must be enabled on the gateway server.
getChaosConfig()
Section titled “getChaosConfig()”Gets the current chaos configuration for this inbox.
getChaosConfig(): Promise<ChaosConfigResponse>Returns
Section titled “Returns”Promise<ChaosConfigResponse> - The current chaos configuration
interface ChaosConfigResponse { enabled: boolean; expiresAt?: string; latency?: LatencyConfig; connectionDrop?: ConnectionDropConfig; randomError?: RandomErrorConfig; greylist?: GreylistConfig; blackhole?: BlackholeConfig;}Example
Section titled “Example”const config = await inbox.getChaosConfig();
console.log(`Chaos enabled: ${config.enabled}`);if (config.latency?.enabled) { console.log(`Latency: ${config.latency.minDelayMs}-${config.latency.maxDelayMs}ms`);}Errors
Section titled “Errors”ApiError(403) - Chaos features are disabled on the server
setChaosConfig()
Section titled “setChaosConfig()”Sets or updates the chaos configuration for this inbox.
setChaosConfig(config: ChaosConfigRequest): Promise<ChaosConfigResponse>Parameters
Section titled “Parameters”interface ChaosConfigRequest { enabled: boolean; expiresAt?: string; latency?: LatencyConfig; connectionDrop?: ConnectionDropConfig; randomError?: RandomErrorConfig; greylist?: GreylistConfig; blackhole?: BlackholeConfig;}| Property | Type | Required | Description |
|---|---|---|---|
enabled | boolean | Yes | Master switch for chaos features |
expiresAt | string | No | ISO 8601 timestamp for auto-disable |
latency | LatencyConfig | No | Latency injection configuration |
connectionDrop | ConnectionDropConfig | No | Connection drop configuration |
randomError | RandomErrorConfig | No | Random error configuration |
greylist | GreylistConfig | No | Greylisting simulation configuration |
blackhole | BlackholeConfig | No | Blackhole mode configuration |
Returns
Section titled “Returns”Promise<ChaosConfigResponse> - The updated chaos configuration
Example
Section titled “Example”const config = await inbox.setChaosConfig({ enabled: true, latency: { enabled: true, minDelayMs: 1000, maxDelayMs: 5000, jitter: true, probability: 0.5, }, randomError: { enabled: true, errorRate: 0.1, errorTypes: ['temporary'], },});
console.log('Chaos configured:', config);Errors
Section titled “Errors”ApiError(403) - Chaos features are disabled on the serverInboxNotFoundError- Inbox does not exist
disableChaos()
Section titled “disableChaos()”Disables all chaos features for this inbox.
disableChaos(): Promise<void>Example
Section titled “Example”// Disable all chaos featuresawait inbox.disableChaos();
console.log('Chaos disabled');Errors
Section titled “Errors”ApiError(403) - Chaos features are disabled on the serverInboxNotFoundError- Inbox does not exist
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
- Webhooks Guide - Set up webhook notifications
- Waiting for Emails Guide - Best practices
- Real-time Monitoring Guide - Advanced monitoring patterns