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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@bernierllc/email-validator

v1.0.5

Published

Atomic utility package for validating email content, structure, and compliance

Readme

@bernierllc/email-validator

Comprehensive email validation utilities for testing email content, headers, structure, and quality.

Installation

npm install @bernierllc/email-validator

Quick Start

import { validateEmail } from '@bernierllc/email-validator';

const emailContent = `From: [email protected]
To: [email protected]
Subject: Test Email
Date: Mon, 1 Jan 2025 10:00:00 +0000
Content-Type: text/plain

This is a test email.`;

const result = await validateEmail(emailContent, {
  maxScore: 85,
  strictMode: true
});

if (result.valid) {
  console.log(`Email validation passed with score: ${result.score}/100`);
} else {
  console.log('Email validation failed:');
  result.errors.forEach(error => {
    console.log(`- ${error.message}`);
  });
}

Features

  • Comprehensive Validation: Headers, content, structure, and attachments
  • Scoring System: 0-100 quality score with configurable thresholds
  • Security Checks: XSS detection, dangerous attachments, suspicious links
  • Test Assertions: Flexible assertion framework for email testing
  • Batch Processing: Validate multiple emails efficiently
  • Detailed Reporting: Categorized issues (errors, warnings, info)
  • Rule-Based Architecture: Enable/disable specific validation rules

API Reference

validateEmail(content, options?)

Validate a single email and return comprehensive results.

Parameters

  • content (string | Buffer) - Raw email content
  • options (EmailValidationOptions) - Validation options

Options

interface EmailValidationOptions {
  rules?: string[];           // Specific rules to apply
  skipRules?: string[];       // Rules to skip
  maxScore?: number;          // Minimum score for valid (default: 70)
  strictMode?: boolean;       // Strict validation mode
  contextHints?: {
    expectedSender?: string;
    expectedRecipient?: string;
    expectedSubjectPattern?: string;
    allowedAttachmentTypes?: string[];
    maxAttachmentSize?: number;
  };
}

Returns

interface ValidationResult {
  valid: boolean;             // Overall validation result
  score: number;              // Quality score (0-100)
  errors: ValidationError[];  // Critical issues
  warnings: ValidationWarning[]; // Non-critical issues  
  info: ValidationInfo[];     // Informational notes
  metadata: {
    rulesApplied: string[];
    processingTime: number;
    emailSize: number;
  };
}

EmailValidator Class

For advanced usage and batch processing:

import { EmailValidator } from '@bernierllc/email-validator';

const validator = new EmailValidator();

// Single email validation
const result = await validator.validateEmail(emailContent, options);

// Batch validation
const emails = [
  { id: 'email1', content: email1Content },
  { id: 'email2', content: email2Content }
];
const results = await validator.validateBatch(emails, options);

// Get available validation rules
const rules = validator.getAvailableRules();

Email Test Assertions

The package includes a powerful assertion framework for email testing:

import { assertEmail, runEmailTest } from '@bernierllc/email-validator';

// Single assertion
const assertion = {
  type: 'header',
  field: 'from',
  condition: 'equals',
  expected: '[email protected]'
};

const result = await assertEmail(emailContent, assertion);
console.log(result.passed); // true/false

// Test suite
const testSuite = {
  name: 'Email Validation Test',
  email: emailContent,
  assertions: [
    {
      type: 'header',
      field: 'subject',
      condition: 'contains',
      expected: 'Test'
    },
    {
      type: 'content',
      field: 'text',
      condition: 'matches',
      expected: /test email/i
    },
    {
      type: 'attachment',
      field: 'count',
      condition: 'equals',
      expected: 0
    }
  ]
};

const suiteResult = await runEmailTest(testSuite);
console.log(`${suiteResult.summary.passed}/${suiteResult.summary.total} tests passed`);

Assertion Types

Header Assertions

{
  type: 'header',
  field: 'from' | 'to' | 'subject' | 'date' | string,
  condition: 'equals' | 'contains' | 'matches' | 'exists' | 'not-exists',
  expected: any
}

Content Assertions

{
  type: 'content',
  field: 'text' | 'html' | 'raw',
  condition: 'equals' | 'contains' | 'matches' | 'exists',
  expected: any
}

Attachment Assertions

{
  type: 'attachment',
  field: 'count' | 'total-size' | 'filename[0]' | 'filename[1]' | ...,
  condition: 'equals' | 'greater-than' | 'less-than' | 'contains',
  expected: any
}

Structure Assertions

{
  type: 'structure',
  field: 'size' | 'isMultipart' | 'hasAttachments' | 'encoding',
  condition: 'equals' | 'greater-than' | 'less-than',
  expected: any
}

Validation Rules

Header Rules

  • required-headers: Validates required headers (From, To, Subject, Date)
  • valid-email-addresses: Validates email address formats
  • date-header: Validates Date header format and reasonableness
  • message-id-format: Validates Message-ID header format
  • content-type-header: Validates Content-Type header
  • subject-length: Validates subject line length (max 78 characters)

Content Rules

  • content-presence: Ensures email has content
  • html-validation: Validates HTML structure and security
  • text-content: Validates plain text quality
  • link-validation: Validates links and detects security issues

Structure Rules

  • email-size: Validates email size limits
  • multipart-structure: Validates multipart email structure
  • encoding-validation: Validates character encoding
  • header-consistency: Validates consistency between headers and content

Attachment Rules

  • attachment-size: Validates attachment sizes
  • attachment-type: Validates file types and detects dangerous attachments
  • attachment-count: Validates number of attachments
  • inline-attachments: Validates inline attachments and embedded images

Usage Examples

Security-Focused Validation

const result = await validateEmail(emailContent, {
  strictMode: true,
  maxScore: 90,
  rules: [
    'valid-email-addresses',
    'html-validation',
    'link-validation',
    'attachment-type'
  ]
});

if (!result.valid) {
  // Handle security issues
  const securityIssues = result.errors.filter(e => 
    ['SCRIPT_TAG', 'JAVASCRIPT_URL', 'DANGEROUS_ATTACHMENT_TYPE'].includes(e.code)
  );
}

Content Quality Validation

const result = await validateEmail(emailContent, {
  skipRules: ['attachment-size'], // Skip attachment size checks
  contextHints: {
    expectedSender: '[email protected]',
    maxAttachmentSize: 5 * 1024 * 1024 // 5MB limit
  }
});

// Review quality score
if (result.score < 80) {
  console.log('Email quality could be improved:');
  result.warnings.forEach(warning => {
    console.log(`- ${warning.message}`);
  });
}

Email Testing Workflow

import { EmailAssertions } from '@bernierllc/email-validator';

const assertions = new EmailAssertions();

// Test multiple emails
const testSuites = [
  {
    name: 'Welcome Email Test',
    email: welcomeEmailContent,
    assertions: [
      { type: 'header', field: 'from', condition: 'contains', expected: 'welcome' },
      { type: 'content', field: 'html', condition: 'contains', expected: 'Welcome' }
    ]
  },
  {
    name: 'Newsletter Test',
    email: newsletterContent,
    assertions: [
      { type: 'header', field: 'subject', condition: 'matches', expected: /newsletter/i },
      { type: 'attachment', field: 'count', condition: 'equals', expected: 0 }
    ]
  }
];

const results = await assertions.runTestSuites(testSuites);
const allPassed = results.every(r => r.passed);

Custom Rule Selection

// Only validate headers and content
const result = await validateEmail(emailContent, {
  rules: [
    'required-headers',
    'valid-email-addresses',
    'content-presence',
    'html-validation'
  ]
});

// Skip specific rules
const result2 = await validateEmail(emailContent, {
  skipRules: ['subject-length', 'attachment-count']
});

Error Codes Reference

Header Errors

  • MISSING_FROM_HEADER, MISSING_TO_HEADER, MISSING_SUBJECT_HEADER, MISSING_DATE_HEADER
  • INVALID_EMAIL_ADDRESS
  • INVALID_DATE_FORMAT, FUTURE_DATE
  • INVALID_MESSAGE_ID_FORMAT
  • SUBJECT_TOO_LONG, EMPTY_SUBJECT

Content Errors

  • NO_CONTENT
  • SCRIPT_TAG, JAVASCRIPT_URL, EVENT_HANDLERS
  • INSECURE_LINKS, URL_SHORTENERS

Structure Errors

  • LARGE_EMAIL_SIZE, EXCESSIVE_EMAIL_SIZE
  • MISSING_MULTIPART_BOUNDARY
  • REPLACEMENT_CHARACTERS, ENCODING_ARTIFACTS

Attachment Errors

  • LARGE_ATTACHMENT, EXCESSIVE_ATTACHMENT_SIZE
  • DANGEROUS_ATTACHMENT_TYPE, SUSPICIOUS_ATTACHMENT_EXTENSION
  • MANY_ATTACHMENTS, EXCESSIVE_ATTACHMENTS

Performance

  • Efficient parsing using @bernierllc/email-parser
  • Parallel rule execution for better performance
  • Memory-conscious attachment handling
  • Processing time tracking included in results

Dependencies

  • @bernierllc/email-parser - Email parsing functionality
  • zod - Schema validation

Integration Status

  • Logger integration: not-applicable - Pure validation utility with no side effects or logging requirements. The package performs synchronous validation and returns structured results without need for @bernierllc/logger integration.
  • Docs-Suite: ready - TypeScript documentation exported via TypeDoc, API reference in README
  • NeverHub integration: not-applicable - Core validation utility with no service discovery needs. The package provides atomic validation functions following the core package pattern and does not require @bernierllc/neverhub-adapter or detectNeverHub capabilities.

License

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