How to send Emails in Node.js — Codementor.tech

chirag patel
2 min readJul 17, 2018

--

If you want full specification please go through THIS article.

https://www.programmingschool.io/how-to-send-emails-in-node-js/

First, install NodeMailer to your node application

npm install --save nodemailer

After installing in your js file require it

const nodeMailer = require('nodemailer');

Now, create transporter object using the default SMTP transport which can send emails. In this example, I am using ZOHO mail.

let transporter = nodeMailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true, //true for 465 port, false for other ports
auth: {
user: 'email@example.com',
pass: 'password'
}
});

In auth object specify your email address and password.

Now, we need to configure our email details.

// setup email data with unicode symbols
let mailOptions = {
from: '"Your Name" <youremail@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
};

Now the last thing is actually sending the email using ‘sendMail()’ method provided by the transporter object we created.

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

‘sendMail()’ method 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 or an error occurred.

Putting everything together,

'use strict';const nodeMailer = require('nodemailer');exports.sendMail = function(req,res){
const transporter = nodeMailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true, //true for 465 port, false for other ports
auth: {
user: 'email@example.com',
pass: 'password'
}
});
const mailOptions = {
from: '"Your Name" <youremail@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) {
console.log(error);
res.status(400).send({success: false})
} else {
res.status(200).send({success: true});
}
});
}

And that’s how we send emails using NodeMailer.

Github link: https://goo.gl/X9dpHx

Here are more tutorials on node.js:

  1. An easy way to build node.js RESTful APIs
  2. File upload in Node.js

Any doubts, feel free to comment.

Happy Coding!!

Cheers!!

--

--

chirag patel
chirag patel

Written by chirag patel

Software Developer , Author @codemetor.tech

Responses (1)