Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs email failed to send with ejs template dynamic data

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.

like image 947
nilesh suryavanshi Avatar asked Dec 31 '22 01:12

nilesh suryavanshi


2 Answers

There are two approaches to solving this problem:

  1. Use the EJS locals object

Context 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>
  1. Disable strict mode

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,
},
like image 122
JM NZ Avatar answered Jan 13 '23 22:01

JM NZ


in main.ts try "app.setViewEngine('ejs');"

like image 25
Kallol Medhi Avatar answered Jan 13 '23 21:01

Kallol Medhi