// /utils/senders/emailSender.js const nodemailer = require('nodemailer'); const config = require('../../config/config'); const logger = require('../logger'); const { isMessagingChannelEnabled } = require('../../components/settings/messagingFlags'); 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'); if (!(await isMessagingChannelEnabled('email'))) { logger.info(`[EmailSender] Skipped (channel disabled) → ${to}`); return { skipped: true, reason: 'channel_disabled' }; } const mailOptions = { from: config.EMAIL_FROM, to, subject, text: body, html: html || `
${body}
` }; 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 };