DEV Community

SH-Hong
SH-Hong

Posted on • Edited on • Originally published at pulsecron.com

5 2 2 2 2

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
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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'
  }
});
Enter fullscreen mode Exit fullscreen mode

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 });

Enter fullscreen mode Exit fullscreen mode

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');
  }
});
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

7.Start the Server

Launch your Express server:

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

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

👉 Join our open source project related to this topic

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay