import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import * as nodemailer from 'nodemailer'; import { SendMailerDto } from './mailer.interface'; import Mail from 'nodemailer/lib/mailer'; @Injectable() export class MailerService { constructor( private readonly configService: ConfigService ) {} mailTransport() { const transporter = nodemailer.createTransport({ service: 'gmail', host: this.configService.get('MAIL_HOST'), auth: { user: this.configService.get('MAIL_USER'), pass: this.configService.get('MAIL_PASS'), }, secure: true, port: this.configService.get('MAIL_PORT'), }); return transporter; } template(html: string, replacements: Record) { return html.replace(/%(\w*)%/g, function (m, key) { return replacements.hasOwnProperty(key) ? replacements[key] : ''; }); } async sendMail(dto: SendMailerDto) { const { from, reciepients, subject } = dto; const html = dto.placeholderReplacements ? this.template(dto.html, dto.placeholderReplacements) : dto.html; const transporter = this.mailTransport(); const fromName = from?.name ?? this.configService.get('APP_NAME'); const fromAddress = from?.address ?? this.configService.get('MAIL_USER'); const options: Mail.Options = { from: { name: fromName, address: fromAddress, }, to: reciepients, subject, html: this.template(html, dto.placeholderReplacements || {}), }; try { const result = await transporter.sendMail(options); return result; } catch (er) { console.log(er); } } }