Send Emails with Nodemailer

Randika Padmashali
4 min readMay 16, 2021

Nodemailer is a Node. js module that allows you to send emails from your server easily. This blog provides step-by-step instructions on how to send an email using Nodemailer.

You can install Nodemailer on your project with the following command

npm i nodemailer

Then create a file sendEmail.js in your project. First, you have to import nodemailer to your file.

Then create the sendMail function(This can be any name as your preference). It is a dynamic function. You can use this function across your application multiple times.

Then create transporter. You have to set a few properties on this function. the first one is “service”. The next field is auth. auth takes an object which has a user field that takes an email username and pass that takes an email password your service provider will give. We have not set any of these yet. We will do that next. For security purposes, it is best to save those properties on your .env file

Then create mailOptions. This is an object that has a “from ”field that contains senders email, a “subject ” field that contains the email subject, and a html field that contains the message you want to send. And “to ” field for the receiver’s email.

Then call sendEmail function on transporter that created. sendEmail takes mailOptions that we created and a function. Finally, the function must be exported.

Then we have to set up SendGrid account. We use SendGrid as our email service provider.To do that go to sendGrid.com

https://sendgrid.com/

You should have to create an account on SendGrid to use this service. It can do with few steps very easily.

after sign in you will be able to see this dashboard. In order to start click the setup guide as shown here.

On the setup guide click on send your first email. It gives two options. we gonna use web API or Stp Relay as shown below. Click on that.

Again provides two options. Select SMTP Relay

It asks for API key name. You can give it as your preference and press create key

Then you can see the details as shown below. You have to copy the Username and password. After copy them tick the check box and click next. (You should copy them before click next. otherwise, you can not get them again)

You have to paste Username and password in your .env file as shown below. (The variable name must be the same as in the sendEmail function)

Then complete .env file as shown in bellow

EMAIL_FROM should be the same email that you verified when you setting up your SendGrid account.

then you can create a route to send mail. First, you have to import sendMail function.

Then create a route as below

you can test the route with Postman

This is the final output

--

--