How to Send Email Using Cron Job in Node.js
Automating email sending is a common requirement in many applications, whether for sending newsletters, reminders, or notifications. Using cron jobs in Node.js can simplify this task significantly. In this post, we'll walk through setting up an email automation system using the Pulse library, which leverages MongoDB for task management.
Setting Up Your Environment
First, ensure you have Node.js and MongoDB installed on your system. Then, create a new Node.js project and install the necessary packages:
npm init -y
npm install express @pulsecron/pulse nodemailer --save
Integrate Pulse with Express
Here’s a step-by-step guide to integrating Pulse with an Express application for email scheduling:
1.Import Dependencies and Setup Express
Begin by importing required modules and setting up the Express server:
import express from 'express';
import Pulse from 'pulse';
import nodemailer from 'nodemailer';
const app = express();
const port = 3000;
app.use(express.json());
2.Configure Pulse
Set up Pulse to connect to MongoDB, where jobs will be managed:
const mongoConnectionString = 'mongodb://localhost:27017/pulse';
const pulse = new Pulse({
db: { address: mongoConnectionString, collection: 'cronjob' },
defaultConcurrency: 4,
maxConcurrency: 4,
processEvery: '10 seconds',
resumeOnRestart: true
});
3.Configure Nodemailer
Set up Nodemailer for sending emails:
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-email-password'
}
});
4.Define Email Job
Create a job definition for sending emails:
pulse.define('send email', async (job, done) => {
const { to, subject, text } = job.attrs.data;
const mailOptions = {
from: 'your-email@gmail.com',
to,
subject,
text
};
try {
await transporter.sendMail(mailOptions);
console.log(`Email sent to ${to}`);
done();
} catch (error) {
console.error(`Failed to send email to ${to}`, error);
done(error);
}
}, { shouldSaveResult: true });
5.Express Route to Trigger Email Job
Implement a route to schedule emails:
app.post('/send-email', async (req, res) => {
try {
await pulse.start();
const { to, subject, text, scheduleTime } = req.body;
const job = pulse.create('send email', { to, subject, text });
await job.schedule(new Date(scheduleTime)).save();
res.status(200).send('Email scheduled successfully');
} catch (error) {
console.error(error);
res.status(500).send('Failed to schedule email');
}
});
6.Event Listeners
Add listeners for various job events:
pulse.on('success', (job) => {
console.log(`Job <${job.attrs.name}> succeeded`);
});
pulse.on('fail', (error, job) => {
console.log(`Job <${job.attrs.name}> failed:`, error);
});
7.Start the Server
Launch your Express server:
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Conclusion
Implementing and managing such a system yourself is necessary but can be tedious and time-consuming. To focus more on product engineering, consider using a cloud service like Pulsecron for your scheduling needs. Pulsecron offers a managed solution that simplifies the entire process, allowing you to concentrate on building great features for your users.
👉 For the complete code and further details, please refer to the GitHub repository
👉 Learn more about Pulsecron's event-based scheduling solutions