Managing Inboxes
This guide covers common inbox management operations with practical examples.
Creating Inboxes
Section titled “Creating Inboxes”Basic Creation
Section titled “Basic Creation”import { VaultSandboxClient } from '@vaultsandbox/client';
const client = new VaultSandboxClient({ url: process.env.VAULTSANDBOX_URL, apiKey: process.env.VAULTSANDBOX_API_KEY,});
const inbox = await client.createInbox();console.log(`Email address: ${inbox.emailAddress}`);With Custom TTL
Section titled “With Custom TTL”// Expire after 1 hour (good for CI/CD)const inbox = await client.createInbox({ ttl: 3600 });
// Expire after 10 minutes (quick tests)const inbox = await client.createInbox({ ttl: 600 });
// Expire after 7 days (long-running tests)const inbox = await client.createInbox({ ttl: 604800 });Requesting Specific Address
Section titled “Requesting Specific Address”try { const inbox = await client.createInbox({ }); console.log('Got requested address:', inbox.emailAddress);} catch (error) { if (error instanceof InboxAlreadyExistsError) { console.log('Address already in use, using random address'); const inbox = await client.createInbox(); }}Listing Emails
Section titled “Listing Emails”List All Emails
Section titled “List All Emails”const emails = await inbox.listEmails();
console.log(`Inbox contains ${emails.length} emails`);emails.forEach((email) => { console.log(`- ${email.from}: ${email.subject}`);});Filtering Emails
Section titled “Filtering Emails”const emails = await inbox.listEmails();
// Filter by sender
// Filter by subjectconst passwordResets = emails.filter((e) => /reset/i.test(e.subject));
// Filter by dateconst recentEmails = emails.filter( (e) => new Date() - e.receivedAt < 3600000 // Last hour);Sorting Emails
Section titled “Sorting Emails”const emails = await inbox.listEmails();
// Sort by date (newest first)const sortedByDate = emails.sort((a, b) => b.receivedAt - a.receivedAt);
// Sort by senderconst sortedBySender = emails.sort((a, b) => a.from.localeCompare(b.from));Getting Specific Emails
Section titled “Getting Specific Emails”const emailId = 'email_abc123';const email = await inbox.getEmail(emailId);
console.log(email.subject);With Error Handling
Section titled “With Error Handling”try { const email = await inbox.getEmail(emailId); console.log('Found:', email.subject);} catch (error) { if (error instanceof EmailNotFoundError) { console.error('Email not found'); }}Deleting Emails
Section titled “Deleting Emails”Delete Single Email
Section titled “Delete Single Email”// By IDawait inbox.deleteEmail('email_abc123');
// Via email objectconst email = await inbox.getEmail('email_abc123');await email.delete();Delete Multiple Emails
Section titled “Delete Multiple Emails”const emails = await inbox.listEmails();
// Delete all emailsfor (const email of emails) { await email.delete();}
// Or in parallelawait Promise.all(emails.map((email) => email.delete()));Delete by Criteria
Section titled “Delete by Criteria”const emails = await inbox.listEmails();
// Delete old emailsconst oldEmails = emails.filter( (e) => new Date() - e.receivedAt > 86400000 // Older than 24h);
await Promise.all(oldEmails.map((email) => email.delete()));Deleting Inboxes
Section titled “Deleting Inboxes”Delete Single Inbox
Section titled “Delete Single Inbox”await inbox.delete();
// Inbox and all emails are now deletedDelete All Inboxes
Section titled “Delete All Inboxes”// Delete all inboxes for this API keyconst count = await client.deleteAllInboxes();console.log(`Deleted ${count} inboxes`);Safe Deletion with Cleanup
Section titled “Safe Deletion with Cleanup”async function withInbox(callback) { const inbox = await client.createInbox(); try { await callback(inbox); } finally { await inbox.delete(); }}
// Usageawait withInbox(async (inbox) => { await sendTestEmail(inbox.emailAddress); const email = await inbox.waitForEmail({ timeout: 10000 }); expect(email.subject).toContain('Test');});Checking Inbox Status
Section titled “Checking Inbox Status”Check if Inbox Exists
Section titled “Check if Inbox Exists”try { const emails = await inbox.listEmails(); console.log('Inbox exists');} catch (error) { if (error instanceof InboxNotFoundError) { console.log('Inbox expired or deleted'); }}Check Expiration
Section titled “Check Expiration”const now = new Date();const expiresIn = inbox.expiresAt - now;
if (expiresIn < 300000) { // Less than 5 minutes console.warn('Inbox expiring soon!'); console.log(`Time left: ${Math.floor(expiresIn / 60000)} minutes`);}Get Sync Status
Section titled “Get Sync Status”const syncStatus = await inbox.getSyncStatus();
console.log('Email count:', syncStatus.emailCount);console.log('Emails hash:', syncStatus.emailsHash);Bulk Operations
Section titled “Bulk Operations”Create Multiple Inboxes
Section titled “Create Multiple Inboxes”const inboxes = await Promise.all([client.createInbox(), client.createInbox(), client.createInbox()]);
console.log(`Created ${inboxes.length} inboxes`);inboxes.forEach((inbox) => { console.log(`- ${inbox.emailAddress}`);});Clean Up Multiple Inboxes
Section titled “Clean Up Multiple Inboxes”// Delete allawait Promise.all(inboxes.map((inbox) => inbox.delete()));
// Or use convenience methodawait client.deleteAllInboxes();Testing Patterns
Section titled “Testing Patterns”Jest Setup/Teardown
Section titled “Jest Setup/Teardown”describe('Email Tests', () => { let client, inbox;
beforeAll(() => { client = new VaultSandboxClient({ url: process.env.VAULTSANDBOX_URL, apiKey: process.env.VAULTSANDBOX_API_KEY, }); });
beforeEach(async () => { inbox = await client.createInbox(); });
afterEach(async () => { await inbox.delete(); });
afterAll(async () => { await client.close(); });
test('receives email', async () => { await sendEmail(inbox.emailAddress); const email = await inbox.waitForEmail({ timeout: 10000 }); expect(email).toBeDefined(); });});Shared Inbox Pattern
Section titled “Shared Inbox Pattern”describe('Email Suite', () => { let client, inbox;
beforeAll(async () => { client = new VaultSandboxClient({ url, apiKey }); inbox = await client.createInbox({ ttl: 7200 }); // 2 hours });
afterAll(async () => { await inbox.delete(); await client.close(); });
test('test 1', async () => { // Use shared inbox });
test('test 2', async () => { // Use shared inbox });});Inbox Pool Pattern
Section titled “Inbox Pool Pattern”class InboxPool { constructor(client, size = 5) { this.client = client; this.size = size; this.available = []; this.inUse = new Set(); }
async initialize() { const promises = Array(this.size) .fill() .map(() => this.client.createInbox()); this.available = await Promise.all(promises); }
acquire() { if (this.available.length === 0) { throw new Error('No inboxes available'); } const inbox = this.available.shift(); this.inUse.add(inbox); return inbox; }
release(inbox) { this.inUse.delete(inbox); this.available.push(inbox); }
async cleanup() { const all = [...this.available, ...this.inUse]; await Promise.all(all.map((inbox) => inbox.delete())); }}
// Usageconst pool = new InboxPool(client, 5);await pool.initialize();
const inbox = pool.acquire();// Use inboxpool.release(inbox);
await pool.cleanup();Error Handling
Section titled “Error Handling”Handling Expired Inboxes
Section titled “Handling Expired Inboxes”try { const emails = await inbox.listEmails();} catch (error) { if (error instanceof InboxNotFoundError) { console.log('Inbox expired, creating new one'); inbox = await client.createInbox(); } else { throw error; }}Handling Creation Errors
Section titled “Handling Creation Errors”try { const inbox = await client.createInbox();} catch (error) { if (error instanceof ApiError) { console.error('API error:', error.statusCode, error.message); } else if (error instanceof NetworkError) { console.error('Network error:', error.message); } else { throw error; }}Best Practices
Section titled “Best Practices”Always Clean Up
Section titled “Always Clean Up”// ✅ Good: Cleanup in finally blockconst inbox = await client.createInbox();try { // Use inbox} finally { await inbox.delete();}
// ❌ Bad: No cleanupconst inbox = await client.createInbox();// Use inbox// Inbox never deletedUse Appropriate TTL
Section titled “Use Appropriate TTL”// ✅ Good: Short TTL for CI/CDconst inbox = await client.createInbox({ ttl: 3600 }); // 1 hour
// ❌ Bad: Long TTL wastes resourcesconst inbox = await client.createInbox({ ttl: 604800 }); // 7 days for quick testHandle Cleanup Errors
Section titled “Handle Cleanup Errors”async function safeDelete(inbox) { try { await inbox.delete(); } catch (error) { // Inbox may have already expired if (!(error instanceof InboxNotFoundError)) { console.error('Error deleting inbox:', error); } }}Next Steps
Section titled “Next Steps”- Waiting for Emails - Learn about email waiting strategies
- Real-time Monitoring - Subscribe to new emails
- API Reference: Inbox - Complete inbox API documentation
- Core Concepts: Inboxes - Deep dive into inbox concepts