import 'dotenv/config'; import nodemailer from 'nodemailer'; import logger from './logger.js'; const FROM_EMAIL = process.env.MAIL_FROM || 'smtp@korrith.com'; const REPLY_TO_EMAIL = process.env.MAIL_REPLY_TO || 'noreply@korrith.com'; const smtpPort = parseInt(process.env.SMTP_PORT, 10) || 587; // Initialize nodemailer transporter with SMTP credentials const transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST, port: smtpPort, secure: smtpPort === 465, // SSL on port 465, STARTTLS otherwise (e.g. 587) auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASSWORD, }, }); /** * Send email using nodemailer with SMTP * @param {string|string[]} to - Recipient email address(es) * @param {string} subject - Email subject * @param {string} htmlBody - HTML email body * @returns {Promise} - Mail service response * @throws {Error} - If email sending fails */ async function sendEmail(to, subject, htmlBody) { const recipients = Array.isArray(to) ? to : [to]; logger.info('Attempting to send email via SMTP', { recipients: recipients.join(', '), subject, from: FROM_EMAIL, timestamp: new Date().toISOString() }); try { const mailOptions = { from: FROM_EMAIL, to: recipients.join(', '), subject, html: htmlBody, replyTo: REPLY_TO_EMAIL, }; const result = await transporter.sendMail(mailOptions); logger.info('Email sent successfully via SMTP', { recipients: recipients.join(', '), subject, from: FROM_EMAIL, messageId: result.messageId, timestamp: new Date().toISOString() }); return result; } catch (error) { logger.error('Email send failed', { recipients: recipients.join(', '), subject, from: FROM_EMAIL, errorMessage: error.message, timestamp: new Date().toISOString() }); throw new Error(`SMTP email error: ${error.message}`); } } export { sendEmail }; export default sendEmail;