NestJS 服务中未定义 MailerService

问题描述 投票:0回答:1

我正在创建一个处理电子邮件的模块,我在 Nest 应用程序中将其称为 MailService

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" <[email protected]>', // 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" <[email protected]>',
  },
  template: {
    dir: process.cwd() + '/src/modules/mail/templates/',
    adapter: new HandlebarsAdapter(),
    options: {
      strict: true,
    },
  },
}));

我正在 app.module.ts 中导入 MailModule,并且 smtp 配置已正确获取。

当我尝试在应用程序中使用mail.service.ts并且调用函数sendEmail时,我收到此错误: enter image description here

显然 Nest 解决了 mailerService 依赖关系,因为没有任何错误,但它仍然是未定义的。感谢您的见解。

nestjs nodemailer
1个回答
0
投票

您缺少

@
@Injectable()
,这使它成为一个装饰器,而不仅仅是一个函数

© www.soinside.com 2019 - 2024. All rights reserved.