How to send mail using NodeJS and Gmail?

Share

This article will show how to send emails using nodejs and Gmail. Before starting to write code we need to obtain an application password for the Gmail account. Previously, the user’s google account password was used to create a connection between your node application and your google account. But according to a recent security update in google, now we have to generate a separate application password.

Generating Gmail Application Password

  1. Go to your Google Account Dashboard.
  2. Go to Security.
  3. Scroll to Signing in to Google
  4. Click on App passwords
  5. Generate passwords for the Gmail app and set a custom device name. (Eg: web)
Generate d application password

After obtaining the application password, now it’s time to write code.

Creating Node Application

To send emails from the node application, we are going to use nodemailer package.

At first, we need to create a mail transporter using nodemailer.

    let transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        port: 465,
        secure: true, // true for 465, false for other ports
        auth: {
          user: 'yourgamail@gmail.com', // gmail id
          pass: 'your_application_password', // generated application password
        },
      });

trasporter helps to send an email, now we call the function to send a mail with mail content.

// sendEmail function

   let info = await transporter.sendMail({
        from: '"CodewithSudeep 👻" <codewithsudeep@gmail.com>', // sender address
        to: "user@gmail.com", // list of receivers
        subject: "Hello ✔", // Subject line
        text: "Hello world?", // plain text body
        html: "<b>Hello world?</b>", // html body
      });

This function returns a response like this:

Complete server.js file

const express = require('express')
const nodemailer = require("nodemailer");

const app = express()

const sendEmail = async(req,res) => {

    try {
        
    let transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        port: 465,
        secure: true, // true for 465, false for other ports
        auth: {
          user: 'yourgmail@gmail.com', // gmail id
          pass: 'app_password', // generated application password
        },
      });
    let info = await transporter.sendMail({
        from: '"CodewithSudeep 👻" <codewithsudeep@gmail.com>', // sender address
        to: "test@gmail.com", // list of receivers
        subject: "Hello ✔", // Subject line
        text: "Hello world?", // plain text body
        html: "<b>Hello world?</b>", // html body
      });
    
      res.send({
        status: `Message sent:${info.messageId}`,
        info: info
      })
    } catch (error) {
        console.log(error)
    }

}


app.get('/',(req,res)=>res.send('running at port 3000'))
app.get('/sendemail',sendEmail)

app.listen(3000,()=>console.log("started at port 3000"))

Complete source code repo: https://github.com/SudeepMi/Node-Mail

Other Web development articles: Javascript window properties and methods

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: