nil*_*shi 4 ejs nodemailer nestjs
我正在尝试使用 @nestjs-modules/mailer nodemailer 在 Nestjs 框架中发送电子邮件。电子邮件与普通文本一起工作正常,但是当设置为使用 EJS 模板作为电子邮件正文时,它停止工作。我使用 [ https://nest-modules.github.io/mailer/docs/mailer.html][1]作为参考,下面是我的源代码。应用模块.ts
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { EjsAdapter } from '@nestjs-modules/mailer/dist/adapters/ejs.adapter';
import { join } from 'path';
const path = join(__dirname, '../../../apps/api/src/app/template');
@Module({
imports: [MailerModule.forRoot({
transport: environment.SmtpDetails,
defaults: {
from: environment.SmtpEmail,
},
template: {
dir: path,
adapter: new EjsAdapter(),
options: {
strict: true,
},
},
})
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
电子邮件服务
import { Injectable, BadGatewayException } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
@Injectable()
export class EmailService {
constructor(private readonly mailerService: MailerService) { }
async sendNotificationEmail(emailTo: string, data: object) {
console.log(__dirname);
try {
const emailData = await this.mailerService.sendMail({
to: emailTo,
from: 'user@test.com',
subject: 'Testing Nest Mailermodule with template',
template: 'notification',
context: { // Data to be sent to template engine.
"code": 'cf1a3f828287',
"username": 'john doe',
},
});
if (emailData) return emailData;
} catch (e) {
console.log(e);
throw new BadGatewayException('Email send failed');
}
}
}
Run Code Online (Sandbox Code Playgroud)
通知.ejs
<p>Welcome , your activation code is <%= code %></p>
Run Code Online (Sandbox Code Playgroud)
我收到代码未定义错误。
有两种方法可以解决这个问题:
locals对象上下文属性被传递到名为 locals 的对象中的已编译 EJS 模板。如果您更新模板变量以使用locals前缀,则可以解析和替换这些值:
<p>Welcome, your activation code is <%= locals.code %></p>
Run Code Online (Sandbox Code Playgroud)
EJS 严格模式需要locals在模板中使用对象而不是上下文中的普通变量名。您可以改为在 NestJS MailerModule 实例化中禁用该设置:
options: {
strict: false,
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2354 次 |
| 最近记录: |