Setting Up Email Transfer With NestJS Using NodeMailer
What is NodeMailer?
A Node.js module, NodeMailer allows the user to send emails from the server with ease. Nodemailer enables users to send emails to the users with the NestJS application like “Confirmation email”, “Forgot Password email”, “Contact us an email” and “Notification types email”. Whether communicating with the users or notify them when something goes wrong, all the activities can be carried out through email.
How to Create Email Templates and send it with NodeMailer from the NestJS application?
In this blog, we will explore ways to get familiar with ways to use NodeMailer to send emails in the NestJS application.
Steps to follow:
Step 1: Install Dependencies
Install NestJS mailer package and its dependencies like NodeMailer in the NestJS application by using the below-specified command:
$ npm install — save @nestjs-modules/mailer NodeMailer
Step 2: Select Template
Choose one of the supported template engines (handlebars, pug, and ejs) to create email templates in the NestJS application.
Use the Handlebars template engine to install the Handlebars package and run the below command:
$ npm install — save handlebars
$ npm install — save @nestjs-modules/mailer NodeMailer handlebars
Step 3: Create Mail Module
The user has to first create a MailModule and MailService using NestJS CLI server mail logic.
To create MailModule, run the command stated below:
$ nest g module mail
This will create a MailModule in the NestJS Application.
To create MailerService, run the below-mentioned command:
$ nest g service mail
This will create a MailService in the NestJS Application.
Step 4: Import Mailer Module
Import the MailerModule into the MailModule and configure the mail server transport via smtp.
Provide a default email address to consistently use the same email throughout the application.
The user can change the default setting whenever necessary.
Configure the templates folder and adapter- in this case, HandlebarsAdapter.
After performing the above configurations, the “mail.module.ts” file will look like the one mentioned below:
Step 5: Create Email Template
For creating an email template, the user has to create a template folder to store the template files, as mentioned below.
$ mkdir src/mail/templates
Create an email template using Handlebars.
Create the first email template as “confirmation.hbs” in the src/mail/templates folder.
Use email template file with extension “.hbs” as Handlebars is being used.
The first email template will look like the one mentioned below:
Click Here to read the full blog.