Sending a mail using Nodemailer — NodeJs

Rachit Gupta
2 min readJan 9, 2021

Nodemailer is a module for Nodejs application to send mails in an easy way. We often think of some complex protocols, hefty networks, HTTP, SMTP etc. while adding code for sending emails, but it’s as easy as you might not have thought.

Let’s get started with it —

first install nodemailer module in your application

npm install --save nodemailer

This command will install all the files related to nodemailer in your nodejs application

The next step is to add nodemailer in your application —

app.js

const nodemailer = require('nodemailer');

working of nodemailer — it takes a transport service using which it sends email. For this article, I am using ZOHO email, but you can use any email host like gmail.

in your app.js file, use the code

let transporter = nodemailer.createTransport({
host: "smtp.zoho.in",
secure: true, // true for 465, false for others
port: 465,
auth: {
user: "youremail@email.com",
pass: "yourpassword",
},
});
auth: {
user: "youremail@email.com",
pass: "yourpassword",
},
});

port 465 is a secure port for email service.

Auth object inside the transport variable carries your email and password which the host will use for authenticating and getting access to send mails.
Now we need another configuration code to be written in app.js file

app.js

var message = {
from: 'address@email.com', // Sender address
to: recipient@email.com, // List of recipients
subject: '<Hi, welcome to my mail>', // Subject line
html: "<b>Hello world?</b>,
attachments:[{
filename: "file.txt",
content: new Buffer(),
}]
};

in the above code,

from: sender’s email address
to: receiver’s email address
subject: “welcome to abc”
html: <Html Code of your email>
attachments: [] //optional

Now, the final step is to send the email using .sendEmail() function of the nodemailer module.

transporter.sendMail(message,function(err,info){
if(err){
console.log("Error is ", err.message);
}else{
console.log("Email sent!", info);
}});

sendMail function takes two argument mailOptions and a callback function which will be called when the mail is sent. The callback function will be called when either email sent successfully our an error occurred.

And that’s the end of this post, on how to use nodemailer in nodejs application.

Hi, my name is Rachit Gupta. Working as a Data Analyst, I spent time writing Javascript code. Catch me on my linkedin below

--

--

Rachit Gupta
0 Followers

Computer Science Engineer | Decision Analyst | NodeJS ❤ MongoDB |