NestJS

Sending Emails

Configuring and sending emails using the @nestjs-modules/mailer package with Nodemailer and Handlebars templates.

Mail Module Configuration: Setting up SMTP transport and Handlebars adapter for email templates.
📄mail.module.ts
typescript
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
import { MailService } from './mail.service';
import { join } from 'path';

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        host: 'smtp.example.com',
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
          user: 'user@example.com',
          pass: 'super-secret-password',
        },
      },
      defaults: {
        from: '"No Reply" <noreply@example.com>',
      },
      template: {
        dir: join(__dirname, 'templates'), // path to handlebars templates
        adapter: new HandlebarsAdapter(), 
        options: {
          strict: true,
        },
      },
    }),
  ],
  providers: [MailService],
  exports: [MailService],
})
export class MailModule {}
Mail Service: A service class to send templated emails.
📄mail.service.ts
typescript
import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';

@Injectable()
export class MailService {
  constructor(private mailerService: MailerService) {}

  async sendUserWelcome(user: any, token: string) {
    const url = `https://example.com/auth/confirm?token=${token}`;

    await this.mailerService.sendMail({
      to: user.email,
      // from: '"Support Team" <support@example.com>', // override default from
      subject: 'Welcome to Our Service! Confirm your Email',
      template: './welcome', // `.hbs` extension is appended automatically
      context: { 
        // Data to be sent to template engine
        name: user.name,
        url,
      },
    });
    
    console.log(`Welcome email sent to ${user.email}`);
  }
}