Files
MultiTenantSaaS/core/mail/mail.service.ts
2026-03-07 07:38:50 +05:45

46 lines
1.3 KiB
TypeScript

import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import * as nodemailer from "nodemailer";
@Injectable()
export class MailService {
private transporter: nodemailer.Transporter;
private mailServiceAvailable = false;
constructor(private readonly configService: ConfigService) {
const mailId = this.configService.get<string | undefined>("MAIL_ID");
const mailPass = this.configService.get<string | undefined>("MAIL_PASS");
if (!mailId || !mailPass)
throw new Error("Make sure MAIL_ID and MAIL_PASS environment variables are set")
// Use secure in prod
// TODO: A table for failed emails to retry later(actually bullmq)
this.transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // Use true for port 465, false for port 587
auth: {
user: mailId,
pass: mailPass,
},
from: mailId
});
this.mailServiceAvailable = true;
}
sendMail({ to, subject, body }: { to: string, subject: string, body: string }) {
if (!this.mailServiceAvailable)
throw new Error("Mail service not available")
this.transporter.sendMail(
{
to,
subject,
html: body
}
)
}
}