Getting started with Nodemailer

Getting started with Nodemailer

Nodemailer is one of the most popular node modules to send emails from a Node.js backend. In this article, we will set up a simple email sending service from our Node.js app.

Setting Up Directory :

We will start by making a directory for our project and initializing npm :

npm init

Now we will install nodemailer

npm install nodemailer

Now we will make our JS file

touch app.js

Mailtrap

For the scope of this article, we will be using Mailtrap. It is a sandbox email service where we can capture emails from development environments. In simpler words, this service is being used to mimic the functionality of a production platform like Gmail.com or Outlook.com.

There are a few reasons we are not using live Email services. The most important one is security. A live email inbox should not be used for development/testing purposes as inboxes may have sensitive data. Another big reason is that setting up a less-secure connection with a simple app is not very beginner-friendly. Modern email services come with Two-Factor Authentication where users are generally asked to verify access via Email and Phone Numbers.

Google has disabled less-secure app connections as of 30th May 2022 for Gmail using only Email & Password. Not very developer-friendly but extremely secure.

Thus we will set up our account on Mailtrap

Screenshot from 2022-06-16 12-36-19.png

After logging in, select inboxes from the left panel and click on 'My Inbox' under Projects.

Screenshot from 2022-06-16 12-51-59.png

In the Inbox section, there is a dropdown menu as "Integrations". We need to select Nodemailer from this menu. Pay special attention to the transport object given to us. This will be used directly in our JS file.

Screenshot from 2022-06-16 12-58-37.png

Setting up the JS application.

in our app.js file, first, we will import the nodemailer module.

const nodemailer = require('nodemailer');

Now we can just bring in our transport object from the mailtrap inbox :

const transporter = nodemailer.createTransport({
    host: "smtp.mailtrap.io", //emailing service host
    port: 2525, // emailing service port
    auth: {
      user: "Given Username", // username
      pass: "Given Password" // password
    }
  });

This transporter object contains all the email service configurations. In this case, we have :

  • Host: Emailing Service Host Name

  • Port: Emailing Service Port

  • Auth Object: This has the username ( or email ) and password of the email that is being used to send the emails.

Now that we have our transported object, we need to configure the email that we will be sending. For this, we will create an email object. The email object needs a "to" email and a "from" email. We can also add a "subject". For the body, we can use "text" or even "html" and send in an HTML template. We can also use JS Template Literals (${variable}) syntax to add variables to our text or template. Here, I've used a function to wrap the email options object and included a simple HTML template :

const emailOptions = (name,recieverEmail)=>{
    return email = {
        from: 'sender@sampleMail.com',
        to: recieverEmail,
        subject: 'Welcome to our website',
        html: `
       <h1> Hi ${name} ! </h1>
        <br>
        <h2> Welcome To our Website. </h2>
        <br>
        For any Queries, Please contact : XXXXXXXXXX
        <br>
        Thanks and Regards
        <br>
        Website Team
        `
    }
}

We will use the transporter object to send the email object. For this, we will use the sendMail function from nodemailer.

const mailer = () => {

    let name = "Roy";
    let recieverEmail = 'roy@gmail.com'

    email = emailOptions(name,recieverEmail);

    transporter.sendMail(email);

}

When we call this function, we can check our inbox on Mailtrap and we would've received an email like this :

Screenshot from 2022-06-16 13-16-09.png

We have successfully sent our very first email via our Node.js backend.

Important Note: Sending an Email is an Asynchronous process and appropriate async-await syntax should be used when using sendMail function in an application.

Conclusion & Future Scope

Thus, we have learned how to use nodemailer to send emails through our JS applications. There are endless possibilities where emails can be used and email services can be integrated. More technologies that can be looked at are SendGrid by Twillio, Google Cloud, and Amazon Web Server.

Here's the GitHub repo for the demo: github.com/architsinghal-mriirs/nodemailer-.. Cover Photo Credits: Image](freepik.com/vectors/new-message)

Did you find this article valuable?

Support WeMakeDevs by becoming a sponsor. Any amount is appreciated!