Email API
The Email class represents a decrypted email message in VaultSandbox. All emails are automatically decrypted when retrieved, so you can access content, headers, links, and attachments directly.
Properties
Section titled “Properties”id: string;Unique identifier for this email. Use this to reference the email in API calls.
Example
Section titled “Example”const emails = await inbox.listEmails();console.log(`Email ID: ${emails[0].id}`);
// Get specific emailconst email = await inbox.getEmail(emails[0].id);from: string;The sender’s email address.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });console.log(`From: ${email.from}`);
to: string[]Array of recipient email addresses.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });console.log(`To: ${email.to.join(', ')}`);
// Check if specific recipient is includedexpect(email.to).toContain(inbox.emailAddress);subject
Section titled “subject”subject: string;The email subject line.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000, subject: /Welcome/,});
console.log(`Subject: ${email.subject}`);expect(email.subject).toContain('Welcome');text: string | null;Plain text content of the email. May be null if the email only has HTML content.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });
if (email.text) { console.log('Plain text version:'); console.log(email.text);
// Validate content expect(email.text).toContain('Thank you for signing up');}html: string | null;HTML content of the email. May be null if the email only has plain text.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });
if (email.html) { console.log('HTML version present');
// Validate HTML structure expect(email.html).toContain('<a href='); expect(email.html).toContain('</html>');
// Check for specific elements expect(email.html).toMatch(/<img[^>]+src="/);}receivedAt
Section titled “receivedAt”receivedAt: Date;The date and time when the email was received by VaultSandbox.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });console.log(`Received at: ${email.receivedAt.toISOString()}`);
// Check if email was received recentlyconst now = Date.now();const received = email.receivedAt.getTime();const ageInSeconds = (now - received) / 1000;
expect(ageInSeconds).toBeLessThan(60); // Within last minuteisRead
Section titled “isRead”isRead: boolean;Whether this email has been marked as read.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });console.log(`Read status: ${email.isRead}`);
// Mark as readawait email.markAsRead();
// Verify status changedconst updated = await inbox.getEmail(email.id);expect(updated.isRead).toBe(true);links: string[]All URLs automatically extracted from the email content (both text and HTML).
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000, subject: /Password Reset/,});
console.log(`Found ${email.links.length} links:`);email.links.forEach((url) => console.log(` - ${url}`));
// Find specific linkconst resetLink = email.links.find((url) => url.includes('/reset-password'));expect(resetLink).toBeDefined();expect(resetLink).toMatch(/^https:\/\//);
// Extract query parametersconst url = new URL(resetLink);const token = url.searchParams.get('token');expect(token).toBeTruthy();headers
Section titled “headers”headers: Record<string, unknown>;All email headers as a key-value object.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });
console.log('Headers:');console.log(` Content-Type: ${email.headers['content-type']}`);console.log(` Message-ID: ${email.headers['message-id']}`);
// Check for custom headersif (email.headers['x-custom-header']) { console.log(`Custom header: ${email.headers['x-custom-header']}`);}attachments
Section titled “attachments”attachments: AttachmentData[]Array of email attachments, automatically decrypted and ready to use.
interface AttachmentData { filename: string; contentType: string; size: number; contentId?: string; contentDisposition?: string; checksum?: string; content?: Uint8Array;}Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000, subject: /Invoice/,});
console.log(`Attachments: ${email.attachments.length}`);
email.attachments.forEach((attachment) => { console.log(` - ${attachment.filename} (${attachment.size} bytes)`); console.log(` Type: ${attachment.contentType}`);});
// Find PDF attachmentconst pdf = email.attachments.find((att) => att.contentType === 'application/pdf');if (pdf && pdf.content) { fs.writeFileSync(`./downloads/${pdf.filename}`, pdf.content); console.log(`Saved ${pdf.filename}`);}
// Process text attachmentconst textFile = email.attachments.find((att) => att.contentType.includes('text'));if (textFile && textFile.content) { const text = new TextDecoder().decode(textFile.content); console.log('Text content:', text);}
// Parse JSON attachmentconst jsonFile = email.attachments.find((att) => att.contentType.includes('json'));if (jsonFile && jsonFile.content) { const json = new TextDecoder().decode(jsonFile.content); const data = JSON.parse(json); console.log('JSON data:', data);}See the Attachments Guide for more examples.
authResults
Section titled “authResults”authResults: AuthResults;Email authentication results including SPF, DKIM, and DMARC validation.
interface AuthResults { spf?: SPFResult; dkim?: DKIMResult[]; dmarc?: DMARCResult; reverseDns?: ReverseDNSResult; validate(): AuthValidation;}Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });
// Validate all authenticationconst validation = email.authResults.validate();console.log(`Authentication passed: ${validation.passed}`);
if (!validation.passed) { console.log('Failures:'); validation.failures.forEach((failure) => console.log(` - ${failure}`));}
// Check individual resultsif (email.authResults.spf) { console.log(`SPF Result: ${email.authResults.spf.result}`);}
if (email.authResults.dkim && email.authResults.dkim.length > 0) { console.log(`DKIM Result: ${email.authResults.dkim[0].result}`);}
if (email.authResults.dmarc) { console.log(`DMARC Result: ${email.authResults.dmarc.result}`);}See the Authentication Guide for more details.
metadata
Section titled “metadata”metadata: Record<string, unknown>;Additional metadata associated with the email.
Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });
if (email.metadata) { console.log('Metadata:', email.metadata);}Methods
Section titled “Methods”markAsRead()
Section titled “markAsRead()”Marks this email as read.
markAsRead(): Promise<void>Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });
console.log(`Read status: ${email.isRead}`); // false
await email.markAsRead();console.log('Marked as read');
// Verify status changedconst updated = await inbox.getEmail(email.id);expect(updated.isRead).toBe(true);delete()
Section titled “delete()”Deletes this email from the inbox.
delete(): Promise<void>Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });
// Delete the emailawait email.delete();console.log('Email deleted');
// Verify deletionconst emails = await inbox.listEmails();expect(emails.find((e) => e.id === email.id)).toBeUndefined();getRaw()
Section titled “getRaw()”Gets the raw MIME source of this email (decrypted).
getRaw(): Promise<RawEmail>Returns
Section titled “Returns”Promise<RawEmail> - Raw email source
interface RawEmail { id: string; raw: string;}Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });const raw = await email.getRaw();
console.log('Raw MIME source:');console.log(raw.raw);
// Save to .eml filefs.writeFileSync(`email-${email.id}.eml`, raw.raw);AuthResults
Section titled “AuthResults”The AuthResults object provides email authentication validation.
Properties
Section titled “Properties”spf?: SPFResultSPF (Sender Policy Framework) validation result.
interface SPFResult { result: 'pass' | 'fail' | 'softfail' | 'neutral' | 'none' | 'temperror' | 'permerror'; domain?: string; ip?: string; details?: string;}dkim?: DKIMResult[]DKIM (DomainKeys Identified Mail) validation results. May have multiple signatures.
interface DKIMResult { result: 'pass' | 'fail' | 'none'; domain?: string; selector?: string; signature?: string;}dmarc?: DMARCResultDMARC (Domain-based Message Authentication) validation result.
interface DMARCResult { result: 'pass' | 'fail' | 'none'; policy?: 'none' | 'quarantine' | 'reject'; aligned?: boolean; domain?: string;}reverseDns
Section titled “reverseDns”reverseDns?: ReverseDNSResultReverse DNS lookup result.
interface ReverseDNSResult { verified: boolean; ip?: string; hostname?: string;}Methods
Section titled “Methods”validate()
Section titled “validate()”Validates all authentication results and returns a summary.
validate(): AuthValidationReturns
Section titled “Returns”interface AuthValidation { passed: boolean; spfPassed: boolean; dkimPassed: boolean; dmarcPassed: boolean; reverseDnsPassed: boolean; failures: string[];}Example
Section titled “Example”const email = await inbox.waitForEmail({ timeout: 10000 });const validation = email.authResults.validate();
console.log(`Overall: ${validation.passed ? 'PASS' : 'FAIL'}`);console.log(`SPF: ${validation.spfPassed ? 'PASS' : 'FAIL'}`);console.log(`DKIM: ${validation.dkimPassed ? 'PASS' : 'FAIL'}`);console.log(`DMARC: ${validation.dmarcPassed ? 'PASS' : 'FAIL'}`);
if (!validation.passed) { console.log('\nFailures:'); validation.failures.forEach((failure) => { console.log(` - ${failure}`); });}Complete Example
Section titled “Complete Example”import { VaultSandboxClient } from '@vaultsandbox/client';import fs from 'fs';
async function completeEmailExample() { const client = new VaultSandboxClient({ url: process.env.VAULTSANDBOX_URL, apiKey: process.env.VAULTSANDBOX_API_KEY, });
try { const inbox = await client.createInbox(); console.log(`Created inbox: ${inbox.emailAddress}`);
// Trigger test email await sendTestEmail(inbox.emailAddress);
// Wait for email const email = await inbox.waitForEmail({ timeout: 10000, subject: /Test/, });
// Basic info console.log('\n=== Email Details ==='); console.log(`ID: ${email.id}`); console.log(`From: ${email.from}`); console.log(`To: ${email.to.join(', ')}`); console.log(`Subject: ${email.subject}`); console.log(`Received: ${email.receivedAt.toISOString()}`); console.log(`Read: ${email.isRead}`);
// Content console.log('\n=== Content ==='); if (email.text) { console.log('Plain text:'); console.log(email.text.substring(0, 200) + '...'); } if (email.html) { console.log('HTML version present'); }
// Links console.log('\n=== Links ==='); console.log(`Found ${email.links.length} links:`); email.links.forEach((link) => console.log(` - ${link}`));
// Attachments console.log('\n=== Attachments ==='); console.log(`Found ${email.attachments.length} attachments:`); email.attachments.forEach((att) => { console.log(` - ${att.filename} (${att.contentType}, ${att.size} bytes)`);
// Save attachment if (att.content) { fs.writeFileSync(`./downloads/${att.filename}`, att.content); console.log(` Saved to ./downloads/${att.filename}`); } });
// Authentication console.log('\n=== Authentication ==='); const validation = email.authResults.validate(); console.log(`Overall: ${validation.passed ? 'PASS' : 'FAIL'}`); console.log(`SPF: ${validation.spfPassed}`); console.log(`DKIM: ${validation.dkimPassed}`); console.log(`DMARC: ${validation.dmarcPassed}`);
if (!validation.passed) { console.log('Failures:', validation.failures); }
// Mark as read await email.markAsRead(); console.log('\nMarked as read');
// Get raw source const raw = await email.getRaw(); fs.writeFileSync(`email-${email.id}.eml`, raw.raw); console.log(`Saved raw source to email-${email.id}.eml`);
// Clean up await inbox.delete(); } finally { await client.close(); }}
completeEmailExample().catch(console.error);Next Steps
Section titled “Next Steps”- Inbox API Reference - Learn about inbox methods
- Attachments Guide - Working with attachments
- Authentication Guide - Email authentication testing
- Waiting for Emails - Best practices for email waiting