OneCompiler

Sending email using Gmail in NodeJS

219

Using nodemailer package in NodeJS we can use gmail credentials to send emails programatically.

Following code shows how to do that

const nodemailer = require('nodemailer');

// one time configuration
let mailTransporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '[email protected]', // repalce this with your email
    pass: 'sender_password'         // replace this with your password
  }
});

function sendEmail(toEmail, subject, body){

  let mailDetails = {
    from: '[email protected]', // repalce this with your email
    to: toEmail,
    subject: subject,
    text: body
  };  
	
  mailTransporter.sendMail(mailDetails,function (err, data) {
    if (err) {
      console.log('email sending failed', err);
    } else {
      console.log('email sent successfully!');
    }
  });
}