
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
mailsafepro-sdk
Advanced tools
Official Node.js/TypeScript SDK for MailSafePro Email Validation API - Professional email verification with batch processing, rate limiting, and comprehensive error handling
Professional Email Validation API for Node.js and Browser
npm install mailsafepro-sdk
or
yarn add mailsafepro-sdk
or
pnpm add mailsafepro-sdk
Requirements:
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.
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();
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' };
}
}
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;
}
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;
}
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,
},
});
// 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);
}
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);
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});
// 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}));
},
});
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.');
}
}
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
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});
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'
});
}
}
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();
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' });
});
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(),
});
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');
}
// ✅ 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 })
));
new MailSafeProClient(options: MailSafeProClientOptions)
login(email, password): Promise<UserSession>register(email, password, name?): Promise<UserSession>logout(): Promise<void>refreshToken(): Promise<UserSession>getSession(): UserSession | nullisAuthenticated(): booleansetApiKey(apiKey): voidclearApiKey(): voidvalidateEmail(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[]>getRateLimiterStats(): object | nullclearRateLimiter(): voidsetAutoRefresh(enabled): voidgetLogger(): Loggerdestroy(): voidFull TypeScript definitions are included. Import types:
import type {
EmailValidationRequest,
EmailValidationResponse,
BatchValidationRequest,
BatchValidationResponse,
UserSession,
MailSafeProClientOptions,
} from 'mailsafepro-sdk';
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!
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
Vote for features on GitHub Discussions!
Contributions are welcome! Please read our Contributing Guide for details.
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
"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>
If you find this SDK helpful, please give it a ⭐️ on GitHub!
FAQs
Official Node.js/TypeScript SDK for MailSafePro Email Validation API - Professional email verification with batch processing, rate limiting, and comprehensive error handling
We found that mailsafepro-sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

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.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.