43 lines
1.4 KiB
TypeScript
43 lines
1.4 KiB
TypeScript
// mailer.service.ts
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
import { Transporter } from 'nodemailer';
|
|
import * as fs from 'fs';
|
|
import * as path from 'path';
|
|
import * as Handlebars from 'handlebars';
|
|
import { MailTemplateDTO } from 'src/auth/auth.dto';
|
|
|
|
@Injectable()
|
|
export class MailService {
|
|
private templatesCache = new Map<string, Handlebars.TemplateDelegate>();
|
|
|
|
constructor(@Inject('MAIL_TRANSPORTER') private readonly transporter: Transporter) {
|
|
console.log(path.join(process.cwd(), 'public', 'mail-templates', 'a.hbs'));
|
|
|
|
}
|
|
|
|
private loadTemplate(templateName: string): Handlebars.TemplateDelegate {
|
|
if (this.templatesCache.has(templateName)) {
|
|
return this.templatesCache.get(templateName)!;
|
|
}
|
|
|
|
const templatePath = path.join(process.cwd(), 'public', 'mail-templates', `${templateName}.hbs`);
|
|
const source = fs.readFileSync(templatePath, 'utf8');
|
|
const compiled = Handlebars.compile(source);
|
|
this.templatesCache.set(templateName, compiled);
|
|
return compiled;
|
|
}
|
|
|
|
async sendMail(data: MailTemplateDTO) {
|
|
const template = this.loadTemplate(data.templateName);
|
|
const html = template(data.variables);
|
|
|
|
const mailOptions = {
|
|
to: data.to,
|
|
subject: data.subject,
|
|
html,
|
|
};
|
|
|
|
return this.transporter.sendMail(mailOptions);
|
|
}
|
|
}
|