Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@devmehq/email-validator-js

devmehq6.6kBSL 1.12.10.2TypeScript support: included

Advanced email validation with MX records, SMTP verification, disposable email detection, batch processing, and caching. Production-ready with TypeScript support.

email-validation, email-verification, email-validator, email-checker, smtp-verification, mx-records, disposable-emails, free-emails, batch-validation, email-typos, email-regex, typescript, cache, rfc5321

readme

Advanced Email Validator

NPM version Build Status Downloads UNPKG TypeScript License

🚀 Advanced email validation library for Node.js with MX record checking, SMTP verification, disposable email detection, and much more. Now with batch processing, advanced caching, and detailed error reporting.

📋 Table of Contents

Features

✅ Check email address validity

✅ Check email address domain validity in domain TLD list

✅ Check email address MX records

✅ Check email address SMTP connection

✅ Check email address disposable or burnable status

✅ Check email address free email provider status

NEW: Batch email verification with concurrency control

NEW: Detailed verification results with error codes

NEW: Built-in caching for improved performance

NEW: Automatic retry mechanism for transient failures

NEW: RFC 5321 compliant validation

NEW: Enhanced name detection from email addresses with composite name support

NEW: Domain typo detection and suggestions with caching

NEW: Get domain age via WHOIS lookup

NEW: Get domain registration status via WHOIS lookup

NEW: Serverless support for AWS Lambda, Vercel Edge, Cloudflare Workers, and more

Use Cases

  • Increase delivery rate of email campaigns by removing spam emails
  • Increase email open rate and your marketing IPs reputation
  • Protect your website from spam, bots and fake emails
  • Protect your product signup form from fake emails
  • Protect your website forms from fake emails
  • Protect your self from fraud orders and accounts using fake emails
  • Integrate email address verification into your website forms
  • Integrate email address verification into your backoffice administration and order processing

API / Cloud Hosted Service

We offer this email verification and validation and more advanced features in our Scalable Cloud API Service Offering - You could try it here Email Verification


License

email-validator-js is licensed under Business Source License 1.1.

Quick License Summary

Use Case Is a commercial license required?
Exploring email-validator-js for your own research, hobbies, and testing purposes No
Using email-validator-js to build a proof-of-concept application No
Using email-validator-js to build revenue-generating applications Yes
Using email-validator-js to build software that is provided as a service (SaaS) Yes
Forking email-validator-js for any production purposes Yes

📄 For commercial licensing, visit dev.me/license/email-validator or contact us at sales@dev.me.


Installation

Install the module through Yarn:

yarn add @devmehq/email-validator-js

Or NPM:

npm install @devmehq/email-validator-js

Requirements

  • Node.js >= 12.0
  • TypeScript >= 4.0 (for TypeScript users)

Build System

  • Uses Rollup for efficient bundling and tree-shaking
  • Optimized build output with separate CJS and ESM modules
  • Serverless builds for edge environments

Quick Start

import { verifyEmail } from '@devmehq/email-validator-js';

// Basic usage
const result = await verifyEmail({
  emailAddress: 'user@example.com',
  verifyMx: true,
  verifySmtp: true,
  timeout: 3000
});

console.log(result.validFormat); // true
console.log(result.validMx);     // true
console.log(result.validSmtp);   // true or false

API Reference

Core Functions

verifyEmail(params: IVerifyEmailParams): Promise<IVerifyEmailResult>

Basic email verification with backward compatibility.

Parameters:

  • emailAddress (string, required): Email address to verify
  • timeout (number): Timeout in milliseconds (default: 4000)
  • verifyMx (boolean): Check MX records (default: false)
  • verifySmtp (boolean): Verify SMTP connection (default: false)
  • smtpPort (number): Custom SMTP port
  • debug (boolean): Enable debug logging (default: false)
  • detectName (boolean): Detect names from email address (default: false)
  • nameDetectionMethod (function): Custom name detection method
  • suggestDomain (boolean): Enable domain typo suggestions (default: false)
  • domainSuggestionMethod (function): Custom domain suggestion method
  • commonDomains (string[]): Custom list of domains for suggestions

Returns:

{
  validFormat: boolean;
  validMx: boolean | null;
  validSmtp: boolean | null;
  detectedName?: DetectedName | null;
  domainSuggestion?: DomainSuggestion | null;
}

verifyEmailDetailed(params: IVerifyEmailParams): Promise<DetailedVerificationResult>

Advanced verification with detailed results and error codes.

Additional Parameters:

  • checkDisposable (boolean): Check for disposable emails (default: true)
  • checkFree (boolean): Check for free email providers (default: true)
  • retryAttempts (number): Retry attempts for failures (default: 1)
  • detectName (boolean): Detect names from email address (default: false)
  • suggestDomain (boolean): Enable domain typo suggestions (default: true in detailed mode)

Returns:

{
  valid: boolean;
  email: string;
  format: {
    valid: boolean;
    error?: VerificationErrorCode;
  };
  domain: {
    valid: boolean | null;
    mxRecords?: string[];
    error?: VerificationErrorCode;
  };
  smtp: {
    valid: boolean | null;
    error?: VerificationErrorCode;
  };
  disposable: boolean;
  freeProvider: boolean;
  detectedName?: DetectedName | null;
  domainSuggestion?: DomainSuggestion | null;
  metadata?: {
    verificationTime: number;
    cached: boolean;
  };
}

verifyEmailBatch(params: IBatchVerifyParams): Promise<BatchVerificationResult>

Verify multiple emails in parallel with concurrency control.

Parameters:

  • emailAddresses (string[], required): Array of emails to verify
  • concurrency (number): Parallel processing limit (default: 5)
  • detailed (boolean): Return detailed results (default: false)
  • detectName (boolean): Detect names from email addresses
  • suggestDomain (boolean): Enable domain typo suggestions
  • Other parameters from verifyEmail

Returns:

{
  results: Map<string, DetailedVerificationResult | IVerifyEmailResult>;
  summary: {
    total: number;
    valid: number;
    invalid: number;
    errors: number;
    processingTime: number;
  };
}

Name Detection Functions

detectName(email: string): DetectedName | null

Detect first and last name from email address.

const name = detectName('john.doe@example.com');
// Returns: { firstName: 'John', lastName: 'Doe', confidence: 0.9 }

Detection Patterns:

  • Dot separator: john.doe → John Doe (90% confidence)
  • Underscore: jane_smith → Jane Smith (80% confidence)
  • Hyphen: mary-johnson → Mary Johnson (80% confidence)
  • CamelCase: johnDoe → John Doe (70% confidence)
  • Composite names: mo1.test2 → Mo1 Test2 (60% confidence)
  • Mixed alphanumeric: user1.admin2 → User1 Admin2 (60% confidence)
  • Smart number handling: john.doe123 → John Doe (80% confidence)
  • Contextual suffixes: john.doe.dev → John Doe (70% confidence)
  • Single name: alice → Alice (50% confidence)

Enhanced Features:

  • Removes email aliases (text after +)
  • Smart handling of numbers (preserves in composite names, removes trailing)
  • Recognizes contextual suffixes (dev, company, sales, years)
  • Handles complex multi-part names
  • Proper name capitalization
  • Filters out common non-name prefixes (admin, support, info, etc.)

detectNameFromEmail(params: IDetectNameParams): DetectedName | null

Advanced name detection with custom method support.

const customMethod = (email: string) => {
  // Your custom logic
  return { firstName: 'Custom', lastName: 'Name', confidence: 1.0 };
};

const name = detectNameFromEmail({
  email: 'user@example.com',
  customMethod: customMethod
});

Parameters:

  • email (string): Email address
  • customMethod (function): Custom detection logic

defaultNameDetectionMethod(email: string): DetectedName | null

The default name detection implementation, exported for custom extensions.

Domain Suggestion Functions

suggestEmailDomain(email: string, commonDomains?: string[]): DomainSuggestion | null

Detect and suggest corrections for misspelled email domains.

const suggestion = suggestEmailDomain('user@gmial.com');
// Returns: { original: 'user@gmial.com', suggested: 'user@gmail.com', confidence: 0.95 }

// With custom domain list
const customDomains = ['company.com', 'enterprise.org'];
const customSuggestion = suggestEmailDomain('user@compny.com', customDomains);

Features:

  • 70+ common email domains by default
  • String similarity algorithm
  • Known typo patterns (95% confidence)
  • Smart thresholds based on domain length
  • 24-hour caching for performance

suggestDomain(params: ISuggestDomainParams): DomainSuggestion | null

Advanced domain suggestion with custom method support.

const suggestion = suggestDomain({
  domain: 'gmial.com',
  customMethod: myCustomMethod,
  commonDomains: ['company.com']
});

Parameters:

  • domain (string): Domain to check
  • customMethod (function): Custom suggestion logic
  • commonDomains (string[]): Custom domain list

defaultDomainSuggestionMethod(domain: string, commonDomains?: string[]): DomainSuggestion | null

The default domain suggestion implementation, exported for custom extensions.

isCommonDomain(domain: string, commonDomains?: string[]): boolean

Check if a domain is in the common domains list.

isCommonDomain('gmail.com'); // true
isCommonDomain('mycompany.com'); // false

// With custom list
isCommonDomain('mycompany.com', ['mycompany.com']); // true

getDomainSimilarity(domain1: string, domain2: string): number

Calculate similarity score between two domains (0-1).

getDomainSimilarity('gmail.com', 'gmial.com'); // 0.8
getDomainSimilarity('gmail.com', 'yahoo.com'); // 0.3

WHOIS Functions

Note: WHOIS functions use PSL (Public Suffix List) validation to ensure domain validity before performing lookups. Invalid domains or domains without valid TLDs will return null.

getDomainAge(domain: string, timeout?: number): Promise<DomainAgeInfo | null>

Get domain age information via WHOIS lookup.

const ageInfo = await getDomainAge('example.com');
// Returns:
// {
//   domain: 'example.com',
//   creationDate: Date,
//   ageInDays: 7890,
//   ageInYears: 21.6,
//   expirationDate: Date,
//   updatedDate: Date
// }

// Works with email addresses and URLs too
await getDomainAge('user@example.com');
await getDomainAge('https://example.com/path');

Parameters:

  • domain (string): Domain, email, or URL to check
  • timeout (number): Timeout in milliseconds (default: 5000)

Returns: DomainAgeInfo object or null if lookup fails

getDomainRegistrationStatus(domain: string, timeout?: number): Promise<DomainRegistrationInfo | null>

Get detailed domain registration status via WHOIS.

const status = await getDomainRegistrationStatus('example.com');
// Returns:
// {
//   domain: 'example.com',
//   isRegistered: true,
//   isAvailable: false,
//   status: ['clientTransferProhibited'],
//   registrar: 'Example Registrar',
//   nameServers: ['ns1.example.com', 'ns2.example.com'],
//   expirationDate: Date,
//   isExpired: false,
//   daysUntilExpiration: 365,
//   isPendingDelete: false,
//   isLocked: true
// }

Parameters:

  • domain (string): Domain, email, or URL to check
  • timeout (number): Timeout in milliseconds (default: 5000)

Returns: DomainRegistrationInfo object or null if lookup fails

Features:

  • Supports 50+ TLDs with specific WHOIS servers
  • Automatic WHOIS server discovery for unknown TLDs
  • Parses various WHOIS response formats
  • Uses PSL (Public Suffix List) for domain validation
  • 1-hour result caching
  • Extracts domain from emails and URLs

Utility Functions

isDisposableEmail(emailOrDomain: string): boolean

Check if email uses a disposable provider.

isDisposableEmail('user@tempmail.com'); // true
isDisposableEmail('tempmail.com'); // true
isDisposableEmail('gmail.com'); // false

isFreeEmail(emailOrDomain: string): boolean

Check if email uses a free provider.

isFreeEmail('user@gmail.com'); // true
isFreeEmail('yahoo.com'); // true
isFreeEmail('corporate.com'); // false

isValidEmail(emailAddress: string): boolean

Validate email format (RFC 5321 compliant).

isValidEmail('user@example.com'); // true
isValidEmail('invalid.email'); // false

Validation Rules:

  • Proper @ symbol placement
  • Local part max 64 characters
  • Domain max 253 characters
  • No consecutive dots
  • No leading/trailing dots
  • Valid domain TLD

isValidEmailDomain(emailOrDomain: string): boolean

Validate if a domain has a valid TLD.

isValidEmailDomain('example.com'); // true
isValidEmailDomain('example.invalid'); // false

clearAllCaches(): void

Clear all internal caches (including domain suggestions).

clearAllCaches();

Types and Interfaces

DetectedName

interface DetectedName {
  firstName?: string;
  lastName?: string;
  confidence: number; // 0-1 scale
}

DomainSuggestion

interface DomainSuggestion {
  original: string;
  suggested: string;
  confidence: number; // 0-1 scale
}

NameDetectionMethod

type NameDetectionMethod = (email: string) => DetectedName | null;

DomainSuggestionMethod

type DomainSuggestionMethod = (domain: string) => DomainSuggestion | null;

DomainAgeInfo

interface DomainAgeInfo {
  domain: string;
  creationDate: Date;
  ageInDays: number;
  ageInYears: number;
  expirationDate: Date | null;
  updatedDate: Date | null;
}

DomainRegistrationInfo

interface DomainRegistrationInfo {
  domain: string;
  isRegistered: boolean;
  isAvailable: boolean;
  status: string[];
  registrar: string | null;
  nameServers: string[];
  expirationDate: Date | null;
  isExpired: boolean;
  daysUntilExpiration: number | null;
  isPendingDelete?: boolean;
  isLocked?: boolean;
}

Constants

COMMON_EMAIL_DOMAINS

Array of 70+ common email domains used for typo detection.

import { COMMON_EMAIL_DOMAINS } from '@devmehq/email-validator-js';

console.log(COMMON_EMAIL_DOMAINS);
// ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', ...]

Includes:

  • Popular free providers (Gmail, Yahoo, Outlook, etc.)
  • Business email services (Google Workspace, Microsoft, etc.)
  • Privacy-focused providers (ProtonMail, Tutanota, etc.)
  • Regional providers (GMX, Yandex, QQ, etc.)
  • Hosting services (GoDaddy, Namecheap, etc.)

Error Codes

enum VerificationErrorCode {
  INVALID_FORMAT = 'INVALID_FORMAT',
  INVALID_DOMAIN = 'INVALID_DOMAIN',
  NO_MX_RECORDS = 'NO_MX_RECORDS',
  SMTP_CONNECTION_FAILED = 'SMTP_CONNECTION_FAILED',
  SMTP_TIMEOUT = 'SMTP_TIMEOUT',
  MAILBOX_NOT_FOUND = 'MAILBOX_NOT_FOUND',
  MAILBOX_FULL = 'MAILBOX_FULL',
  NETWORK_ERROR = 'NETWORK_ERROR',
  DISPOSABLE_EMAIL = 'DISPOSABLE_EMAIL',
  FREE_EMAIL_PROVIDER = 'FREE_EMAIL_PROVIDER'
}

Configuration Options

timeout

Set a timeout in milliseconds for the smtp connection. Default: 4000.

verifyMx

Enable or disable domain checking. This is done in two steps:

  1. Verify that the domain does indeed exist
  2. Verify that the domain has valid MX records

Default: false.

verifySmtp

Enable or disable mailbox checking. Only a few SMTP servers allow this, and even then whether it works depends on your IP's reputation with those servers. This library performs a best effort validation:

  • It returns null for Yahoo addresses, for failed connections, for unknown SMTP errors
  • It returns true for valid SMTP responses
  • It returns false for SMTP errors specific to the address's formatting or mailbox existence

Default: false.

checkDisposable (NEW)

Check if the email domain is a known disposable email provider. Default: false.

checkFree (NEW)

Check if the email domain is a known free email provider. Default: false.

detailed (NEW)

Return detailed verification results with error codes. Default: false.

retryAttempts (NEW)

Number of retry attempts for transient failures. Default: 1.

Examples

Basic Usage

import { verifyEmail } from '@devmehq/email-validator-js';

const { validFormat, validSmtp, validMx } = await verifyEmail({ 
  emailAddress: 'foo@email.com', 
  verifyMx: true, 
  verifySmtp: true, 
  timeout: 3000 
});
// validFormat: true
// validMx: true
// validSmtp: true

Detailed Verification (NEW)

import { verifyEmailDetailed } from '@devmehq/email-validator-js';

const result = await verifyEmailDetailed({
  emailAddress: 'foo@email.com',
  verifyMx: true,
  verifySmtp: true,
  checkDisposable: true,
  checkFree: true
});
// result.valid: true
// result.disposable: false
// result.freeProvider: false
// result.domain.mxRecords: ['mx1.email.com', 'mx2.email.com']
// result.metadata.verificationTime: 125

Batch Verification (NEW)

import { verifyEmailBatch } from '@devmehq/email-validator-js';

const emails = ['user1@gmail.com', 'user2@example.com', 'invalid@fake.com'];

const result = await verifyEmailBatch({
  emailAddresses: emails,
  concurrency: 5,
  verifyMx: true,
  detailed: true
});
// result.summary.valid: 2
// result.summary.invalid: 1
// result.summary.processingTime: 234

Name Detection (ENHANCED)

import { detectName, verifyEmailDetailed } from '@devmehq/email-validator-js';

// Standalone name detection - now with composite name support
const name = detectName('john.doe@example.com');
// name: { firstName: 'John', lastName: 'Doe', confidence: 0.9 }

// Handle alphanumeric composite names
const composite = detectName('mo1.test2@example.com');
// composite: { firstName: 'Mo1', lastName: 'Test2', confidence: 0.6 }

// Smart handling of numbers and suffixes
const withNumbers = detectName('john.doe123@example.com');
// withNumbers: { firstName: 'John', lastName: 'Doe', confidence: 0.8 }

const withSuffix = detectName('jane.smith.dev@example.com');
// withSuffix: { firstName: 'Jane', lastName: 'Smith', confidence: 0.7 }

// Integrated with email verification
const result = await verifyEmailDetailed({
  emailAddress: 'jane_smith@example.com',
  detectName: true
});
// result.detectedName: { firstName: 'Jane', lastName: 'Smith', confidence: 0.8 }

// Custom detection method
const customMethod = (email: string) => {
  // Your custom logic here
  return { firstName: 'Custom', lastName: 'Name', confidence: 1.0 };
};

const resultCustom = await verifyEmail({
  emailAddress: 'user@example.com',
  detectName: true,
  nameDetectionMethod: customMethod
});

Domain Typo Detection (NEW)

import { suggestEmailDomain, verifyEmailDetailed } from '@devmehq/email-validator-js';

// Standalone domain suggestion
const suggestion = suggestEmailDomain('user@gmial.com');
// suggestion: { original: 'user@gmial.com', suggested: 'user@gmail.com', confidence: 0.95 }

// Integrated with email verification (enabled by default in detailed mode)
const result = await verifyEmailDetailed({
  emailAddress: 'john@yaho.com',
  suggestDomain: true  // Default: true for detailed verification
});
// result.domainSuggestion: { original: 'john@yaho.com', suggested: 'john@yahoo.com', confidence: 0.9 }

// With custom domain list
const customDomains = ['company.com', 'enterprise.org'];
const resultCustom = await verifyEmail({
  emailAddress: 'user@compny.com',
  suggestDomain: true,
  commonDomains: customDomains
});
// resultCustom.domainSuggestion: { suggested: 'user@company.com', confidence: 0.85 }

Handling Different Validation Scenarios

When a domain does not exist or has no MX records:

const result = await verifyEmail({ 
  emailAddress: 'foo@bad-domain.com', 
  verifyMx: true, 
  verifySmtp: true 
});
// validFormat: true
// validMx: false
// validSmtp: null (couldn't be performed)

Using Detailed Verification for Better Insights

const detailed = await verifyEmailDetailed({
  emailAddress: 'user@suspicious-domain.com',
  verifyMx: true,
  verifySmtp: true,
  checkDisposable: true,
  checkFree: true
});

if (!detailed.valid) {
  switch (detailed.domain.error) {
    case VerificationErrorCode.DISPOSABLE_EMAIL:
      console.log('Rejected: Disposable email');
      break;
    case VerificationErrorCode.NO_MX_RECORDS:
      console.log('Rejected: Invalid domain');
      break;
    case VerificationErrorCode.MAILBOX_NOT_FOUND:
      console.log('Rejected: Mailbox does not exist');
      break;
  }
}

Batch Processing for Large Lists

const emails = [
  'valid@gmail.com',
  'test@tempmail.com',
  'user@company.com',
  // ... hundreds more
];

const batch = await verifyEmailBatch({
  emailAddresses: emails,
  concurrency: 10, // Process 10 emails simultaneously
  verifyMx: true,
  checkDisposable: true,
  detailed: true
});

console.log(`Processed ${batch.summary.total} emails`);
console.log(`Valid: ${batch.summary.valid}`);
console.log(`Invalid: ${batch.summary.invalid}`);
console.log(`Time: ${batch.summary.processingTime}ms`);

// Filter out invalid emails
const validEmails = [];
for (const [email, result] of batch.results) {
  if (result.valid) {
    validEmails.push(email);
  }
}

Performance Optimization with Caching

// First verification - hits DNS and SMTP
const first = await verifyEmail({ 
  emailAddress: 'cached@example.com',
  verifyMx: true 
});
// Takes ~500ms

// Second verification - uses cache
const second = await verifyEmail({ 
  emailAddress: 'cached@example.com',
  verifyMx: true 
});
// Takes ~1ms (cached)

// Clear cache if needed
clearAllCaches();

Note: Yahoo, Hotmail, and some providers always return validSmtp: true as they don't allow mailbox verification.

🌐 Serverless Deployment

The package includes serverless adapters for major cloud platforms. The serverless implementation provides email validation without Node.js dependencies, making it suitable for edge computing environments.

AWS Lambda

import { apiGatewayHandler } from '@devmehq/email-validator-js/serverless/aws';

export const handler = apiGatewayHandler;

Vercel Edge Functions

import { edgeHandler } from '@devmehq/email-validator-js/serverless/vercel';

export const config = {
  runtime: 'edge',
};

export default edgeHandler;

Cloudflare Workers

import { workerHandler } from '@devmehq/email-validator-js/serverless/cloudflare';

export default {
  async fetch(request, env, ctx) {
    return workerHandler(request, env, ctx);
  },
};

Features in Serverless Mode

  • ✅ Syntax validation
  • ✅ Typo detection and domain suggestions
  • ✅ Disposable email detection (full database)
  • ✅ Free email provider detection (full database)
  • ✅ Batch processing
  • ✅ Built-in caching
  • ❌ MX record validation (requires DNS)
  • ❌ SMTP verification (requires TCP sockets)

For detailed serverless documentation and more platform examples, see docs/SERVERLESS.md.

📊 Performance & Caching

The library includes intelligent caching to improve performance:

Cache Type TTL Description
MX Records 1 hour DNS MX record lookups
Disposable 24 hours Disposable email checks
Free Provider 24 hours Free email provider checks
Domain Valid 24 hours Domain validation results
SMTP 30 minutes SMTP verification results
Domain Suggestions 24 hours Domain typo suggestions

Performance Tips

  1. Use Batch Processing: For multiple emails, use verifyEmailBatch() for parallel processing
  2. Enable Caching: Caching is automatic and reduces repeated lookups by ~90%
  3. Adjust Timeouts: Lower timeouts for faster responses, higher for accuracy
  4. Skip SMTP: If you only need format/MX validation, skip SMTP for 10x faster results
  5. Domain Suggestions: Cached for 24 hours to avoid recalculating similarity scores
  6. Name Detection: Lightweight operation with minimal performance impact

🗂️ Email Provider Databases

Disposable Email Providers (✅ Always Updated)

View List - 5,000+ disposable email domains

Free Email Providers (✅ Always Updated)

View List - 1,000+ free email providers

Common Email Domains (✅ NEW)

Access the list of 70+ common email domains used for typo detection:

import { COMMON_EMAIL_DOMAINS } from '@devmehq/email-validator-js';

console.log(COMMON_EMAIL_DOMAINS);
// ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', ...]

// Use with your own domain validation
const isCommon = COMMON_EMAIL_DOMAINS.includes('gmail.com'); // true

Testing

Run the test suite:

yarn test

Run with coverage:

yarn test --coverage

Lint the code:

yarn lint
yarn lint-fix  # Auto-fix issues

Build the project:

yarn build

Development

Project Structure

email-validator-js/
├── src/                 # Source code
│   ├── index.ts        # Main entry point
│   ├── smtp.ts         # SMTP verification
│   ├── dns.ts          # DNS/MX lookups
│   ├── validator.ts    # Format validation
│   ├── cache.ts        # Caching system
│   ├── batch.ts        # Batch processing
│   └── types.ts        # TypeScript types
├── __tests__/          # Test files
├── examples/           # Usage examples
└── dist/              # Compiled output

Scripts

yarn build      # Build TypeScript with Rollup
yarn test       # Run tests with Jest
yarn lint       # Run ESLint
yarn lint-fix   # Fix ESLint issues
yarn typecheck  # Run TypeScript type checking

Build Optimizations

  • Type Safety: Improved type inference reduces redundant type declarations
  • Bundle Size: Optimized with tree-shaking and minification
  • Performance: Faster builds with parallelized compilation
  • Code Quality: Strict TypeScript mode with comprehensive type checking

Contributing

We welcome contributions! Please feel free to open an issue or create a pull request and fix bugs or add features. All contributions are welcome!

How to Contribute

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Setup

# Clone the repo
git clone https://github.com/devmehq/email-validator-js.git
cd email-validator-js

# Install dependencies
yarn install

# Run tests
yarn test

# Build
yarn build

Support

For issues, questions, or commercial licensing:

🐛 Open an Issue 📧 Email Support 📄 Commercial License 🌐 Visit Dev.me

LICENSE

Business Source License 1.1 - see LICENSE file for details.

📝 When Do You Need a Commercial License?

The BSL allows use only for non-production purposes. Here's a comprehensive guide to help you understand when you need a commercial license:

Use Case Commercial License Required? Details
Personal & Learning |
🔬 Exploring email-validator-js for research or learning No Use freely for educational purposes
🎨 Personal hobby projects (non-commercial) No Build personal tools and experiments
🧪 Testing and evaluation in development environment No Test all features before purchasing
Development & Prototyping |
💡 Building proof-of-concept applications No Create demos and prototypes
🛠️ Internal tools (not customer-facing) No Use for internal development tools
📚 Open source projects (non-commercial) No Contribute to the community
Commercial & Production Use |
💰 Revenue-generating applications Yes Any app that generates income
☁️ Software as a Service (SaaS) products Yes Cloud-based service offerings
📦 Distributed commercial software Yes Software sold to customers
🏢 Enterprise production systems Yes Business-critical applications
🔄 Forking for commercial purposes Yes Creating derivative commercial products
🏭 Production use in any form Yes Live systems serving real users
Specific Scenarios |
🎓 Student projects and coursework No Academic use is encouraged
🏗️ CI/CD pipelines (for commercial products) Yes Part of commercial development
📧 Email validation in production APIs Yes Production service usage
🛒 E-commerce checkout validation Yes Revenue-related validation
📱 Mobile apps (free with ads or paid) Yes Monetized applications

💡 Quick Decision Guide

Ask yourself these questions:

  1. Will real users interact with this in production? → You need a license
  2. Will this help generate revenue? → You need a license
  3. Is this for learning or testing only? → No license needed
  4. Is this an internal prototype or POC? → No license needed

🎯 Why Choose Our Commercial License?

Unlimited Usage - Use in all your production applications
🚀 Priority Support - Direct support from our engineering team
🔄 Regular Updates - Get the latest features and improvements
🛡️ Legal Protection - Full commercial rights and warranty
🏢 Enterprise Ready - Suitable for large-scale deployments

📄 Get Your Commercial License

Ready to use email-validator-js in production?

🛍️ Purchase a License - Simple pricing, instant activation
📧 Contact Sales - For enterprise or custom needs

changelog

Change Log

v2.10.2 - 2025-09-03

🔧 Maintenance & Improvements

Changed

  • Build System: Reverted from Rolldown back to Rollup for better stability and ecosystem compatibility
  • Type System: Improved TypeScript type inference throughout the codebase
    • Removed duplicate type definitions
    • Leveraged automatic type inference where possible
    • Reduced redundant type declarations for better maintainability
    • Maintained strict type safety while simplifying code

Fixed

  • Dependencies: Updated all non-major dependencies to latest versions (#529)
  • Build Configuration: Restored stable Rollup configuration for consistent builds

Technical Details

  • Removed redundant types.d.ts file (271 lines of duplicate definitions)
  • Improved type inference in batch processing, domain suggestion, and name detection modules
  • Simplified array and object type declarations using TypeScript's inference capabilities
  • All tests passing with enhanced type safety

v2.10.1 - 2025-08-29

🐛 Bug Fixes & Improvements

Fixed

  • Serverless Adapters: Added missing handler export for AWS Lambda and Vercel Edge Functions adapters
  • TypeScript: Fixed type casting issues in serverless adapter tests
  • Dependencies: Added @types/aws-lambda for proper TypeScript support

Added

  • Testing: Comprehensive test suites for AWS Lambda adapter (287 lines)
  • Testing: Comprehensive test suites for Vercel Edge Functions adapter (328 lines)
  • Testing: All serverless adapters now have full test coverage

Improved

  • Code Quality: Fixed all linting issues with proper type annotations
  • Test Coverage: 241 tests passing across 15 test suites
  • Developer Experience: Better TypeScript support for serverless environments

v2.10.0 - 2025-08-28

🚀 Serverless Platform Support

This release introduces comprehensive serverless platform support with dedicated adapters for AWS Lambda, Cloudflare Workers, Vercel Edge Functions, and Deno Deploy, enabling email validation at the edge with optimized performance.

Added

  • Serverless Core Module

    • Edge-optimized email validation without Node.js dependencies
    • Built-in EdgeCache for high-performance caching at the edge
    • Batch validation support with configurable concurrency
    • Lightweight bundle size (~15KB gzipped)
  • Platform Adapters

    • AWS Lambda: Full support for API Gateway v1/v2 and ALB triggers
    • Cloudflare Workers: Native Workers API with KV storage integration
    • Vercel Edge Functions: Edge runtime support with streaming responses
    • Deno Deploy: Native Deno server with TypeScript support
  • API Features

    • RESTful endpoints for single and batch validation
    • CORS support with configurable origins
    • Rate limiting and request validation
    • Comprehensive error handling and logging
    • Health check endpoints
  • Performance Optimizations

    • Edge caching with TTL configuration
    • Parallel batch processing
    • Minimal cold start times
    • Optimized bundle sizes per platform

Improved

  • Module System: New modular exports for tree-shaking
  • TypeScript Support: Enhanced types for serverless environments
  • Documentation: Comprehensive serverless deployment guides
  • Testing: Platform-specific test suites

Technical Details

  • Zero Node.js dependencies in serverless core
  • Platform-agnostic validation logic
  • Streaming response support for large batches
  • Environment-based configuration

v2.6.0 - 2025-08-26

🚀 Enhanced Name Detection Release

This release introduces significant improvements to the name detection functionality, providing more accurate and intelligent extraction of first and last names from complex email address patterns.

Added

  • Enhanced Composite Name Detection

    • Support for alphanumeric composite names (e.g., "mo1.test2@example.com")
    • Smart handling of mixed letter-number patterns
    • Preservation of alphanumeric identities when contextually appropriate
    • Confidence scoring adjusted for composite patterns (0.6 for full alphanumeric, 0.8 for mixed)
  • Intelligent Number Processing

    • Context-aware number handling in email addresses
    • Smart extraction of base names from trailing numbers ("john123" → "John")
    • Mixed case processing ("john2.doe" → "John", "Doe")
    • Alphanumeric pattern preservation for composite identities
  • Advanced Contextual Suffix Recognition

    • Extended suffix detection for modern email patterns
    • Recognition of development suffixes ("dev", "company", "team")
    • Year pattern detection and filtering (1900-2099)
    • Corporate and organizational suffix handling
  • Complex Multi-Part Name Parsing

    • Enhanced handling of 3+ part email structures
    • Intelligent first/last name extraction from complex patterns
    • Mixed separator support (dots, underscores, hyphens)
    • Smart suffix filtering in multi-component addresses
  • Refined Confidence Scoring System

    • Granular confidence levels (0.4-0.9) based on pattern complexity
    • Higher confidence for standard patterns (dot-separated: 0.9)
    • Appropriate confidence for alphanumeric patterns (0.6)
    • Context-aware scoring for extracted vs. preserved patterns

Improved

  • Name Detection Accuracy: Significantly improved detection rates for modern email patterns
  • Pattern Recognition: Better handling of development, gaming, and platform email formats
  • International Support: Enhanced parsing of hyphenated and compound names
  • Edge Case Handling: Robust processing of unusual email structures
  • Performance: Maintained linear time complexity with enhanced functionality

Technical Enhancements

  • Composite Name Parsing: New parseCompositeNamePart() function for alphanumeric analysis
  • Smart Capitalization: Enhanced capitalization that preserves alphanumeric formatting
  • Pattern Validation: Improved isLikelyName() with number-aware validation
  • Comprehensive Testing: 212 test cases covering various pattern types and edge cases

Use Cases

Backward Compatibility

  • All existing API signatures remain unchanged
  • Previous detection results maintain consistency
  • New capabilities are purely additive
  • No breaking changes to confidence thresholds

v2.4.1 - 2025-01-26

Improvements

  • Enhanced Domain Validation: WHOIS functions now use PSL (Public Suffix List) for consistent domain validation
  • Type Safety: Fixed TypeScript type assertions in WHOIS cache
  • Code Quality: Removed non-null assertions for safer code

Changed

  • WHOIS domain validation now uses psl.isValid() matching email domain validation
  • Invalid domains without valid TLDs now correctly return null

v2.4.0 - 2025-01-26

🎉 WHOIS Domain Information Release

This release adds WHOIS lookup capabilities to retrieve domain age and registration status, providing deeper insights into email domain validity and reputation.

Added

  • Domain Age Detection via WHOIS

    • New getDomainAge() function retrieves domain creation date and age
    • Calculates age in days and years
    • Returns expiration and last updated dates
    • Supports extraction from email addresses and URLs
    • 1-hour caching for performance optimization
  • Domain Registration Status via WHOIS

    • New getDomainRegistrationStatus() function checks domain registration
    • Detects if domain is registered or available
    • Returns registrar information and name servers
    • Provides domain status codes (locked, pending deletion, etc.)
    • Calculates days until expiration
    • Identifies expired domains
  • WHOIS Infrastructure

    • Support for 50+ TLDs with specific WHOIS servers
    • Automatic WHOIS server discovery for unknown TLDs
    • Intelligent parsing of various WHOIS response formats
    • Robust error handling and timeout support
    • Built-in caching with 1-hour TTL
  • New Type Definitions

    • DomainAgeInfo interface for domain age results
    • DomainRegistrationInfo interface for registration status
    • WhoisData interface for raw WHOIS data

Performance

  • WHOIS results cached for 1 hour to reduce network calls
  • Timeout support (default 5 seconds) for unresponsive WHOIS servers
  • Graceful degradation when WHOIS servers are unavailable

Testing

  • Added comprehensive test suite for WHOIS functions
  • 19 tests covering various scenarios and edge cases
  • Integration tests with real WHOIS servers

v2.3.0 - 2025-01-26

🎉 Name Detection & Domain Suggestion Release

This release introduces intelligent name detection from email addresses and domain typo detection with suggestions, enhancing the email validation capabilities.

Added

  • Name Detection from Email Addresses

    • New detectName() function extracts first and last names from email addresses
    • Supports common separators: dot (.), underscore (_), hyphen (-)
    • Handles camelCase patterns (e.g., johnDoe@example.com)
    • Removes email aliases (text after +) before detection
    • Confidence scoring based on pattern reliability
    • Custom detection method support via nameDetectionMethod parameter
    • Integrated into verifyEmail() and verifyEmailDetailed() with detectName parameter
  • Domain Typo Detection and Suggestions

    • New suggestEmailDomain() function detects and corrects domain typos
    • Supports 70+ common email domains (Gmail, Yahoo, Outlook, etc.)
    • Uses string similarity algorithm from string-similarity-js package
    • Smart similarity thresholds based on domain length
    • Known typo patterns detected with 95% confidence
    • Custom domain list support via commonDomains parameter
    • Cached suggestions for 24-hour performance optimization
    • Enabled by default in verifyEmailDetailed()
  • New Utility Functions

    • isCommonDomain() - Check if domain is in common list
    • getDomainSimilarity() - Calculate similarity between two domains
    • COMMON_EMAIL_DOMAINS - Exported constant with 70+ common domains
  • Enhanced Type Definitions

    • DetectedName interface for name detection results
    • DomainSuggestion interface for domain suggestions
    • NameDetectionMethod type for custom detection functions
    • DomainSuggestionMethod type for custom suggestion functions

Changed

  • Updated verifyEmail(), verifyEmailDetailed(), and verifyEmailBatch() to support name detection and domain suggestions
  • Enhanced caching system to include domain suggestions (24-hour TTL)
  • Added string-similarity-js as a dependency for similarity calculations

Performance

  • Domain suggestions cached for 24 hours to avoid recalculating similarity scores
  • Name detection is lightweight with minimal performance impact
  • All features are optional and don't affect performance when disabled

v2.2.1 - 2025-01-26

Changed

  • Move @types/psl from dependencies to devDependencies for cleaner production installs
  • Update typescript-eslint to v8.41.0
  • Update eslint to v9.34.0
  • Update README documentation

Fixed

  • Reduced production dependencies footprint by correctly categorizing development-only packages

v2.1.0 - 2024-01-19

🎉 Major Improvements Release

This release brings significant performance improvements, new features, and better developer experience while maintaining full backward compatibility.

Added

  • Batch Email Verification - New verifyEmailBatch() function for parallel processing of multiple emails with concurrency control
  • Detailed Verification Results - New verifyEmailDetailed() function returns comprehensive results with error codes
  • Advanced Caching System - Integrated tiny-lru for intelligent caching with configurable TTL:
    • MX Records: 1 hour TTL
    • Disposable checks: 24 hours TTL
    • Free provider checks: 24 hours TTL
    • Domain validation: 24 hours TTL
    • SMTP results: 30 minutes TTL
  • Error Code System - New VerificationErrorCode enum for precise error identification
  • Retry Mechanism - Automatic retry for transient failures with exponential backoff
  • Multiple MX Fallback - Automatically tries up to 3 MX servers if the first fails
  • Cache Management - New clearAllCaches() utility function
  • TypeScript Enhancements - Strict mode enabled with comprehensive type definitions
  • RFC 5321 Compliance - Enhanced email validation with proper length checks (64 char local, 253 char domain)
  • New Test Coverage - Added comprehensive tests for batch processing, caching, and detailed verification

Changed

  • Socket Cleanup - Fixed memory leaks with proper socket cleanup and event listener removal
  • Performance - ~90% reduction in DNS lookups through caching
  • Email Validation - Enhanced pattern detection (consecutive dots, leading/trailing dots)
  • Dependencies - Added tiny-lru for efficient LRU caching
  • TypeScript Configuration - Enabled strict mode for better type safety
  • Jest Configuration - Updated to use new transform syntax (removed deprecated globals)

Fixed

  • Memory leak in socket connections preventing proper cleanup
  • Socket cleanup issues causing "Cannot log after tests are done" errors
  • Caching for negative results (now caches both positive and negative results)
  • TypeScript strict null check issues throughout the codebase
  • Test isolation issues with shared cache between tests

Performance Improvements

  • Caching reduces repeated DNS lookups by ~90%
  • Batch processing enables parallel verification of multiple emails
  • Smart MX record fallback reduces false negatives
  • Connection reuse through SMTP result caching
  • Optimized memory usage with proper cleanup

Developer Experience

  • Comprehensive JSDoc documentation for all public APIs
  • New examples directory with advanced usage patterns
  • Migration guide for upgrading from v2.0.0
  • Improved error messages with specific error codes
  • Better TypeScript support with exported types
  • All tests passing with 100% reliability

Documentation

  • Complete API reference in README
  • Performance optimization guide
  • Migration guide (MIGRATION.md)
  • Advanced usage examples
  • Commercial licensing information at https://dev.me/license/email-validator

Migration Notes

This release is fully backward compatible. All existing code will continue to work without changes. New features are opt-in through new functions. See MIGRATION.md for details.

v2.0.1

  • Update release script

v2.0.0

  • Update license from MIT to BSL-1.1
  • Improve performance use es6 set to speed up domain lookups thanks to @ArsenyYankovsky #221
  • Update dependencies
  • Update lists

v1.0.19

  • allow passing smtpPort to verifyEmail function

v1.0.18

  • Fix npm release folder

v1.0.17

  • Update dependencies
  • Update disposable email domains
  • Update free email domains

v1.0.14

  • add socket.on('timeout') event
  • add socket.on('close') event
  • enhance email regex validation

v1.0.13

  • minor refactoring
  • adding more tests and real dns tests
  • change free email domains to json file
  • change disposable email domains to json file

v1.0.12

  • change default value verifyMx to false
  • fix validMx value check when verifySmtp is true

v1.0.11

  • remove yahoo exclusion in smtp

v1.0.10

  • change response validEmailFormat to validFormat

v1.0.9

  • change response wellFormed to validEmailFormat
  • change response validDomain to validMx
  • change response validMailbox to validSmtp

v1.0.8

  • change params verifyDomain to verifyMx
  • change params verifyMailbox to verifySmtp

v1.0.7

  • Add PSL to support ( isValidEmailDomain )
  • Refactor tests

v1.0.0

  • Initial release