molana-mailer
v1.0.3
Published
A simple and efficient email sending package using nodemailer with TypeScript support, pre-built templates, and bulk email capabilities
Maintainers
Readme
Molana Mailer
A simple and efficient email sending package using nodemailer with TypeScript support, pre-built templates, and bulk email capabilities.
Features
- Simple & Easy to Use: Clean API with TypeScript support
- Multiple Email Providers: Support for Gmail, Outlook, and custom SMTP
- Pre-built Templates: Ready-to-use email templates for common scenarios
- Advanced Bulk Email Support: Send multiple emails with rate limiting and retry logic
- Advanced Template Engine: Support for loops, conditionals, and variable substitution
- Automatic Retry: Built-in retry mechanism for failed emails
- Email Statistics: Track sending success rates and performance
- Rate Limiting: Prevent SMTP server overload with configurable delays
- File Attachments: Support for file attachments
- Connection Verification: Verify SMTP connections before sending
- TypeScript: Full TypeScript support with type definitions
Installation
npm install molana-mailerQuick Start
Basic Usage
import { MolanaMailer } from 'molana-mailer';
// Create a mailer instance with Gmail
const mailer = new MolanaMailer({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'your-app-password'
}
});
// Send a simple email
await mailer.sendEmail({
from: '[email protected]',
to: '[email protected]',
subject: 'Hello from Molana Mailer!',
text: 'This is a test email',
html: '<h1>Hello!</h1><p>This is a test email</p>'
});Using Pre-built Templates
import { MolanaMailer, EmailTemplates } from 'molana-mailer';
const mailer = new MolanaMailer({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'your-app-password'
}
});
// Get a welcome template
const welcomeTemplate = EmailTemplates.getWelcomeTemplate();
// Send email with template
await mailer.sendTemplateEmail(
welcomeTemplate,
{
name: 'John Doe',
companyName: 'My Company'
},
{
from: '[email protected]',
to: '[email protected]'
}
);Configuration
Gmail Setup
const mailer = new MolanaMailer({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'your-app-password' // Use App Password, not regular password
}
});Outlook Setup
const mailer = new MolanaMailer({
service: 'outlook',
auth: {
user: '[email protected]',
pass: 'your-password'
}
});Custom SMTP Setup
const mailer = new MolanaMailer({
host: 'smtp.your-provider.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '[email protected]',
pass: 'your-password'
}
});API Reference
Types and Interfaces
BulkEmailOptions
interface BulkEmailOptions {
delayBetweenEmails?: number; // milliseconds between emails
maxRetries?: number; // maximum retry attempts
retryDelay?: number; // milliseconds between retries
batchSize?: number; // emails processed per batch
}BulkEmailResult
interface BulkEmailResult {
success: boolean;
result?: any;
error?: string;
email: EmailOptions;
attempts: number;
batchIndex: number;
}EmailStats
interface EmailStats {
totalSent: number;
totalFailed: number;
lastSent: Date | null;
lastFailed: Date | null;
}MolanaMailer Class
Constructor
new MolanaMailer(config: EmailConfig | MolanaMailerConfig)Methods
sendEmail(options: EmailOptions): Promise<any>
Send a single email.
await mailer.sendEmail({
from: '[email protected]',
to: '[email protected]',
cc: '[email protected]', // optional
bcc: '[email protected]', // optional
subject: 'Email Subject',
text: 'Plain text version',
html: '<h1>HTML version</h1>',
attachments: [
{
filename: 'document.pdf',
content: Buffer.from('file content'),
contentType: 'application/pdf'
}
],
replyTo: '[email protected]', // optional
priority: 'high' // 'high' | 'normal' | 'low'
});sendTemplateEmail(template, data, options): Promise<any>
Send an email using a template with variable substitution.
await mailer.sendTemplateEmail(
template,
{ name: 'John', company: 'Acme Corp' },
{
from: '[email protected]',
to: '[email protected]',
subject: 'Welcome {{name}}!'
}
);sendBulkEmails(emails: EmailOptions[], options?: BulkEmailOptions): Promise<BulkEmailResult[]>
Send multiple emails with rate limiting, retry logic, and batch processing.
const results = await mailer.sendBulkEmails([
{
from: '[email protected]',
to: '[email protected]',
subject: 'Email 1',
text: 'Content 1'
},
{
from: '[email protected]',
to: '[email protected]',
subject: 'Email 2',
text: 'Content 2'
}
], {
delayBetweenEmails: 2000, // 2 seconds between emails
maxRetries: 3,
retryDelay: 5000, // 5 seconds between retries
batchSize: 5 // Process 5 emails at a time
});verifyConnection(): Promise<boolean>
Verify SMTP connection before sending emails.
getStats(): EmailStats
Get email sending statistics including total sent, failed, and timestamps.
getStatsSummary(): string
Get a human-readable summary of email sending statistics.
isHealthy(maxRecentFailures?: number): boolean
Check if the mailer is healthy based on failure rates.
const isConnected = await mailer.verifyConnection();
if (isConnected) {
console.log('SMTP connection verified!');
} else {
console.log('SMTP connection failed!');
}EmailTemplates Class
Available Templates
getWelcomeTemplate(): EmailTemplate
Welcome email template with variables: {{name}}, {{companyName}}
getPasswordResetTemplate(): EmailTemplate
Password reset template with variables: {{name}}, {{companyName}}, {{resetLink}}, {{expiryTime}}
getNewsletterTemplate(): EmailTemplate
Newsletter template with variables: {{name}}, {{companyName}}, {{newsletterTitle}}, {{newsletterIntro}}, {{featuredContent}}, {{newsletterBody}}, {{ctaText}}, {{ctaLink}}, {{unsubscribeLink}}
getOrderConfirmationTemplate(): EmailTemplate
Order confirmation template with variables: {{customerName}}, {{companyName}}, {{orderNumber}}, {{orderDate}}, {{totalAmount}}, {{shippingAddress}}
createCustomTemplate(subject: string, html: string, text?: string): EmailTemplate
Create a custom email template.
const customTemplate = EmailTemplates.createCustomTemplate(
'Hello {{name}}!',
'<h1>Hello {{name}}!</h1><p>Welcome to {{company}}!</p>',
'Hello {{name}}! Welcome to {{company}}!'
);Template Variables
Templates use an advanced variable substitution system with support for:
- Simple Variables:
{{variableName}} - Loops:
{{#each items}}...{{/each}} - Conditionals:
{{#if condition}}...{{/if}}
// Template
const template = {
subject: 'Welcome to {{companyName}}, {{name}}!',
html: '<h1>Hello {{name}}!</h1><p>Welcome to {{companyName}}!</p>'
};
// Data
const data = {
name: 'John Doe',
companyName: 'Acme Corp'
};
// Result
// Subject: "Welcome to Acme Corp, John Doe!"
// HTML: "<h1>Hello John Doe!</h1><p>Welcome to Acme Corp!</p>"
### Advanced Template Examples
#### Loops Example
```typescript
const template = {
subject: 'Your Order #{{orderNumber}}',
html: `
<h1>Order Items:</h1>
<ul>
{{#each items}}
<li>{{name}} - {{quantity}} x ${{price}}</li>
{{/each}}
</ul>
`
};
const data = {
orderNumber: '12345',
items: [
{ name: 'Product A', quantity: 2, price: 19.99 },
{ name: 'Product B', quantity: 1, price: 29.99 }
]
};Conditionals Example
const template = {
subject: 'Welcome {{name}}!',
html: `
<h1>Hello {{name}}!</h1>
{{#if isPremium}}
<p>Welcome to our premium service!</p>
{{/if}}
<p>Thank you for joining {{company}}!</p>
`
};
## Examples
### Complete Example with Gmail
```typescript
import { MolanaMailer, EmailTemplates } from 'molana-mailer';
async function sendWelcomeEmail() {
// Create mailer instance
const mailer = new MolanaMailer({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'your-app-password'
}
});
// Verify connection
const isConnected = await mailer.verifyConnection();
if (!isConnected) {
throw new Error('Failed to connect to SMTP server');
}
// Get welcome template
const welcomeTemplate = EmailTemplates.getWelcomeTemplate();
// Send welcome email
try {
const result = await mailer.sendTemplateEmail(
welcomeTemplate,
{
name: 'John Doe',
companyName: 'My Awesome Company'
},
{
from: '[email protected]',
to: '[email protected]'
}
);
console.log('Welcome email sent successfully!', result);
} catch (error) {
console.error('Failed to send welcome email:', error);
}
}
sendWelcomeEmail();Enhanced Bulk Email Example
import { MolanaMailer, EmailTemplates } from 'molana-mailer';
async function sendBulkNewsletter() {
const mailer = new MolanaMailer({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'your-app-password'
}
});
const newsletterTemplate = EmailTemplates.getNewsletterTemplate();
const subscribers = [
{ email: '[email protected]', name: 'User 1' },
{ email: '[email protected]', name: 'User 2' },
{ email: '[email protected]', name: 'User 3' }
];
const emails = subscribers.map(subscriber => ({
from: '[email protected]',
to: subscriber.email,
subject: newsletterTemplate.subject,
html: newsletterTemplate.html,
text: newsletterTemplate.text
}));
// Enhanced bulk email with rate limiting and retry logic
const results = await mailer.sendBulkEmails(emails, {
delayBetweenEmails: 2000, // 2 seconds between emails
maxRetries: 3,
retryDelay: 5000, // 5 seconds between retries
batchSize: 5 // Process 5 emails at a time
});
results.forEach((result, index) => {
if (result.success) {
console.log(`Email sent successfully to ${subscribers[index].email} (attempts: ${result.attempts})`);
} else {
console.error(`Failed to send email to ${subscribers[index].email} after ${result.attempts} attempts:`, result.error);
}
});
// Get statistics
console.log(mailer.getStatsSummary());
console.log('Mailer healthy:', mailer.isHealthy());
}
sendBulkNewsletter();Error Handling
try {
await mailer.sendEmail({
from: '[email protected]',
to: '[email protected]',
subject: 'Test Email',
text: 'This is a test'
});
} catch (error) {
console.error('Email sending failed:', error.message);
}Security Notes
- For Gmail, use App Passwords instead of your regular password
- Store sensitive credentials in environment variables
- Use secure connections (TLS/SSL) when possible
- Validate email addresses before sending
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some 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.
Support
If you encounter any issues or have questions, please open an issue on GitHub.
