npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bernierllc/email-capture

v1.0.3

Published

Atomic utility package for capturing and storing emails for testing and analysis

Readme

@bernierllc/email-capture

Atomic utility package for capturing and storing emails for testing and analysis. Provides session-based email capture with metadata extraction, querying capabilities, and multiple export formats.

Installation

npm install @bernierllc/email-capture

Usage

Basic Email Capture

import { EmailCapture } from '@bernierllc/email-capture';

// Create an email capture instance
const capture = new EmailCapture();

// Create a session for organizing captured emails
const session = await capture.createSession({
  name: 'Test Session',
  description: 'Capturing emails for API testing',
  retention: {
    maxAge: 86400000, // 24 hours
    maxCount: 1000,
    autoCleanup: true
  }
});

// Capture an email
const email = await capture.captureEmail(session.id, {
  content: 'From: [email protected]\nTo: [email protected]\nSubject: Test Email\n\nHello, world!',
  source: { 
    type: 'smtp', 
    server: 'localhost:1025' 
  }
});

console.log('Captured email:', email.id);

Querying and Filtering

// Query emails by various criteria
const emails = await capture.queryEmails({
  sessionId: session.id,
  sender: '[email protected]',
  subject: 'Test Email'
});

// Get emails with pagination
const recentEmails = await capture.queryEmails(
  { sessionId: session.id },
  10, // limit
  0   // offset
);

Export Functionality

// Export emails as JSON
const jsonData = await capture.exportEmails(
  { sessionId: session.id },
  { format: 'json', includeContent: true }
);

// Export as CSV for spreadsheet analysis
const csvData = await capture.exportEmails(
  { sessionId: session.id },
  { format: 'csv' }
);

// Export as EML files
const emlData = await capture.exportEmails(
  { sessionId: session.id },
  { format: 'eml' }
);

// Export as MBOX format
const mboxData = await capture.exportEmails(
  { sessionId: session.id },
  { format: 'mbox' }
);

Session Management

// List all sessions
const sessions = await capture.listSessions(10, 0);

// Update session configuration
await capture.updateSession(session.id, {
  name: 'Updated Session Name',
  retention: {
    maxAge: 172800000, // 48 hours
    maxCount: 2000,
    autoCleanup: true
  }
});

// Get session statistics
const stats = await capture.getSessionStats(session.id);
console.log(`Session has ${stats.totalEmails} emails using ${stats.totalBytes} bytes`);

Cleanup Operations

// Clean up old emails based on retention policy
const cleanupResult = await capture.cleanupSession(session.id);
console.log(`Deleted ${cleanupResult.emailsDeleted} emails, freed ${cleanupResult.bytesFreed} bytes`);

// Clean up expired sessions globally
const globalCleanup = await capture.cleanupExpiredSessions();
console.log(`Cleaned up ${globalCleanup.sessionsDeleted} expired sessions`);

API Reference

EmailCapture

Main class for email capture operations.

Constructor

new EmailCapture(storage?: StorageBackend)
  • storage (optional): Custom storage backend. Defaults to MemoryStorage.

Session Management Methods

createSession(config: SessionConfig): Promise<EmailCaptureSession>

Creates a new email capture session.

  • config.name: Human-readable session name
  • config.description (optional): Session description
  • config.retention (optional): Retention policy configuration
  • config.metadata (optional): Additional session metadata
getSession(sessionId: string): Promise<EmailCaptureSession | null>

Retrieves a session by ID.

updateSession(sessionId: string, updates: Partial<EmailCaptureSession>): Promise<EmailCaptureSession>

Updates session configuration.

deleteSession(sessionId: string): Promise<boolean>

Deletes a session and all its emails.

listSessions(limit?: number, offset?: number): Promise<QueryResult<EmailCaptureSession>>

Lists all sessions with pagination.

Email Capture Methods

captureEmail(sessionId: string, email: RawEmail): Promise<CapturedEmail>

Captures an email in the specified session.

  • email.content: Raw email content (headers + body)
  • email.source: Source information (type, server, etc.)
  • email.metadata (optional): Pre-extracted metadata
getEmail(emailId: string): Promise<CapturedEmail | null>

Retrieves a specific email by ID.

deleteEmail(emailId: string): Promise<boolean>

Deletes a specific email.

Query and Export Methods

queryEmails(filters: EmailFilters, limit?: number, offset?: number): Promise<QueryResult<CapturedEmail>>

Queries emails with filtering and pagination.

Supported filters:

  • sessionId: Filter by session
  • sender: Filter by sender email address
  • recipient: Filter by recipient email address
  • subject: Filter by subject (partial match)
  • sourceType: Filter by source type ('smtp', 'api', 'webhook', etc.)
exportEmails(filters: EmailFilters, options: ExportOptions): Promise<string>

Exports emails in various formats.

Export options:

  • format: 'json', 'csv', 'eml', or 'mbox'
  • includeContent (optional): Include raw email content
  • includeMetadata (optional): Include extracted metadata
exportSession(sessionId: string, options: ExportOptions): Promise<string>

Exports all emails from a session.

Statistics Methods

getSessionStats(sessionId: string): Promise<SessionStats>

Returns statistics for a specific session.

getGlobalStats(): Promise<GlobalStats>

Returns global statistics across all sessions.

Cleanup Methods

cleanupSession(sessionId: string): Promise<CleanupResult>

Cleans up emails in a session based on retention policy.

cleanupExpiredSessions(): Promise<CleanupResult>

Cleans up all expired sessions globally.

Types

EmailCaptureSession

interface EmailCaptureSession {
  id: string;
  name: string;
  description?: string;
  createdAt: Date;
  updatedAt: Date;
  isActive: boolean;
  retention?: RetentionPolicy;
  metadata?: Record<string, any>;
}

CapturedEmail

interface CapturedEmail {
  id: string;
  sessionId: string;
  content: string;
  source: EmailSource;
  metadata?: EmailMetadata;
  capturedAt: Date;
  size: number;
}

RetentionPolicy

interface RetentionPolicy {
  maxAge?: number;        // Max age in milliseconds
  maxCount?: number;      // Max number of emails
  autoCleanup?: boolean;  // Auto-cleanup on capture
}

Configuration

Environment Variables

The package respects these environment variables:

  • EMAIL_CAPTURE_MAX_SIZE: Maximum email size in bytes (default: 10MB)
  • EMAIL_CAPTURE_DEFAULT_RETENTION: Default retention period in milliseconds
  • EMAIL_CAPTURE_AUTO_CLEANUP: Enable auto-cleanup by default (true/false)

Storage Backends

By default, the package uses in-memory storage. You can implement custom storage backends:

import { StorageBackend } from '@bernierllc/email-capture';

class CustomStorage implements StorageBackend {
  // Implement all required methods
  async createSession(config: SessionConfig): Promise<EmailCaptureSession> {
    // Custom implementation
  }
  
  // ... other methods
}

const capture = new EmailCapture(new CustomStorage());

Integration Status

  • Logger integration: not-applicable - Core utility package with minimal logging needs. Uses console for critical errors only.
  • Docs-Suite: ready - Complete API documentation with TypeScript support, exportable as TypeDoc format.
  • NeverHub integration: not-applicable - Core atomic utility with no external service dependencies. Designed for direct integration by service packages. Uses graceful degradation patterns when @bernierllc/neverhub-adapter is not available.

Error Handling

All methods follow a consistent error handling pattern. Errors are thrown with descriptive messages and error codes:

try {
  await capture.captureEmail('invalid-session', email);
} catch (error) {
  console.error('Capture failed:', error.message);
  // Error includes context: session ID, email details, etc.
}

Security Considerations

  • Email content is stored as provided - no automatic sanitization
  • Session IDs use cryptographically secure random generation
  • No external network connections required
  • Memory storage is cleared on process exit

Testing

The package includes comprehensive tests with 95+ test cases covering:

  • Session management and lifecycle
  • Email capture and metadata extraction
  • Query operations with various filters
  • Export functionality in all formats
  • Error handling and edge cases
  • Storage backend compliance

Run tests:

npm test                # Run all tests
npm run test:coverage   # Run with coverage report
npm run test:watch      # Run in watch mode

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

This package is part of the BernierLLC tools ecosystem and follows the BernierLLC MECE architecture principles for atomic, reusable utilities.