Reusable Node Code Modules, Part 6 - Notifications - Email
Keeping Users Informed: Implementing Reusable Email Notification Modules
Email notifications are crucial for user communication, including account verification, password resets, and general updates. Implementing a reusable email notification module ensures consistent email handling across projects. This guide covers how to structure reusable email notification modules in Node.js using Express, manage email sending efficiently, and integrate common libraries.
Common Libraries and Tools
1. Nodemailer
Nodemailer is a popular module for sending emails in Node.js.
Key Features
SMTP Support: Supports sending emails via SMTP
OAuth2: Supports OAuth2 for secure authentication
Attachments: Allows sending emails with attachments
Templating: Supports various templating engines for email content
2. SendGrid
SendGrid is a cloud-based email service that provides reliable email delivery
Key Features
Email Delivery: Reliable email delivery with high deliverability rates
Templates: Supports dynamic email templates
Analytics: Provides email analytics and tracking
API Integration: Easy integration with a RESTful API
3. Mailgun
Mailgun is an email automation service for sending, receiving, and tracking emails
Key Features
Email Delivery: High deliverability with advanced email routing
Validation: Email validation to ensure accurate email addresses
Tracking: Detailed email tracking and analytics
API Integration: Simple and flexible API for integration
4. Amazon SES (Simple Email Service)
Amazon SES is a cost-effective, scalable email service for businesses
Key Features
Scalability: Easily scales to handle large volumes of emails
Cost-Effective: Competitive pricing for high-volume email sending
Security: Supports DKIM, SPF, and DMARC for email security
Integration with AWS: Seamlessly integrates with other AWS services
Comparison
Nodemailer: Best for simple email sending with SMTP support and templating.
SendGrid: Ideal for reliable email delivery with dynamic templates and analytics.
Mailgun: Suitable for advanced email routing, validation, and tracking.
Amazon SES: Best for scalable, cost-effective email sending with strong security features.
Examples and Wrapper Class
Example 1: Nodemailer
Setup:
$ npm install nodemailer
Configuration:
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-email-password'
}
});
const sendEmail = async (to, subject, text) => {
const mailOptions = {
from: 'your-email@gmail.com',
to,
subject,
text
};
try {
await transporter.sendMail(mailOptions);
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
}
};
export default sendEmail;
Wrapper Class:
class EmailClient {
constructor() {
this.transporter = transporter;
}
async sendEmail(to, subject, text) {
const mailOptions = {
from: 'your-email@gmail.com',
to,
subject,
text
};
try {
await this.transporter.sendMail(mailOptions);
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
}
}
}
export default new EmailClient();
Example 2: SendGrid
Setup:
$ npm install @sendgrid/mail
Configuration:
import sgMail from '@sendgrid/mail';
sgMail.setApiKey('your-sendgrid-api-key');
const sendEmail = async (to, subject, text) => {
const msg = {
to,
from: 'your-email@example.com',
subject,
text
};
try {
await sgMail.send(msg);
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
}
};
export default sendEmail;
Wrapper Class:
class SendGridClient {
constructor() {
sgMail.setApiKey('your-sendgrid-api-key');
}
async sendEmail(to, subject, text) {
const msg = {
to,
from: 'your-email@example.com',
subject,
text
};
try {
await sgMail.send(msg);
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
}
}
}
export default new SendGridClient();
Example 3: Mailgun
Setup:
$ npm install mailgun-js
Configuration:
import mailgun from 'mailgun-js';
const mg = mailgun({ apiKey: 'your-mailgun-api-key', domain: 'your-mailgun-domain' });
const sendEmail = async (to, subject, text) => {
const data = {
from: 'your-email@example.com',
to,
subject,
text
};
try {
await mg.messages().send(data);
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
}
};
export default sendEmail;
Wrapper Class:
class MailgunClient {
constructor() {
this.mg = mailgun({ apiKey: 'your-mailgun-api-key', domain: 'your-mailgun-domain' });
}
async sendEmail(to, subject, text) {
const data = {
from: 'your-email@example.com',
to,
subject,
text
};
try {
await this.mg.messages().send(data);
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
}
}
}
export default new MailgunClient();
Example 4: Amazon SES
Setup:
$ npm install aws-sdk
Configuration:
import AWS from 'aws-sdk';
AWS.config.update({
accessKeyId: 'your-access-key-id',
secretAccessKey: 'your-secret-access-key',
region: 'your-region'
});
const ses = new AWS.SES({ apiVersion: '2010-12-01' });
const sendEmail = async (to, subject, text) => {
const params = {
Destination: {
ToAddresses: [to]
},
Message: {
Body: {
Text: { Data: text }
},
Subject: { Data: subject }
},
Source: 'your-email@example.com'
};
try {
await ses.sendEmail(params).promise();
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
}
};
export default sendEmail;
Wrapper Class:
class SESClient {
constructor() {
AWS.config.update({
accessKeyId: 'your-access-key-id',
secretAccessKey: 'your-secret-access-key',
region: 'your-region'
});
this.ses = new AWS.SES({ apiVersion: '2010-12-01' });
}
async sendEmail(to, subject, text) {
const params = {
Destination: {
ToAddresses: [to]
},
Message: {
Body: {
Text: { Data: text }
},
Subject: { Data: subject }
},
Source: 'your-email@example.com'
};
try {
await this.ses.sendEmail(params).promise();
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email:', error);
}
}
}
export default new SESClient();