How to Schedule and Send E-mails from a Node.js app

Sending emails refers to the act of electronically transmitting messages from one computer or device to another through an email system. It's like sending a digital letter, where you compose a message, add recipients, and hit send to deliver it to their email address. This method allows for faster and more convenient communication compared to traditional mail.

In this article, we will learn how to send emails from your Node.js app. At the end of it, we will be able to schedule and send e-mails. Not only that, we will be creating a REST API to post required details to a node.js app for sending emails.

Setting 

Nodemailer is a super cool module for the Node.js application to allow email sending so easily. Install it using npm

npm install nodemailer --save

Import Nodemailer in your .js(app.js, email.js whatever) file:

let nodemailer = require('nodemailer');

Next, follow these three simple steps to get things working:

Setup a message option: This is to tell 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'
};

Note: The to property above can have multiple email ids separated by commas(,).

Create a Nodemailer transporter using either SMTP(this is default) or some other transport mechanism

let transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: '<FROM_EMAIL_ADDRESS>',
        pass: '<FROM_EMAIL_PASSWORD>'
      }
});

Note: In the above example, we have mentioned the service as gmail. It is just an example. You can specify the name of the e-mail services you want to use.

Use the sendMail() method of your previously created transporter to deliver the message.

transporter.sendMail(mailOptions, function(error, info){
      if (error) {
        console.log(error);
      } else {
        console.log('Email sent: ' + info.response);
      }
});

That's all, and you are done. Now we have everything required to send e-mail from this node.js app.

Hang on a Minute. We can schedule it!

Yeah, right! The real power of this app comes with the fact that you will be able to schedule the emails like,

  • Send now
  • Send every day at 7 p.m. (19:00 hrs), like a daily-digest
  • Send every 30 minutes.
  • Send on 29th Feb!
  • Many many more desired ways.

You guessed it right, we need something like a cron job, and for that, we will be using a node module called node-cron.

First install it.

node install node-cron --save

Import node-cron and schedule a task

let cron = require('node-cron');

cron.schedule('* * * * *', () => {
   console.log('running a task every minute');
});

Note: You can read about several cron schedule patterns here. In the above example, we have scheduled a simple console log in every minute.

Here is the combined code where I am scheduling the e-mail to send every minute:

  let cron = require('node-cron');
  let nodemailer = require('nodemailer');

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

  // e-mail transport configuration
  let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: '<FROM_EMAIL_ADDRESS>',
          pass: '<FROM_EMAIL_PASSWORD>'
        }
    });

 cron.schedule('* * * * *', () => {
  // Send e-mail
  transporter.sendMail(mailOptions, function(error, info){
        if (error) {
          console.log(error);
        } else {
          console.log('Email sent: ' + info.response);
        }
    });
  });

REST API to Schedule and Send e-mail

  • Create a route in the routes.js file of your sails.js app
'post /api/sendemail': 'EmailController.sendEmail'
  • Create an EmailController with the sendEmail method. This method should have the code discussed above for scheduling and sending emails.

Wow, that was quick.

 Note: With sails.js, you can also use other cron libraries like sails-hook-cron as well. You can find the details here.

Conlucion

In this tutorial you learned the simple steps to send email from a node.js application

#node.js #javascript #sailsjs #web development

How to Schedule and Send E-mails from a Node.js app
18.65 GEEK