node js and nodemailer for send emails

·

2 min read

Mail send is an important requirement for any type of web application. In this article we will see how we can send an email using nodemailer:

use this command in node application

npm install --save nodemailer

now in app.js file import library and make suggested changes:

const nodemailer = require("nodemailer");
async function main() {
  let authObj = nodemailer.createTransport({
    host: "smtp.office365.com",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: "your outlook email",
      pass: "your outlook password",
    }
  });

 // now use sendMail method using above authObj variable
  let info = await authObj.sendMail({
    from: '"Ashish" <yourmail@domain.com>', // sender address
    to: "receiver mail id",
    subject: "Hello",
    text: "Hello world?" // plain text body
    html: "<b>Hello world?</b>", // html body
  });
}

Above configuration will work in case we are using outlook SMTP. For Gmail change host to:

host: "smtp.gmail.com"

and change auth object as per your gmail username and password:

What should we do in case we want to send mail from html file:

create email.ejs file in our views directory:

<h1>Hello {{name}},</h1>
<div>
    Hope you are doing well
</div>

Now we need to add following code to send email using above html file

let info = await authObj.sendMail({
    from: '"Ashish" <yourmail@domain.com>', // sender address
    to: "receiver mail id",
    subject: "Hello",
// template is our ejs file
    template: 'email',
// context we are using to pass variables to our email template
    context: {
      name: 'Ashish'
    }
  });