Skip to main content

Command Palette

Search for a command to run...

node js and nodemailer for send emails

Published
2 min read
A

Self taught developer working on Angular, Vue, Typescript, Node JS, MongoDB, Express JS, LoopBack API, Laravel, Laravel Lumen, mysql. write packages for angular/vue. Part time youtuber

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'
    }
  });
R
ramu k4y ago

nice...

More from this blog

Angular, TypeScript, Vue, Node JS, Express JS, MongoDB, MongoDB Cloud, PHP, Laravel, Slim Framework, Mysql, JavaScript, PWA

24 posts

I'm a Full Stack Developer, Open Source Contributor, Blogger, npm packages developer, Youtuber. My hobbies are Contribution in open source projects, blogging, develop npm packages, part time youtuber