How to set up emails in NodeJS?

Krunal Shah

Dec 13, 2019 | 3 min read

Essentially in every web application, there's a need to send the user an email. In this article, we will set up an easy module that will handle our mail sending.

  1. Nodemailer
  2. SendGrid

Prerequisites

  • Node installed on your machine
  • NPM installed on your machine
  • Basic Knowledge of JavaScript
  • Create Node Application into your system
  • Install Node packages like express
  • Create Backend Server in index.js file using the express package
  • Then Listen to your Application with some random port e.g 4001

1. Send Email Using Nodemailer

Install Nodemailer

The nodemailer module used to send emails from your node server. To install the module the following command is executed from the terminal

npm install nodemailer --save

To use nodemailer the module has to be imported in index.js file:

const nodeMailer = require('nodemailer');

Setup Transport Object

Create a transporter object using the default SMTP transport which can send emails. In this example, I am using Gmail. Add the Bellow code in your index.js file.

let transporter = nodemailer.createTransport({
    host: "smtp.gmail.email",
    port: 587,
    secure: false, // true for 465
    auth: {
        user: testAccount.user, // your gmail email adress
        pass: testAccount.pass // your gmail password
    }
});

Verify your Nodemailer configuration

To verify your nodemailer SMTP is correctly working on your server verify() function has been used.

Add the Bellow function code in your index.js file and call it.

function verifySmtp(){
        // verify connection configuration
   smtpTransport.verify(function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log('Server is ready for emails');
        }
        return true;
  });
}
verifySmtp(); // call function in index.js file

Basic example of Sending Email with HTML and text

  • Add the below code in your index.js file.
const nodeMailer = require('nodemailer');

exports.sendMail = function(req,res){
  const transporter = nodeMailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: true,  //true for 465 port
    auth: {
      user: 'email@example.com',
      pass: 'password'
    }
  });

  const mailOptions = {
    from: '"Your Name" <email@example.com>', // sender address
    to: 'abc@example.com, xyz@example.com', // list of receivers
    subject: 'Hello ', // Subject line
    text: 'Hello world?', // plain text body
    html: '<b>Hello world?</b>' // html body
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      res.status(400).send({success: false})
    } else {
      res.status(200).send({success: true});
    }
});

2 Send Email Using SendGrid

Install SendGrid

The sendgrid module used to send emails from your node server. To install the module the following command is executed from the terminal

npm install @sendgrid/mail --save

To use sendgrid the module has to be imported in index.js file:

const SGmail = require('@sendgrid/mail');

Now we have the Sendgrid node package for the sending emails in your node application.

Configuring SendGrid

To use this package you need an API key that you will get after you have created an account with SendGrid.

Add the below code in your index.js file.

SGmail.setApikey('xxxxx-xxxxx') // Input Api key or add to environment config

Basic example of Sending Email with SendGrid

  • Add the below code in your index.js file.
const SGmail = require('@sendgrid/mail');

SGmail.setApikey('xxxxx-xxxxx') // Input Api key or add to environment config

exports.sendMail = function(req,res){
  const mailOptions = {
    to : email, //email variable
    from : { email : 'your email' , name: 'Name of user you want to  send email as'},
    message : `Hi there, ${name}`,
    subject : "This is a test Email"
  };

  SGmail.send(message).then((sent) => {
   console.log("Email has been sent.");
 })
}

Conclusion

  • We saw how easy it is to send emails from your node server by using nodemailer and sendgrid.
  • Nodemailer is a free library to send emails in nodeJs.
  • SendGrid is free as well as a paid library, so please check the pricing of SendGrid before integrating it from link
· · · ·

Third Rock Techkno is a leading IT services company. We are a top-ranked web, voice and mobile app development company with over 10 years of experience. Client success forms the core of our value system.

We have expertise in the latest technologies including angular, react native, iOs, Android and more. Third Rock Techkno has developed smart, scalable and innovative solutions for clients across a host of industries.

Our team of dedicated developers combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.