mailsafepro-sdk
v1.2.3
Published
Official Node.js/TypeScript SDK for MailSafePro Email Validation API - Professional email verification with batch processing, rate limiting, and comprehensive error handling
Maintainers
Readme
MailSafePro JavaScript/TypeScript SDK
Professional Email Validation API for Node.js and Browser
Documentation • API Reference • Examples • Changelog
🚀 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-sdkor
yarn add mailsafepro-sdkor
pnpm add mailsafepro-sdkRequirements:
- Node.js >= 16.0.0
- TypeScript >= 4.5 (for TypeScript users)
🏁 Quick Start
API Key Authentication (Recommended)
import { MailSafeProClient } from 'mailsafepro-sdk';
const client = new MailSafeProClient({
apiKey: 'your_api_key_here',
});
// Validate a single email
const result = await client.validateEmail({
email: '[email protected]',
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('[email protected]', 'your-password');
// Now you can make authenticated requests
const result = await client.validateEmail({
email: '[email protected]',
});
// 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
- Installation
- Quick Start
- Configuration
- Usage Examples
- Error Handling
- Rate Limiting
- Advanced Features
- API Reference
- TypeScript
- Contributing
- Support
⚙️ 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: '[email protected]',
});// With SMTP check
const result = await client.validateEmail({
email: '[email protected]',
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 = [
'[email protected]',
'[email protected]',
'[email protected]',
// ... 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: '[email protected]' });
} 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: '[email protected]' });
} 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: '[email protected]'
});
}
}🔥 Advanced Features
Automatic Token Refresh
JWT tokens are automatically refreshed before expiration:
await client.login('[email protected]', '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: '[email protected]' });
});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('[email protected]');
// Email is valid, proceed
} catch (error) {
console.error('Invalid email format');
}
// Batch validation
try {
validateEmails(['[email protected]', '[email protected]']);
} 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: ['[email protected]', '[email protected]'],
});
// ❌ 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 | nullisAuthenticated(): booleansetApiKey(apiKey): voidclearApiKey(): 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 | nullclearRateLimiter(): voidsetAutoRefresh(enabled): voidgetLogger(): Loggerdestroy(): 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: '[email protected]',
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 testWatch mode
npm run test:watchCoverage
npm run test:coverageUnit tests only
npm run test:unitIntegration tests only
npm run test:integration🗺️ Roadmap
- [x] TypeScript SDK with full type support
- [x] Batch validation with progress tracking
- [x] Rate limiting and retry logic
- [x] 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
- 📧 Email: [email protected]
- 📖 Documentation: https://docs.mailsafepro.com
- 🐛 Issues: https://github.com/mailsafepro/sdk-js/issues
- 💬 Discussions: https://github.com/mailsafepro/sdk-js/discussions
🌟 Show Your Support
If you find this SDK helpful, please give it a ⭐️ on GitHub!
📊 Stats
