Transform your email operations with our enterprise-grade solution that combines intelligent automation, smart analytics, and bulletproof reliability. Whether you're sending 10 emails or 10,000, we've got you covered!
- π§ Smart Retry Logic - Never lose an email again with intelligent exponential backoff
- β‘ Adaptive Rate Limiting - Automatically adjusts to your email provider's limits
- π Real-time Analytics - Track success rates, performance metrics, and delivery insights
- π¨ Template Engine - Create personalized emails with dynamic content
- π‘οΈ Enterprise Security - Built with production-grade error handling and validation
- π Scalable Architecture - Handles everything from startups to enterprise workloads
npm install @prathammahajan/multi-email-senderimport { EmailSender } from '@prathammahajan/multi-email-sender';
// π― Initialize with your email provider
const sender = new EmailSender({
email: {
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-app-password' // Use app password for Gmail
}
}
});
// π§ Send to multiple recipients instantly
const results = await sender.sendToMultiple(
['user1@example.com', 'user2@example.com'],
{
subject: 'π Welcome to Our Platform!',
html: '<h1>Hello there!</h1><p>Thanks for joining us!</p>'
}
);
console.log(`β
Sent ${results.filter(r => r.success).length} emails successfully!`);That's it! Your emails are sent with automatic retry logic, rate limiting, and comprehensive logging. π
// Automatically retries failed emails with exponential backoff
const sender = new EmailSender({
options: {
maxRetries: 5, // Try up to 5 times
retryDelay: 1000, // Start with 1 second delay
enableLogging: true // Track every attempt
}
});// Automatically adjusts to your provider's limits
const sender = new EmailSender({
rateLimit: {
enabled: true,
maxEmailsPerMinute: 10, // Gmail-friendly
maxEmailsPerHour: 100 // Respectful limits
}
});// Create personalized emails with ease
const recipients = [
{ email: 'john@example.com', name: 'John', company: 'Tech Corp' },
{ email: 'jane@example.com', name: 'Jane', company: 'Design Studio' }
];
const emailContent = {
subject: 'Hello {{name}} from {{company}}!',
html: `
<h1>Welcome {{name}}!</h1>
<p>We're excited to have you from <strong>{{company}}</strong> join our community.</p>
<p>Best regards,<br>The Team</p>
`,
template: {
name: 'welcome',
variables: { name: '{{name}}', company: '{{company}}' }
}
};
await sender.sendToMultiple(recipients, emailContent);// Get comprehensive insights
const stats = sender.getStatistics();
console.log(`
π Email Analytics:
β
Success Rate: ${((stats.totalSent / (stats.totalSent + stats.totalFailed)) * 100).toFixed(1)}%
π§ Total Sent: ${stats.totalSent}
β±οΈ Avg Duration: ${Math.round(stats.averageDuration)}ms
π Total Attempts: ${stats.totalAttempts}
`);π΅ Gmail Configuration (Click to expand)
const gmailSender = new EmailSender({
email: {
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-app-password' // Generate in Google Account settings
}
},
options: {
dailyLimit: 100, // Gmail's recommended limit
delayBetweenEmails: 2000, // 2 seconds between emails
maxRetries: 3
},
rateLimit: {
maxEmailsPerMinute: 10,
maxEmailsPerHour: 100
}
});π‘ Pro Tip: Enable 2-factor authentication and use app passwords for better security!
π Outlook Configuration (Click to expand)
const outlookSender = new EmailSender({
email: {
service: 'hotmail',
auth: {
user: 'your-email@outlook.com',
pass: 'your-password'
}
},
options: {
dailyLimit: 300, // Outlook allows more
delayBetweenEmails: 1000, // Faster sending
maxRetries: 3
},
rateLimit: {
maxEmailsPerMinute: 20,
maxEmailsPerHour: 200
}
});π’ Custom SMTP Configuration (Click to expand)
const customSender = new EmailSender({
email: {
service: 'custom',
auth: {
user: 'your-email@yourdomain.com',
pass: 'your-smtp-password'
},
host: 'smtp.yourdomain.com',
port: 587,
secure: false
},
options: {
dailyLimit: 500, // Check with your provider
delayBetweenEmails: 500, // Custom providers often allow faster sending
maxRetries: 5
},
rateLimit: {
maxEmailsPerMinute: 30,
maxEmailsPerHour: 500
}
});// Send personalized order confirmations
const orderEmails = orders.map(order => ({
email: order.customerEmail,
name: order.customerName,
orderId: order.id,
total: order.total,
items: order.items
}));
const emailContent = {
subject: 'π Order Confirmation #{{orderId}}',
html: `
<h1>Thank you {{name}}!</h1>
<p>Your order #{{orderId}} has been confirmed.</p>
<p><strong>Total: ${{total}}</strong></p>
<p>We'll send you tracking information soon!</p>
`,
template: {
name: 'order-confirmation',
variables: { name: '{{name}}', orderId: '{{orderId}}', total: '{{total}}' }
}
};
await sender.sendToMultiple(orderEmails, emailContent);// Send newsletters with attachments
const newsletterContent = {
subject: 'π° Weekly Newsletter - {{date}}',
html: newsletterHTML,
attachments: [
{ filename: 'newsletter.pdf', path: './newsletters/weekly.pdf' }
],
template: {
name: 'newsletter',
variables: { date: new Date().toLocaleDateString() }
}
};
// Process in batches for large lists
const batchSize = 50;
for (let i = 0; i < subscribers.length; i += batchSize) {
const batch = subscribers.slice(i, i + batchSize);
await sender.sendToMultiple(batch, newsletterContent);
// Add delay between batches
await new Promise(resolve => setTimeout(resolve, 5000));
}// Send system notifications
const notifications = [
{ email: 'admin@company.com', type: 'system', message: 'Server backup completed' },
{ email: 'user@example.com', type: 'account', message: 'Password changed successfully' }
];
for (const notification of notifications) {
const emailContent = {
subject: `π ${notification.type.charAt(0).toUpperCase() + notification.type.slice(1)} Notification`,
text: notification.message,
priority: 'high'
};
await sender.sendSingle(notification.email, emailContent);
}// Automatic error categorization and handling
const results = await sender.sendToMultiple(recipients, emailContent);
results.forEach(result => {
if (!result.success) {
switch (result.error) {
case 'authentication':
console.log('π Auth issue - check credentials');
break;
case 'rate_limit':
console.log('β±οΈ Rate limited - will retry automatically');
break;
case 'network':
console.log('π Network issue - retrying with backoff');
break;
default:
console.log('β Other error:', result.error);
}
}
});// Get detailed performance insights
const stats = sender.getStatistics();
const logs = sender.getLogs();
console.log(`
π Performance Report:
βββββββββββββββββββββββββββββββββββββββ
β π§ Emails Sent: ${stats.totalSent.toString().padEnd(20)} β
β β Failed: ${stats.totalFailed.toString().padEnd(23)} β
β β±οΈ Avg Time: ${Math.round(stats.averageDuration).toString().padEnd(18)}ms β
β π Total Attempts: ${stats.totalAttempts.toString().padEnd(15)} β
βββββββββββββββββββββββββββββββββββββββ
π Success Rate: ${((stats.totalSent / (stats.totalSent + stats.totalFailed)) * 100).toFixed(1)}%
π― Error Breakdown:`, stats.errorBreakdown);// Process large lists with progress tracking
const processLargeList = async (recipients, emailContent) => {
const batchSize = 100;
const totalBatches = Math.ceil(recipients.length / batchSize);
for (let i = 0; i < recipients.length; i += batchSize) {
const batchNumber = Math.floor(i / batchSize) + 1;
const batch = recipients.slice(i, i + batchSize);
console.log(`π¦ Processing batch ${batchNumber}/${totalBatches} (${batch.length} recipients)...`);
const results = await sender.sendToMultiple(batch, emailContent);
const successful = results.filter(r => r.success).length;
console.log(`β
Batch ${batchNumber} completed: ${successful}/${batch.length} successful`);
// Show progress bar
const progress = Math.round((batchNumber / totalBatches) * 100);
console.log(`π Progress: [${'β'.repeat(progress/5)}${'β'.repeat(20-progress/5)}] ${progress}%`);
// Rate limiting delay
if (batchNumber < totalBatches) {
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
};# .env file
EMAIL_SERVICE=gmail
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-app-password
EMAIL_DAILY_LIMIT=100
EMAIL_DELAY=2000
EMAIL_MAX_RETRIES=3
EMAIL_RATE_LIMIT_ENABLED=true
EMAIL_MAX_PER_MINUTE=10
EMAIL_MAX_PER_HOUR=100// Use environment variables
import { createConfigFromEnv } from '@prathammahajan/multi-email-sender';
const config = createConfigFromEnv();
const sender = new EmailSender(config);π Security Best Practices
- β Use App Passwords for Gmail/Yahoo (never regular passwords)
- β Enable 2FA on your email accounts
- β Store credentials in environment variables
- β Use dedicated email accounts for sending
- β Monitor your sending reputation regularly
β‘ Performance Optimization
- π Batch processing for large lists (50-100 emails per batch)
- π Use appropriate delays based on your provider
- π Monitor rate limits and adjust accordingly
- π Enable logging for debugging and optimization
- π Use templates for consistent formatting
π Monitoring & Analytics
- π Track success rates and identify patterns
- π Monitor error types to improve reliability
- π Set up alerts for high failure rates
- π Regular log analysis for optimization
- π A/B test different sending strategies
π Authentication Errors
Problem: Authentication failed or Invalid credentials
Solutions:
- β Verify email and password are correct
- β For Gmail: Use app passwords instead of regular passwords
- β Enable 2-factor authentication
- β Check if account is locked or suspended
- β Verify SMTP settings for custom providers
// Test your configuration
const isValid = sender.validateConfiguration();
console.log('Configuration valid:', isValid);β±οΈ Rate Limiting Issues
Problem: Emails being delayed or blocked
Solutions:
- β
Reduce
maxEmailsPerMinutesetting - β
Increase
delayBetweenEmails - β Use multiple email accounts for rotation
- β Check your provider's specific limits
- β Monitor rate limit statistics
// Check current rate limit status
const status = sender.rateLimiter.getStatus();
console.log('Rate limit status:', status);π Network & Connection Issues
Problem: Timeouts or connection failures
Solutions:
- β
Increase
timeoutsetting - β Check internet connection stability
- β Verify SMTP server settings
- β Try different ports (587 vs 465)
- β Check firewall settings
// Increase timeout for slow networks
const sender = new EmailSender({
email: { /* config */ },
options: {
timeout: 60000, // 60 seconds
maxRetries: 5
}
});| Class | Description | Key Methods |
|---|---|---|
EmailSender |
Main email sending class | sendToMultiple(), sendSingle(), getStatistics() |
Logger |
Comprehensive logging system | info(), error(), getLogs(), getStatistics() |
RetryLogic |
Intelligent retry mechanism | executeWithRetry(), getRetryStatistics() |
RateLimiter |
Smart rate limiting | waitIfNeeded(), getStatus(), updateConfig() |
EmailSender Options
{
email: {
service: 'gmail', // 'gmail', 'outlook', 'yahoo', 'custom'
auth: {
user: 'email@domain.com',
pass: 'password'
},
host: 'smtp.domain.com', // For custom SMTP
port: 587, // For custom SMTP
secure: false // For custom SMTP
},
options: {
dailyLimit: 100, // Max emails per day
delayBetweenEmails: 2000, // Delay in milliseconds
maxRetries: 3, // Max retry attempts
retryDelay: 1000, // Base retry delay
timeout: 30000, // Send timeout
enableLogging: true, // Enable detailed logging
logFile: 'email-logs.json' // Log file path
},
rateLimit: {
enabled: true, // Enable rate limiting
maxEmailsPerMinute: 10, // Max emails per minute
maxEmailsPerHour: 100 // Max emails per hour
}
}We love contributions! Here's how you can help:
- π Report bugs - Found an issue? Let us know!
- π‘ Suggest features - Have ideas? We'd love to hear them!
- π§ Submit PRs - Fix bugs or add features
- π Improve docs - Help others learn
- β Star the repo - Show your support!
- π Issues: GitHub Issues
- π¬ Discussions: GitHub Discussions
- π Documentation: GitHub Wiki
- β Buy me a coffee: Support the project
This project is licensed under the MIT License - see the LICENSE file for details.
Made with β€οΈ by Pratham Mahajan
| π E-commerce | π§ Marketing | π Notifications | π Analytics |
|---|---|---|---|
| Order confirmations | Newsletter campaigns | System alerts | Performance tracking |
| Shipping updates | Promotional emails | User notifications | Delivery insights |
| Customer support | Welcome sequences | Password resets | Error monitoring |