npm package: @gmana/email-checker
Description: Email checker
Author: Sun Sreng
Latest version: 0.0.11

# @gmana/email-checker

A powerful and lightweight TypeScript library to detect disposable email addresses with advanced validation features and comprehensive domain coverage.

[![npm version](https://badge.fury.io/js/@gmana%2Femail-checker.svg)](https://badge.fury.io/js/@gmana%2Femail-checker)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## ✨ Features

- 🚀 **Comprehensive Detection**: 286+ disposable email domains (constantly updated)
- 🔧 **Highly Configurable**: Custom whitelists, validation modes, and extensible options
- 📊 **Detailed Validation**: Rich validation results with metadata and error reporting
- ⚡ **Performance Optimized**: O(1) lookups with intelligent caching system
- 🌍 **International Support**: Handles international domains and subdomains
- 💪 **TypeScript First**: Full type safety with comprehensive type definitions
- 🪶 **Zero Dependencies**: Lightweight with no external runtime dependencies
- 📦 **Universal**: Works in Node.js, browsers, and supports both ESM & CJS

## 📦 Installation

```bash
npm install @gmana/email-checker
```

```bash
yarn add @gmana/email-checker
```

```bash
pnpm add @gmana/email-checker
```

```bash
bun add @gmana/email-checker
```

## 🚀 Quick Start

### Basic Usage

```typescript
import { isDisposableEmail } from "@gmana/email-checker"

// Simple boolean check
console.log(isDisposableEmail("user@10minutemail.com")) // true
console.log(isDisposableEmail("user@gmail.com")) // false
console.log(isDisposableEmail("user@tempmail.net")) // true
```

### Advanced Validation with Details

```typescript
import { validateEmail } from "@gmana/email-checker"

const result = validateEmail("user@tempmail.net")
console.log(result)
// {
//   isValid: true,
//   isDisposable: true,
//   domain: "tempmail.net",
//   errors: [],
//   metadata: {
//     isInternational: false,
//     hasSubdomains: false,
//     isWhitelisted: false
//   }
// }
```

## 🔧 Configuration

### Global Configuration

```typescript
import { configureEmailChecker, isDisposableEmail } from "@gmana/email-checker"

// Configure global settings
configureEmailChecker({
  strictMode: true, // Enable strict email validation
  whitelistedDomains: ["company.com"], // Always allow these domains
  customDisposableDomains: [
    // Add custom disposable domains
    "suspicious-temp.com",
    "fake-emails.net",
  ],
  allowInternational: true, // Allow international domains
  allowSubdomains: false, // Disallow subdomains
  enableCaching: true, // Enable performance caching
  maxCacheSize: 1000, // Cache size limit
})

// Now all validation uses these settings
console.log(isDisposableEmail("user@company.com")) // false (whitelisted)
```

### Per-Validation Options

```typescript
import { isDisposableEmail, validateEmail } from "@gmana/email-checker"

// Override global config for specific validations
const isDisposable = isDisposableEmail("user@sub.tempmail.com", {
  allowSubdomains: true,
  whitelistedDomains: ["tempmail.com"],
})

const result = validateEmail("user@münchen-temp.de", {
  allowInternational: true,
  strictMode: false,
})
```

## 📚 Complete API Reference

### Core Functions

#### `isDisposableEmail(email: string, options?: EmailValidationOptions): boolean`

Simple boolean check for disposable emails.

```typescript
isDisposableEmail("test@10minutemail.com") // true
isDisposableEmail("user@gmail.com") // false
isDisposableEmail("invalid-email") // false
```

#### `validateEmail(email: string, options?: EmailValidationOptions): EmailValidationResult`

Comprehensive validation with detailed results.

```typescript
const result = validateEmail("user@sub.tempmail.com")
// Returns detailed validation information
```

### Configuration Functions

#### `configureEmailChecker(config: Partial<EmailCheckerConfig>): void`

Set global configuration options.

#### `resetEmailCheckerConfig(): void`

Reset configuration to defaults.

#### `getEmailCheckerConfig(): EmailCheckerConfig`

Get current configuration settings.

### Domain Analysis Functions

#### `isDomainDisposable(domain: string): boolean`

Check if a specific domain is disposable.

```typescript
isDomainDisposable("tempmail.net") // true
isDomainDisposable("gmail.com") // false
```

#### `getDomainInfo(domain: string, options?: EmailValidationOptions): DomainInfo`

Get detailed information about a domain.

```typescript
const info = getDomainInfo("tempmail.net")
// { domain: "tempmail.net", isDisposable: true, isWhitelisted: false, isInternational: false }
```

#### `getDisposableDomains(): string[]`

Get the complete list of known disposable domains.

```typescript
const domains = getDisposableDomains()
console.log(`Total domains: ${domains.length}`) // Total domains: 286+
```

### Utility Functions

#### `extractDomain(email: string): string | null`

Extract domain from email address.

```typescript
extractDomain("user@example.com") // "example.com"
extractDomain("invalid-email") // null
```

#### `isValidEmailFormat(email: string, strictMode?: boolean): boolean`

Validate email format.

```typescript
isValidEmailFormat("user@example.com") // true
isValidEmailFormat("invalid-email") // false
```

### Cache Management

#### `clearCache(): void`

Clear the domain validation cache.

#### `getCacheStats(): { size: number; maxSize: number }`

Get cache statistics.

```typescript
const stats = getCacheStats()
console.log(`Cache: ${stats.size}/${stats.maxSize}`)
```

## 🎯 Advanced Usage Examples

### Form Validation with Zod

```typescript
import { z } from "zod"
import { isDisposableEmail } from "@gmana/email-checker"

const signUpSchema = z.object({
  email: z
    .string()
    .min(1, "Email is required")
    .email("Invalid email format")
    .refine((email) => !isDisposableEmail(email), {
      message: "Disposable emails are not allowed",
    }),
})

type SignUpData = z.infer<typeof signUpSchema>
```

### Express.js Middleware

```typescript
import express from "express"
import { validateEmail } from "@gmana/email-checker"

const app = express()

// Advanced email validation middleware
app.post("/signup", (req, res) => {
  const { email } = req.body
  const validation = validateEmail(email)

  if (!validation.isValid) {
    return res.status(400).json({
      error: "Invalid email",
      details: validation.errors,
    })
  }

  if (validation.isDisposable) {
    return res.status(400).json({
      error: "Disposable emails are not allowed",
      domain: validation.domain,
    })
  }

  // Continue with signup process
})
```

### React Hook Integration

```typescript
import { useState, useEffect } from "react"
import { validateEmail } from "@gmana/email-checker"

function useEmailValidation(email: string) {
  const [validation, setValidation] = useState(null)

  useEffect(() => {
    if (email) {
      const result = validateEmail(email)
      setValidation(result)
    }
  }, [email])

  return validation
}

// Usage in component
function SignUpForm() {
  const [email, setEmail] = useState("")
  const validation = useEmailValidation(email)

  return (
    <div>
      <input
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Enter email"
      />
      {validation?.isDisposable && (
        <p className="error">Disposable emails are not allowed</p>
      )}
    </div>
  )
}
```

### Bulk Email Processing

```typescript
import { isDisposableEmail, configureEmailChecker } from "@gmana/email-checker"

// Configure once for optimal performance
configureEmailChecker({
  enableCaching: true,
  maxCacheSize: 5000,
})

async function processBulkEmails(emails: string[]) {
  const results = emails.map((email) => ({
    email,
    isDisposable: isDisposableEmail(email),
    isValid: email.includes("@"),
  }))

  const stats = {
    total: emails.length,
    disposable: results.filter((r) => r.isDisposable).length,
    valid: results.filter((r) => r.isValid).length,
  }

  return { results, stats }
}
```

## 🎛️ TypeScript Types

```typescript
interface EmailValidationOptions {
  allowInternational?: boolean
  allowSubdomains?: boolean
  customDisposableDomains?: string[]
  whitelistedDomains?: string[]
  strictMode?: boolean
}

interface EmailValidationResult {
  isValid: boolean
  isDisposable: boolean
  domain: string | null
  errors: string[]
  metadata: {
    isInternational: boolean
    hasSubdomains: boolean
    isWhitelisted: boolean
  }
}

interface EmailCheckerConfig extends EmailValidationOptions {
  enableCaching?: boolean
  maxCacheSize?: number
}

interface DomainInfo {
  domain: string
  isDisposable: boolean
  isWhitelisted: boolean
  isInternational: boolean
}
```

## 🌍 International Domain Support

The library fully supports international domains and provides proper handling for:

```typescript
// International domains
validateEmail("user@münchen-mail.de") // Properly handled
validateEmail("test@временная-почта.рф") // International disposable domains

// Subdomain analysis
validateEmail("user@mail.tempmail.net") // Detects parent domain
validateEmail("test@sub.domain.company.com") // Flexible subdomain handling
```

## 🏎️ Performance Characteristics

- **O(1) Domain Lookups**: Using Set-based storage for instant domain checking
- **Intelligent Caching**: LRU cache with configurable size limits
- **Memory Efficient**: Minimal memory footprint with smart data structures
- **Bundle Size**: < 10KB minified, < 3KB gzipped

## 🔄 Migration Guide

### From v0.x to v1.x

The basic API remains unchanged, but new features are available:

```typescript
// v0.x - Still works
import { isDisposableEmail } from "@gmana/email-checker"
const isDisposable = isDisposableEmail("test@tempmail.com")

// v1.x - Enhanced with new features
import { validateEmail, configureEmailChecker } from "@gmana/email-checker"

// Configure once
configureEmailChecker({
  whitelistedDomains: ["yourcompany.com"],
  strictMode: true,
})

// Get detailed results
const result = validateEmail("test@tempmail.com")
```

## 🤝 Contributing

Contributions are welcome! Here's how you can help:

1. **Add New Disposable Domains**: Submit PRs with new disposable email providers
2. **Report Issues**: Found a legitimate domain being flagged? Let us know!
3. **Feature Requests**: Suggest new features or improvements
4. **Bug Fixes**: Help us squash bugs and improve reliability

## 📄 License

MIT © [Sun Sreng](https://github.com/sun-sreng)

## 🔗 Links

- **Homepage**: [https://github.com/sun-sreng/npm-gmana-email-checker](https://github.com/sun-sreng/npm-gmana-email-checker)
- **Issues**: [https://github.com/sun-sreng/npm-gmana-email-checker/issues](https://github.com/sun-sreng/npm-gmana-email-checker/issues)
- **Sponsor**: [https://github.com/sponsors/sun-sreng](https://github.com/sponsors/sun-sreng)

---

<p align="center">
Made with ❤️ for the developer community
</p>