New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

mailsafepro-sdk

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mailsafepro-sdk

Official Node.js/TypeScript SDK for MailSafePro Email Validation API - Professional email verification with batch processing, rate limiting, and comprehensive error handling

latest
Source
npmnpm
Version
1.2.3
Version published
Maintainers
1
Created
Source

MailSafePro JavaScript/TypeScript SDK

MailSafePro Logo

Professional Email Validation API for Node.js and Browser

npm version TypeScript Node.js License: MIT Tests Coverage: 85% npm downloads

DocumentationAPI ReferenceExamplesChangelog

🚀 Features

  • Full TypeScript Support - Complete type definitions and IntelliSense
  • 🔐 Dual Authentication - API Key and JWT (OAuth2) support
  • 🚦 Smart Rate Limiting - Client-side rate limiting prevents 429 errors
  • 🔄 Auto Retry Logic - Exponential backoff for transient failures
  • 📦 Batch Processing - Validate thousands of emails efficiently
  • 🛡️ Type-Safe Errors - Comprehensive error handling with typed exceptions
  • 📊 Progress Tracking - Real-time progress for batch operations
  • 🔌 Zero Config - Works out of the box with sensible defaults
  • 🌐 Universal - Runs in Node.js and modern browsers
  • 📝 Extensive Logging - Built-in debugging and monitoring
  • High Performance - Optimized for speed and reliability
  • 🎯 Production Ready - Battle-tested with 85%+ test coverage and 249 tests

📦 Installation

npm install mailsafepro-sdk

or

yarn add mailsafepro-sdk

or

pnpm add mailsafepro-sdk

Requirements:

  • Node.js >= 16.0.0
  • TypeScript >= 4.5 (for TypeScript users)

🏁 Quick Start

import { MailSafeProClient } from 'mailsafepro-sdk';

const client = new MailSafeProClient({
apiKey: 'your_api_key_here',
});

// Validate a single email
const result = await client.validateEmail({
email: 'user@example.com',
checkSmtp: true,
});

console.log(result.valid); // true/false
console.log(result.riskScore); // 0-100
console.log(result.provider); // 'gmail', 'outlook', etc.

JWT Authentication

const client = new MailSafeProClient({
baseURL: 'https://api.mailsafepro.com/v1',
});

// Login to get JWT tokens
await client.login('your-email@example.com', 'your-password');

// Now you can make authenticated requests
const result = await client.validateEmail({
email: 'test@example.com',
});

// Logout when done
await client.logout();

🎬 Real-World Examples

Signup Form Validation

async function validateSignupEmail(email: string) {
try {
const result = await client.validateEmail({
email,
checkSmtp: true
});
if (!result.valid) {
  return { valid: false, message: 'Invalid email address' };
}

if (result.riskScore > 70) {
  return { valid: false, message: 'High-risk email detected' };
}

if (result.disposable) {
  return { valid: false, message: 'Disposable emails not allowed' };
}

return { valid: true };
} catch (error) {
console.error('Validation error:', error);
return { valid: false, message: 'Validation service unavailable' };
}
}

Newsletter Cleanup

async function cleanEmailList(emails: string[]) {
const results = await client.batchValidateEmails({
emails,
checkSmtp: true,
});

// Filter valid, low-risk emails
const cleanList = results.results
.filter(r => r.valid && r.riskScore < 50 && !r.disposable)
.map(r => r.email);

console.log(✅ Clean emails: ${cleanList.length}/${emails.length});
return cleanList;
}

E-commerce Order Verification

async function verifyOrderEmail(email: string) {
const result = await client.validateEmail({
email,
checkSmtp: true,
includeRawDns: true
});

// Accept only corporate/personal emails
if (result.disposable || result.roleAccount) {
throw new Error('Please use a personal email address');
}

// Require mailbox verification
if (!result.mailboxExists) {
throw new Error('Email address does not exist');
}

return result;
}

📖 Table of Contents

⚙️ Configuration

Client Options

const client = new MailSafeProClient({
// Required (one of these)
apiKey: 'your_api_key', // API Key authentication

// Optional
baseURL: 'https://api.mailsafepro.com/v1', // API base URL
timeout: 30000, // Request timeout (ms)
maxRetries: 3, // Max retry attempts
enableRetry: true, // Enable automatic retries
autoRefresh: true, // Auto-refresh JWT tokens

// Rate limiting
rateLimitConfig: {
maxRequestsPerSecond: 10, // Max requests per second
maxConcurrent: 5, // Max concurrent requests
},

// Logging
logger: {
level: 'INFO', // DEBUG, INFO, WARN, ERROR, NONE
prefix: '[MailSafePro]',
timestamp: true,
colors: true,
},
});

💡 Usage Examples

Single Email Validation

// Basic validation
const result = await client.validateEmail({
email: 'user@example.com',
});
// With SMTP check
const result = await client.validateEmail({
email: 'user@example.com',
checkSmtp: true, // Verify mailbox exists
includeRawDns: true, // Include DNS records
});
// Check result
if (result.valid && result.riskScore < 50) {
console.log('✅ Email is valid and safe');
console.log(Provider: ${result.provider});
console.log(Reputation: ${result.reputation}/100);
}

Batch Validation

const emails = [
'user1@example.com',
'user2@example.com',
'user3@example.com',
// ... up to 1000 emails
];

const results = await client.batchValidateEmails({
emails,
checkSmtp: true,
});

console.log(✅ Valid: ${results.validCount});
console.log(❌ Invalid: ${results.invalidCount});
console.log(⏱️ Processing time: ${results.processingTime}ms);

// Filter valid emails
const validEmails = results.results
.filter(r => r.valid && r.riskScore < 50)
.map(r => r.email);

File Upload Batch

import fs from 'fs';

// Upload CSV file
const fileBuffer = fs.readFileSync('emails.csv');

const job = await client.uploadFileBatch(fileBuffer, {
filename: 'emails.csv',
contentType: 'text/csv',
checkSmtp: true,
});

console.log(Job ID: ${job.jobId});
console.log(Status: ${job.status});

// Wait for completion with progress
const results = await client.waitForBatchCompletion(job.jobId, {
pollInterval: 2000,
onProgress: (status) => {
console.log(Progress: ${status.progress}%);
},
});

console.log('Batch completed!');
console.log(Valid: ${results.validCount});
console.log(Invalid: ${results.invalidCount});

Progress Tracking

// Validate with progress callback
const results = await client.validateEmailsWithRetry(emails, {
checkSmtp: true,
maxRetries: 3,
onProgress: (completed, total) => {
const percentage = (completed / total * 100).toFixed(1);
console.log(Progress: ${percentage}% (${completed}/${total}));
},
});

🚨 Error Handling

The SDK provides typed error classes for precise error handling:

import {
RateLimitError,
AuthenticationError,
ValidationError,
QuotaExceededError,
NetworkError,
TimeoutError,
} from 'mailsafepro-sdk';

try {
await client.validateEmail({ email: 'test@example.com' });
} catch (error) {
if (error instanceof RateLimitError) {
console.error(Rate limited. Retry after: ${error.retryAfter}s);
console.log(Limit: ${error.limit}, Remaining: ${error.remaining});
console.log(Resets at: ${error.reset});
}
else if (error instanceof AuthenticationError) {
console.error('Authentication failed. Check your API key.');
}
else if (error instanceof ValidationError) {
console.error('Invalid input:', error.details);
}
else if (error instanceof QuotaExceededError) {
console.error(Quota exceeded: ${error.used}/${error.limit});
}
else if (error instanceof TimeoutError) {
console.error('Request timed out. Try again.');
}
else if (error instanceof NetworkError) {
console.error('Network error. Check your connection.');
}
}

Error Properties

All errors extend MailSafeProError and include:

error.message // Human-readable message
error.code // Machine-readable code
error.statusCode // HTTP status code (if applicable)
error.details // Additional error details
error.timestamp // ISO timestamp

🚦 Rate Limiting

Client-Side Rate Limiting

Prevent 429 errors with built-in rate limiting:

const client = new MailSafeProClient({
apiKey: 'your_api_key',
rateLimitConfig: {
maxRequestsPerSecond: 10, // 10 req/s
maxConcurrent: 5, // Max 5 concurrent
},
});

// SDK automatically queues and throttles requests
const promises = emails.map(email =>
client.validateEmail({ email })
);

// All requests respect rate limits
await Promise.all(promises);

// Check queue stats
const stats = client.getRateLimiterStats();
console.log(Queue size: ${stats.queueSize});
console.log(Pending: ${stats.pendingCount});

Handle Server Rate Limits

try {
await client.validateEmail({ email: 'test@example.com' });
} catch (error) {
if (error instanceof RateLimitError) {
// Wait and retry
await new Promise(resolve =>
setTimeout(resolve, error.retryAfter * 1000)
);

// Retry the request
const result = await client.validateEmail({ 
  email: 'test@example.com' 
});
}
}

🔥 Advanced Features

Automatic Token Refresh

JWT tokens are automatically refreshed before expiration:

await client.login('email@example.com', 'password');

// Token automatically refreshes 1 minute before expiration
// No manual refresh needed!

// Check session status
const session = client.getSession();
console.log(Expires at: ${session.expiresAt});
console.log(Is valid: ${client.isAuthenticated()});

// Manual refresh if needed
await client.refreshToken();

Custom Retry Configuration

import { RetryPolicy } from 'mailsafepro-sdk';

const retryPolicy = new RetryPolicy()
.withMaxRetries(5)
.withInitialDelay(1000)
.withMaxDelay(60000)
.withBackoffMultiplier(2)
.onRetry((attempt, error, delay) => {
console.log(Retry ${attempt} after ${delay}ms);
});

await retryPolicy.execute(async () => {
return client.validateEmail({ email: 'test@example.com' });
});

Custom Logger

import { ConsoleLogger } from 'mailsafepro-sdk';

// Built-in logger with options
const logger = new ConsoleLogger({
level: 'DEBUG',
prefix: '[MyApp]',
timestamp: true,
colors: true,
});

const client = new MailSafeProClient({
apiKey: 'your_api_key',
logger: logger,
});

// Or implement custom logger
class CustomLogger {
debug(message: string, ...args: any[]) { /* custom logic / }
info(message: string, ...args: any[]) { / custom logic / }
warn(message: string, ...args: any[]) { / custom logic / }
error(message: string, ...args: any[]) { / custom logic */ }
}

const client2 = new MailSafeProClient({
apiKey: 'your_api_key',
logger: new CustomLogger(),
});

Input Validation

import { validateEmail, validateEmails } from 'mailsafepro-sdk';

// Validate before sending
try {
validateEmail('user@example.com');
// Email is valid, proceed
} catch (error) {
console.error('Invalid email format');
}

// Batch validation
try {
validateEmails(['email1@example.com', 'email2@example.com']);
} catch (error) {
console.error('Invalid email in batch');
}

⚡ Performance

Benchmarks

  • Single validation: ~100-300ms
  • Batch validation (100 emails): ~2-5 seconds
  • Rate limiting: 10 req/s (configurable)
  • Memory usage: ~50MB base + 1MB per 1000 emails

Optimization Tips

// ✅ Good - Batch validation
const results = await client.batchValidateEmails({
emails: ['email1@test.com', 'email2@test.com'],
});

// ❌ Bad - Sequential validation
for (const email of emails) {
await client.validateEmail({ email }); // Slow!
}

// ✅ Good - Parallel with rate limiting
const client = new MailSafeProClient({
rateLimitConfig: { maxConcurrent: 5 }
});
await Promise.all(emails.map(email =>
client.validateEmail({ email })
));

📚 API Reference

MailSafeProClient

Constructor

new MailSafeProClient(options: MailSafeProClientOptions)

Authentication Methods

  • login(email, password): Promise<UserSession>
  • register(email, password, name?): Promise<UserSession>
  • logout(): Promise<void>
  • refreshToken(): Promise<UserSession>
  • getSession(): UserSession | null
  • isAuthenticated(): boolean
  • setApiKey(apiKey): void
  • clearApiKey(): void

Validation Methods

  • validateEmail(request): Promise<EmailValidationResponse>
  • batchValidateEmails(request): Promise<BatchValidationResponse>
  • uploadFileBatch(file, options?): Promise<BatchJobStatus>
  • getBatchStatus(jobId): Promise<BatchJobStatus>
  • getBatchResults(jobId): Promise<BatchValidationResponse>
  • waitForBatchCompletion(jobId, options?): Promise<BatchValidationResponse>
  • cancelBatch(jobId): Promise<void>
  • validateEmailsWithRetry(emails, options?): Promise<EmailValidationResponse[]>

Utility Methods

  • getRateLimiterStats(): object | null
  • clearRateLimiter(): void
  • setAutoRefresh(enabled): void
  • getLogger(): Logger
  • destroy(): void

Types

Full TypeScript definitions are included. Import types:

import type {
EmailValidationRequest,
EmailValidationResponse,
BatchValidationRequest,
BatchValidationResponse,
UserSession,
MailSafeProClientOptions,
} from 'mailsafepro-sdk';

🎯 TypeScript

This SDK is written in TypeScript and includes complete type definitions:

// Full IntelliSense support
const result: EmailValidationResponse = await client.validateEmail({
email: 'test@example.com',
checkSmtp: true,
});

// Type-safe error handling
if (result.valid) {
// result.valid is boolean
// result.riskScore is number
// result.provider is string | undefined
}

// Import types
import type {
EmailValidationRequest,
EmailValidationResponse,
BatchValidationResponse,
RateLimiterConfig,
Logger,
} from 'mailsafepro-sdk';

No additional @types packages required!

🧪 Testing

Run all tests

npm test

Watch mode

npm run test:watch

Coverage

npm run test:coverage

Unit tests only

npm run test:unit

Integration tests only

npm run test:integration

🗺️ Roadmap

  • TypeScript SDK with full type support
  • Batch validation with progress tracking
  • Rate limiting and retry logic
  • JWT authentication
  • Webhook support for async validation
  • React hooks library
  • Vue.js plugin
  • Real-time validation streaming
  • Email list deduplication
  • Advanced filtering and segmentation

Vote for features on GitHub Discussions!

🤝 Contributing

Contributions are welcome! Please read our Contributing Guide for details.

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

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🔧 Troubleshooting

Common Issues

"Authentication failed"

// Check your API key format
const apiKey = 'msp_live_xxxxxxxxxxxxxxxxxxxxx'; // Correct format
// msp_test_xxxxxxxxxxxxxxxxxxxxx for test mode

"Rate limit exceeded"

// Enable client-side rate limiting
const client = new MailSafeProClient({
apiKey: 'your_key',
rateLimitConfig: {
maxRequestsPerSecond: 10,
},
});

"Request timeout"

// Increase timeout for slow networks
const client = new MailSafeProClient({
apiKey: 'your_key',
timeout: 60000, // 60 seconds
});

"Module not found" in Browser // Use CDN for browser

<script src="https://unpkg.com/mailsafepro-sdk@latest/dist/browser.js"></script>
<script>
  const client = new MailSafePro.MailSafeProClient({
    apiKey: 'your_key'
  });
</script>

💬 Support

🌟 Show Your Support

If you find this SDK helpful, please give it a ⭐️ on GitHub!

📊 Stats

npm bundle size npm GitHub issues GitHub pull requests

Made with ❤️ by the MailSafePro Team

Keywords

email

FAQs

Package last updated on 16 Feb 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts