Express/MongoDB backend with JWT auth, RBAC, S3 uploads, notifications, and scheduled jobs.
53 lines
1.4 KiB
JavaScript
53 lines
1.4 KiB
JavaScript
// /utils/senders/emailSender.js
|
|
|
|
const nodemailer = require('nodemailer');
|
|
const config = require('../../config/config');
|
|
const logger = require('../logger');
|
|
|
|
let transporter = null;
|
|
|
|
const getTransporter = () => {
|
|
if (!transporter) {
|
|
transporter = nodemailer.createTransport({
|
|
host: config.SMTP_HOST,
|
|
port: config.SMTP_PORT,
|
|
secure: config.SMTP_PORT === 465,
|
|
auth: config.SMTP_USER ? {
|
|
user: config.SMTP_USER,
|
|
pass: config.SMTP_PASS
|
|
} : undefined
|
|
});
|
|
}
|
|
return transporter;
|
|
};
|
|
|
|
const sendEmail = async ({ to, subject, body, html }) => {
|
|
try {
|
|
if (!to) throw new Error('Recipient email is required');
|
|
|
|
const mailOptions = {
|
|
from: config.EMAIL_FROM,
|
|
to,
|
|
subject,
|
|
text: body,
|
|
html: html || `<p>${body}</p>`
|
|
};
|
|
|
|
if (config.NODE_ENV === 'test' || !config.SMTP_USER) {
|
|
logger.info(`[EmailSender MOCK] To: ${to} | Subject: ${subject} | Body: ${body}`);
|
|
return { success: true, messageId: `mock_${Date.now()}` };
|
|
}
|
|
|
|
const info = await getTransporter().sendMail(mailOptions);
|
|
logger.info(`[EmailSender] Message sent: ${info.messageId} to ${to}`);
|
|
return { success: true, messageId: info.messageId };
|
|
} catch (error) {
|
|
logger.error(`[EmailSender ERROR] Failed to send email to ${to}: ${error.message}`);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
sendEmail
|
|
};
|