ticket-booking-be/src/node-mailer/mailer.service.ts
2025-03-20 17:52:53 +05:30

58 lines
1.7 KiB
TypeScript

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<string>('MAIL_HOST'),
auth: {
user: this.configService.get<string>('MAIL_USER'),
pass: this.configService.get<string>('MAIL_PASS'),
},
secure: true,
port: this.configService.get<number>('MAIL_PORT'),
});
return transporter;
}
template(html: string, replacements: Record<string, string>) {
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<string>('APP_NAME');
const fromAddress =
from?.address ?? this.configService.get<string>('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);
}
}
}