We're planting a tree for every job application! Click here to learn more

How to Schedule Emails Using Node

Blessing Krofegha

11 Apr 2022

•

6 min read

How to Schedule Emails Using Node
  • Node.js

Did you once think of sending an email that needs to arrive at a particular time for it to be most effective? That's what scheduled emails are about. They come in very handy when you want to send specific emails of project calendars, or weekly reports worked upon during weekends or midnights but want your team members in a different time-zone to view at an optimal time, say Monday 9 AM.

In this article, you will learn how to schedule emails using Node.js. I will show you how to do this using the Nodemailer and node-cron modules. Nodemailer is a super cool node module that makes it easy to streamline creating email templates and sending emails to users. With the node-cron module, you can schedule operations and repeat tasks at specific time intervals.

First, I will show you how node-cron works to schedule processes and define how many times and when you should repeat them within your Node.js server. Next, I will show you the steps to send emails from a Node.js app. After that, you will also learn how to automate the process and schedule emails.

Pre-requisites

What you'll need for this tutorial:

  1. Knowledge of JavaScript and Node.

  2. Node & NPM - To get started with the project, you'll need Node and NPM installed on your local machine. To confirm they're installed, run the following commands in your terminal:

node --v


npm --v

The Node Package Manager comes installed with Node, and it allows us to install various application dependencies. If you don't have them installed, you can follow the instructions on the official Node.js website.

This tutorial works with Node v14.18.2, npm v6.14.15, node-cron v3.0.0, nodemailer v6.7.2, and express v4.17.2.

Table of Contents

Here’s what we’ll cover today:

  • What are scheduled emails?
  • What is node-cron?
  • What is Nodemailer?
  • Project setup
  • Building the server and scheduling a cron job
  • Sending emails with Nodemailer
  • Automating the process for scheduled emails
  • Conclusion

What are scheduled emails?

Email scheduling is the ability to schedule an email (maybe marketing, sales, or personal) for a future event. The essential part of email scheduling is creating extraordinarily customized email campaigns without an expensive third-party integration. It allows you to send out emails to your subscribers very effectively.

What is node-cron?

Cron is a tool that makes it possible to execute something on a schedule. In Node.js applications, cron-like functionalities can be performed using packages such as the node-cron module, which uses the crontab syntax you would learn about in this article.

What is Nodemailer?

Nodemailer is a famous Node.js module that allows sending emails from Node.js applications. The creators themselves say that it makes sending an email a piece of cake.

Some features of Nodemailer are:

  • Platform-independence.
  • Massive focus on security - email delivery with TLS/STARTTLS and DKIM email authentication.
  • Unicode support, including emojis.
  • Ability to embed the HTML content and image attachments.
  • Different transport methods besides the built-in SMTP support.

Project setup

Now, we can kick off the project by creating a scheduled-email folder (you can give it a name of your choice if you'd like). The next thing we do is to initialize Node in the project folder by running the following in the terminal, from the scheduled-email directory:

npm init --yes

It creates a package.json file which makes it possible to track application dependencies.

Building the server and scheduling a cron job

Now, let's build the server and schedule a cron job.

We first install the web framework called Express to build the webserver and the node-cron module to schedule tasks by running the command below in the project terminal:

npm install express node-cron

Then, let's create a file in the project directory called index.js by running the following in the terminal:

 touch index.js

We begin writing codes by importing the express and node-cron modules in the index.js file; then, we create a new Express instance on which we'd build the server.

const cron = require('node-cron');
const express = require('express');

// Create an instance of Express
app = express();

With the server now created, we can build a simple scheduling function and then run the server at port 3000 by adding the following codes below:

cron.schedule('* * * * *', () =>
 console.log('Tasked scheduled with 1 minute interval')
);

app.listen(3000);

Now, when you run node index on the terminal, you get an output as shown below:

The terminal keeps printing 'Tasked scheduled with 1-minute interval' after every minute. This is made possible because the node-cron works using the full crontab syntax. Let's see how that works:

cron.schedule(cronExpression: string, task: Function, options: Object)

The crontab syntax looks like this:

  * * * * * *
  | | | | | |
  | | | | | day of week
  | | | | month
  | | | day of month
  | | hour
  | minute
  second ( optional )

A single asterisk behaves like a wildcard, and this means that it will run the task for every instance of that unit of time. Five asterisks ('* * * * *'), as used in our current project, represents the crontab default of running a task every minute.

Placing a number in the place of asterisks will be treated as values for that unit of time. This allows you to schedule tasks to occur daily, weekly, or in a more difficult time.

Sending emails with Nodemailer

Before I show you how to schedule emails using Node.js, I find it essential to learn how to send an email from your Node.js app using Nodemailer.

For starters, let's install the Nodemailer module in our app by running the following command in the terminal from the project directory:

npm install nodemailer

Since this demonstration shows how to send an email without scheduling it, let's create a separate file in the project directory called email.js.

In email.js, import the nodemailer module.

const nodemailer = require('nodemailer');

Next, follow these three steps to get things working:

  1. Create the message option: This tells nodemailer who is sending what message to whom?
let mailOptions = {
  from: '<FROM_EMAIL_ADDRESS>',
  to: '<TO_EMAIL_ADDRESS>',
  subject: 'Email from Node-App: A Test Message!',
  text: 'Some content to send',
};

The to property in the mailOptions can have multiple email ids separated by commas(,).

  1. Create a nodemailer transporter using either SMTP(this is the default transport method) or some other transport mechanism, like shown below:
let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '<FROM_EMAIL_ADDRESS>',
    pass: '<FROM_EMAIL_PASSWORD>',
  },
});

In our use case, Gmail is used as the service. However, you can specify the name of the email service you'd want to use.

Note: For this to work with Gmail as your service, make sure you allow less secure apps to access Gmail for the sake of this tutorial. Also, replace the content in angular brackets with your email address, password, and receiver's email address.

Nodemailer also supports test accounts that are provided by Ethereal Email. You can create an Ethereal account and use the username and password generated.

  1. Use the sendMail() method of the transporter you created to deliver the message.
transporter.sendMail(mailOptions, (error, info) => {
  if (error) console.log(error);
  else console.log('Email sent: ' + info.response);
});

Now, the content of email.js should look like this:

const nodemailer = require('nodemailer');

let mailOptions = {
  from: '<FROM_EMAIL_ADDRESS>',
  to: '<TO_EMAIL_ADDRESS>',
  subject: 'Email from Node-App: A Test Message!',
  text: 'Some content to send',
  html: '<b>The html content</b>'
};

// Mail transport configuration
let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '<FROM_EMAIL_ADDRESS>',
    pass: '<FROM_EMAIL_PASSWORD>',
  },
  tls: {
    rejectUnauthorized: false,
  },
});

// Delivering mail with sendMail method
transporter.sendMail(mailOptions, (error, info) => {
  if (error) console.log(error);
  else console.log('Email sent: ' + info.response);
});

By running node email in the terminal, it should output a successful result like shown below:

That's it! You are done. Make sure to use your proper email credentials before testing, and with that, you have all that's required to send an email from your Node.js app.

Automating the process for scheduled emails

Now that we know how to send an email using Node.js, it's time to learn how to schedule the email so that you can send it at the perfect time you wish.

Now, let's execute the scheduling process by using the cron function we created earlier to automate the sendMail function we have just created.

The implementation is shown below, and index.js is updated to become:

const cron = require('node-cron');
const express = require('express');
const nodemailer = require('nodemailer');

// Create an instance of Express
app = express();

let mailOptions = {
  from: '<FROM_EMAIL_ADDRESS>',
  to: '<TO_EMAIL_ADDRESS>',
  subject: 'Email from Node-App: A Test Message!',
  text: 'Some content to send',
  html: '<b>The html content</b>'
};

// Mail transport configuration
let transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '<FROM_EMAIL_ADDRESS>',
    pass: '<FROM_EMAIL_PASSWORD>',
  },
  tls: {
    rejectUnauthorized: false,
  },
});

cron.schedule('* * * * *', function () {
  console.log('---------------------');
  console.log('Running Cron Process');
  // Delivering mail with sendMail method
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) console.log(error);
    else console.log('Email sent: ' + info.response);
  });
});

app.listen(3000);

I am scheduling the email to send every minute in the combined code.

Now, when you run node index from the terminal of the project directory, it should output the result like shown below:

Conclusion

Now, you can easily send personalized emails when you consider optimal using Node.js, node-cron, and the nodemailer module. Don't forget that the nodemailer documentation is your best friend for learning about the more complex available options.

Happy coding!

Resources

Nodemailer documentation

Did you like this article?

Blessing Krofegha

Blessing Krofegha is a Software Engineer Based in Lagos Nigeria, with a burning desire to contribute to making the web awesome for all, by writing and building solutions.

See other articles by Blessing

Related jobs

See all

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Related articles

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

•

12 Sep 2021

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

•

12 Sep 2021

WorksHub

CareersCompaniesSitemapFunctional WorksBlockchain WorksJavaScript WorksAI WorksGolang WorksJava WorksPython WorksRemote Works
hello@works-hub.com

Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ

108 E 16th Street, New York, NY 10003

Subscribe to our newsletter

Join over 111,000 others and get access to exclusive content, job opportunities and more!

© 2024 WorksHub

Privacy PolicyDeveloped by WorksHub