mirror of
https://github.com/rgrgogu/new_starr.git
synced 2026-09-27 00:12:54 +08:00
69 lines
2.2 KiB
JavaScript
69 lines
2.2 KiB
JavaScript
/***********************************************************************************************************************************************************************
|
|
* File Name: email.service.js
|
|
* Type of Program: Service
|
|
* Description: Nodemailer-based email service.
|
|
* Subject + body per type are hardcoded in data/email_body.data.js —
|
|
* there is no admin UI or DB table. To add or change an email,
|
|
* edit that file directly and redeploy.
|
|
* Author: rgrgogu, Kenneth Obsequio (@lash0000)
|
|
* Date Created: Oct. 6, 2025
|
|
***********************************************************************************************************************************************************************
|
|
* HOW TO USE:
|
|
* const emailService = require('../services/email.service');
|
|
* await emailService.sendEmail({ to: user.email, type: 'OTP', data: { otp } });
|
|
***********************************************************************************************************************************************************************/
|
|
const nodemailer = require('nodemailer');
|
|
const { emailTemplates } = require('../data/email_body.data');
|
|
|
|
const port = Number(process.env.SMTP_PORT);
|
|
|
|
const transporter = nodemailer.createTransport({
|
|
host: process.env.SMTP_HOST,
|
|
port,
|
|
secure: port === 465,
|
|
requireTLS: port === 587,
|
|
auth: {
|
|
user: process.env.SMTP_USER,
|
|
pass: process.env.SMTP_PASS,
|
|
},
|
|
tls: {
|
|
rejectUnauthorized: false,
|
|
},
|
|
});
|
|
|
|
const sendEmail = async ({ to, type, data = {} }) => {
|
|
try {
|
|
const templateFn = emailTemplates[type];
|
|
|
|
if (!templateFn) {
|
|
throw new Error(`Email template "${type}" not found`);
|
|
}
|
|
|
|
const { subject, html } = templateFn(data);
|
|
|
|
return await new Promise((resolve, reject) => {
|
|
transporter.sendMail(
|
|
{
|
|
from: {
|
|
name: "STARR System",
|
|
address: process.env.EMAIL_FROM,
|
|
},
|
|
to,
|
|
subject,
|
|
html,
|
|
},
|
|
(err, info) => {
|
|
if (err) return reject(err);
|
|
resolve(info);
|
|
}
|
|
);
|
|
});
|
|
} catch (err) {
|
|
throw new Error(err.message);
|
|
}
|
|
};
|
|
|
|
const ping = () => transporter.verify();
|
|
|
|
module.exports = { sendEmail, ping };
|