How to Add NodeMailer to Your NestJS Backend Server with a Gmail Account

Rihem Larbi
Stackademic
Published in
2 min readApr 30, 2024

--

In this guide, I will show you how to integrate NodeMailer into your NestJS backend application and send emails using your Gmail account.

Enable App Password using GMAIL

Before you can use your Gmail account with NestJS applications, you need to enable app passwords. Here’s how:

1- Log in to your Google account.

2- Go to My Account > Security.

3- Under the “How you sign in to Google” section, you should activate “2 step verification”

4- Then you should “https://accounts.google.com/app/apppaswords”. You might need to sign in again to confirm it’s you.

5- Give your app password a name, e.g. “appexample”.

6- Click on Generate.

7- You’ll now see a 16-character password. Copy this password and use it in your NestJs script instead of your actual Gmail password.

Implement NodeMailer in NestJS backend server

NodeMailer is a module that facilitates easy email sending with NestJS or Node.js. This module provides a straightforward API to interact with SMTP servers, enabling sending plain text emails, HTML emails, attachments, and more.

1- Install NodeMailer in your NestJS backend server using this command:

npm install nodemailer

2- Implement a sendEmail function to send emails:

import * as nodemailer from 'nodemailer';
async sendEmail() {
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'test@gmail.com',
pass: 'your app password',
},
});

let info = await transporter.sendMail({
from: 'test@gmail.com',
to: 'test2@gmail.com',
subject: 'hello world!',
text: 'hello world!',
});

console.log('Message sent: %s', info.accepted);
}

Now you can run your application, and you should receive an email from your backend as shown below.

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--

A full-stack enthusiast and dedicated development engineer, Keen to broaden understanding of development techniques and engage in collaborative efforts.