email-sender-sdn
Version:
Reusable email sender with support for HTML, plain text, templates, and attachments.
51 lines (43 loc) • 1.46 kB
JavaScript
const nodemailer = require('nodemailer');
const config = require('./config');
const fs = require('fs');
const path = require('path');
const Handlebars = require('handlebars');
const transporter = nodemailer.createTransport({
host: config.host,
port: config.port,
secure: config.secure,
auth: config.auth,
});
function renderTemplate(templateName, data) {
const filePath = path.join(__dirname, 'templates', `${templateName}.hbs`);
const source = fs.readFileSync(filePath, 'utf8');
const compiledTemplate = Handlebars.compile(source);
return compiledTemplate(data);
}
/**
* Send an email with dynamic options
* @param {Object} options
* @param {string} options.to - Recipient
* @param {string} options.subject - Subject
* @param {string} [options.text] - Plain text content
* @param {string} [options.html] - Raw HTML content
* @param {Object} [options.template] - { name: 'templateName', data: { … } }
* @param {Array} [options.attachments] - Attachments array
*/
async function sendEmail({ to, subject, text, html, template, attachments = [] }) {
let finalHtml = html;
if (!html && template?.name) {
finalHtml = renderTemplate(template.name, template.data || {});
}
const mailOptions = {
from: config.from,
to,
subject,
text,
html: finalHtml,
attachments,
};
return transporter.sendMail(mailOptions);
}
module.exports = { sendEmail };