Send mail in nodejs

In this article, we will show you how to send mail using nodemailer. Nodemailer is a module for Node.js Application. It allows sending emails in an easy way. Here we will discuss how to send mail through the Gmail SMTP server.

Before starting this article First, you have to

  • unlock your Google account using this link
  • give access to Less secure app in your Google account using this link


Because if you do not give this above access then you can't connect your google account with your node.js application. Following errors will be shown:


  • Error { Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbvl
  • Error { Error: connect ETIMEDOUT 74.125.24.108:25    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)


So you have to give the above two access in your google account.
After completion of the above access now comes to your node.js application. Now install Nodemailer module.

npm install nodemailer

Then install nodemailer-smtp-transport module.

npm install nodemailer-smtp-transport

After that write following code in your node.js application for sending mail.

const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
function sendEmail(subject, html){
  nodemailer.createTestAccount((err, account) => {
      var transporter = nodemailer.createTransport(smtpTransport({
         service:"Gmail",
          auth: {
              user: 'admin@gmail.com',       // Sender mail id
              pass: 'admin@1234'                 // Sender password
          }
          }));
      let mailOptions = {
          from: 'admin@gmail.com',        // Sender mail id
          to: 'user@gmail.com',                // Reciever mail id (For multiple recievers to:'abc@gmail.com,xyz@gmail.com')
          subject: subject,
          html: html 
      };

      transporter.sendMail(mailOptions, (error, info) => {
          if (error) {
              console.log('Error', error);
          }
          else{
              console.log('Success', info);
          }
      });
  });
}

Output will be:

Success { accepted: [ 'admin@gmail.com' ],
  rejected: [],
  response: '250 2.0.0 OK  1571372009 s18sm10868303pji.30 - gsmtp',
  envelope:
   { from: 'admin@gmail.com',
     to: [ 'admin@gmail.com' ] },
  messageId: '388a2385-e3cf-fd12-4e52-ffa2776b9a3d@gmail.com' }


send mail in node.js,sending email in node js,send mail in node js using smtp,send mail in node js without password,send html email in node.js,send smtp mail in node js,send mail node.js gmail,sending email in node js

Post a Comment

0 Comments