我正在创建一个处理电子邮件的模块,我调用了
邮件服务
在我的Nest应用程序中。
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,
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
,并且smtp配置已正确获取。
当我尝试使用
mail.service.ts
在我的应用程序中,并且我调用函数
发送电子邮件
,我得到这个错误:
显然Nest解决了
mailerService
依赖性,因为这方面没有错误,但它仍然是未定义的。谢谢你的真知灼见。