import { Injectable } from '@nestjs/common'; import { MailerService } from '@nestjs-modules/mailer'; import * as Handlebars from 'handlebars'; import { DataSource } from 'typeorm'; import { IcsMeetingService } from 'src/module/ics/service/ics.service'; @Injectable() export class EmailService { constructor( private readonly mailerService: MailerService, private readonly datasource: DataSource, private readonly icsService: IcsMeetingService, ) {} async sendEmail( email: string, subject: string, context?: any, icsPayload?: any, ) { const template = await this.datasource .getRepository('frm_wf_comm_template') .findOne({ where: { code: 'OTP_TEMPLATE' } }); if (!template) return; const compiled = Handlebars.compile(template.rich_text || ''); const htmlContent = compiled(context); const attachments: any[] = []; if (icsPayload) { const icsBase64 = await this.icsService.generateIcs(icsPayload); if (icsBase64) { attachments.push({ filename: 'invite.ics', content: icsBase64, encoding: 'base64', contentType: 'text/calendar; charset="utf-8"; method=REQUEST', }); } } // fire-and-forget // removed await const result = this.mailerService .sendMail({ to: email, subject, html: htmlContent, attachments, }) .then(() => { console.log(`Email sent to ${email}`); return; }) .catch((err) => { console.error(`Failed to send email to ${email}`, err); // Optionally: push to a retry queue, Sentry, DB log, etc. }); console.log(result); // Return immediately (parent doesn’t block) return; } async sendEmailWithDynamicTemplate( email: string, subject: string, templateCode: string, cc?: string[], bcc?: string[], message?: string, context?: any, icsPayload?: any, ) { // retrieve the rich_text from the database table frm_wf_comm_template for the given templateCode const template = await this.datasource .getRepository('frm_wf_comm_template') .findOne({ where: { code: templateCode } }); if (!template) { console.log(`Template with code ${templateCode} not found`); return { success: false, message: `Template with code ${templateCode} not found`, }; } // Compile the template string with Handlebars const templateString = template.rich_text || ''; const compiled = Handlebars.compile(message || templateString); const htmlContent = compiled(context); // Attachments (ICS optional) const attachments: any[] = []; if (icsPayload) { const icsBase64 = await this.icsService.generateIcs(icsPayload); if (icsBase64) { attachments.push({ filename: 'invite.ics', content: icsBase64, encoding: 'base64', contentType: 'text/calendar; charset="utf-8"; method=REQUEST', }); } } const mailOptions: any = { to: email, subject, html: htmlContent, attachments, }; if (cc && cc.length > 0) { mailOptions.cc = cc; } if (bcc && bcc.length > 0) { mailOptions.bcc = bcc; } // Send the email await this.mailerService.sendMail(mailOptions); return { success: true, message: 'Email sent successfully' }; } }