I am trying to send email in Nestjs framework using @nestjs-modules/mailer nodemailer. Email are working fine with normal text but when is setup to use EJS template for email body its stoped working. I use [https://nest-modules.github.io/mailer/docs/mailer.html][1] for reference below are my source code. App.module.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 { }
Email Service
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: '[email protected]',
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');
}
}
}
Notification.ejs
<p>Welcome , your activation code is <%= code %></p>
I am getting code is not defined error.
There are two approaches to solving this problem:
locals
objectContext properties are passed to your compiled EJS templates in an object called locals. If you update your template variables to use the locals
prefix, those values can be resolved and substituted:
<p>Welcome, your activation code is <%= locals.code %></p>
EJS strict mode is creating the need to use the locals
object in your templates instead of the plain variable names from your context. You could instead just disable that setting in your NestJS MailerModule instantiation:
options: {
strict: false,
},
in main.ts try "app.setViewEngine('ejs');"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With