Enhancing Email Delivery in NestJS with Queue Management
Nadeera Sampath
Senior Lead Software Engineer | NestJS | MongoDB | ReactJS | AWS
As developers, we often face the challenge of efficiently handling time-consuming tasks like sending emails in our NestJS applications. Synchronous email sending can slow down the application's responsiveness and affect user experience. To overcome this, NestJS provides an elegant solution with the help of a queue management system. In this tutorial, we will guide you through the process of setting up NestJS Queue to send emails asynchronously, improving the performance and scalability of your application.
Prerequisites:
Before we begin, ensure you have the following prerequisites in place:
Basic knowledge of TypeScript, Node.js, and NestJS.
Node.js and npm (Node Package Manager) installed on your machine.
Setting Up a NestJS Project:
Create a new NestJS project using the NestJS CLI:
bash
$ npx @nestjs/cli new nest-email-app
Installing Required Packages:
Install the required packages for NestJS Queue and email sending:
bash
$ cd nest-email-app $ npm install @nestjs/bull bull nodemailer
Configuring Bull and Email Module:
Open the app.module.ts file and import the necessary modules and decorators:
typescript
import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
Set up the MailerModule configuration in the same file:
typescript
@Module({
imports: [
BullModule.forRoot({
redis: {
host: 'localhost',
port: 6379,
},
}),
MailerModule.forRoot({
transport: {
// Add your email configuration here (e.g., SMTP or other providers)
},
defaults: {
from: '[email protected]',
},
template: {
dir: __dirname + '/templates',
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
],
})
export class AppModule {}
Creating an Email Queue:
Inside the src folder, create a new folder named queues.
Inside the queues folder, create a new file named email.queue.ts:
领英推荐
typescript
import { Process, Processor } from '@nestjs/bull';
import { Job } from 'bull';
import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
@Injectable()
@Processor('email')
export class EmailQueue {
constructor(private readonly mailerService: MailerService) {}
@Process()
async sendEmail(job: Job<{ to: string; subject: string; text: string }>) {
const { data } = job;
const { to, subject, text } = data;
await this.mailerService.sendMail({
to,
subject,
template: 'email', // Name of the email template (create the template in the 'templates' folder)
context: { text },
});
}
}
Creating an Email Template:
Inside the src folder, create a new folder named templates.
Inside the templates folder, create a new file named email.hbs (Handlebars template file):
handlebars
<!DOCTYPE html>
<html>
<head>
<title>{{ subject }}</title>
</head>
<body>
<p>{{ text }}</p>
</body>
</html>
Sending Emails from a Controller:
Create a new file named email.controller.ts inside the src folder:
typescript
import { Body, Controller, Post } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bull';
import { Queue } from 'bull';
@Controller('email')
export class EmailController {
constructor(@InjectQueue('email') private readonly emailQueue: Queue) {}
@Post('/send')
async sendEmail(@Body() data: { to: string; subject: string; text: string }) {
await this.emailQueue.add(data);
return { message: 'Email added to the queue' };
}
}
Setting Up Routes:
Open the app.controller.ts file in the src folder and add the following route for the email controller:
typescript
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { EmailController } from './email/email.controller';
@Controller()
export class AppController {
constructor(private readonly appService: AppService, private readonly emailController: EmailController) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
Testing the Setup:
Start your NestJS application:
bash
$ npm run start
Use an API testing tool like Postman or curl to send a POST request to https://localhost:3000/email/send with the following JSON payload:
json
{
"to": "[email protected]",
"subject": "Test Email",
"text": "This is a test email sent using NestJS Queue with Bull."
}
Conclusion:
Congratulations! You have successfully integrated NestJS Queue with Bull to send emails asynchronously in your NestJS application. By leveraging the power of Bull's queue management system, you can now handle email sending efficiently, improving the performance and responsiveness of your application. As you continue to develop your NestJS application, consider exploring advanced features of NestJS Queue and optimizing your email templates to further enhance the user experience.