MailerService undefined in NestJS service

Advertisements

I am creating a module that handles emails and that i called MailService in my Nest app.

mail.module.ts

import { Module } from '@nestjs/common';
import { MailService } from './mail.service';
import { MailerModule } from '@nestjs-modules/mailer';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    MailerModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        ...configService.get('smtp'),
      }),
      inject: [ConfigService],
    }),
  ],
  providers: [MailService],
  exports: [MailService],
})
export class MailModule {}

mail.service.ts

import { MailerService } from '@nestjs-modules/mailer';
import { Injectable } from '@nestjs/common';
import { User } from 'src/modules/user/entities/user.entity';

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

  async sendResetPasswordEmail(user: User, token: string) {
    const link = `https://example.com/reset-password/?token=${token}`;

    await this.mailerService.sendMail({
      to: user.email,
      // from: '"Support Team" <support@example.com>', // override default from
      subject: 'Math&Maroc Competition | Reset your password',
      template: './reset-password',
      context: {
        firstName: user.firstName,
        link,
      },
    });
  }
}

smtp.config.ts

import { registerAs } from '@nestjs/config';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';

export default registerAs('smtp', () => ({
  transport: {
    service: 'Gmail',
    host: process.env.SMTP_HOST,
    port: 465,
    secure: true,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASSWORD,
    },
  },
  defaults: {
    from: '"No Reply" <noreply@example.com>',
  },
  template: {
    dir: process.cwd() + '/src/modules/mail/templates/',
    adapter: new HandlebarsAdapter(),
    options: {
      strict: true,
    },
  },
}));

I am importing MailModule in app.module.ts, and the smtp config is fetched correctly.

When i try to use mail.service.ts in my application and that i call the function sendEmail, i get this error:

Apparently Nest resolves the mailerService dependency since there is no errors about that, but it is still undefined. Thanks for you insights.

>Solution :

You’re missing the @ for @Injectable() that makes it a decorator, not just a function

Leave a ReplyCancel reply