Skip to content

How to use a Google Gmail account to send nodemailer emails

What's the problem?

When using nodemailer to send emails on a Node application, the setup needed to use a Gmail account is different, we need to create an application specific password on our Gmail account and pass that information to the transport we are using on nodemailer

Getting started

This code below shows the basic configuration needed to send an email using nodemailer and Gmail, first we need to create a transport, as we can see the service used on the transport is "gmail", but we cannot use our password directly, or we will get an error we need to use a application specific password, and then we can use that transport to send the message with specific options we can pass on the parameters

const nodemailer = require("nodemailer");

const testTransport = nodemailer.createTransport({
    service: "gmail", // Service is gmail
    port: 465, // Port 465 is used for implicit TLS
    secure: true, //  If true the connection will use TLS when connecting to server.
    auth: {
        user: "email@gmail.com", // Our gmail email
        pass: "cekuljujeprfixat", // Application specific password
    },
});

// Mail option used to send message
let mailOptions = {
    from: from,
    to: to,
    subject: subject,
    html: html,
};

// Use transport above to send email to specified options
testTransport.sendMail(mailOptions, (error) => {
    if (error) {
        console.log(error);
    }
});

Getting our application specific password

Important before creating an application specific password you need to enable two-factor authentication on your account for security reasons

First you need to log in into you gmail account or the one you are planning to use next go to the following url https://myaccount.google.com/apppasswords this will redirect you to the app passwords manager here you can create a new application specific password or manage the ones you already have, add your new app by filling the app name and clicking create as shown in the picture below

Application specific password create app

Once you create your new app a modal will show the password you can use for this specific application, this is the one we are going to use on our nodemailer transport just remove the white spaces, for example in this case my password would be cekuljujeprfixat

Application specific password create app

Once you use this new password you would be able to use nodemailer to send emails using your Gmail account safely