@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-validatorQuick 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 contentoptions(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_HEADERINVALID_EMAIL_ADDRESSINVALID_DATE_FORMAT,FUTURE_DATEINVALID_MESSAGE_ID_FORMATSUBJECT_TOO_LONG,EMPTY_SUBJECT
Content Errors
NO_CONTENTSCRIPT_TAG,JAVASCRIPT_URL,EVENT_HANDLERSINSECURE_LINKS,URL_SHORTENERS
Structure Errors
LARGE_EMAIL_SIZE,EXCESSIVE_EMAIL_SIZEMISSING_MULTIPART_BOUNDARYREPLACEMENT_CHARACTERS,ENCODING_ARTIFACTS
Attachment Errors
LARGE_ATTACHMENT,EXCESSIVE_ATTACHMENT_SIZEDANGEROUS_ATTACHMENT_TYPE,SUSPICIOUS_ATTACHMENT_EXTENSIONMANY_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 functionalityzod- 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.
