53 lines
1.7 KiB
JavaScript
53 lines
1.7 KiB
JavaScript
const nodemailer = require('nodemailer');
|
|
const EmailTemplate = require('../models/EmailTemplate');
|
|
|
|
const sendEmail = async ({ templateName, to, variables = {} }) => {
|
|
try {
|
|
const template = await EmailTemplate.findOne({ name: templateName });
|
|
let subject = variables.subject || 'Antigravity Guitars Update';
|
|
let htmlContent = `<p>Thank you for contacting Antigravity Guitars!</p>`;
|
|
|
|
if (template) {
|
|
subject = template.subject;
|
|
htmlContent = template.bodyHtml;
|
|
|
|
// Replace placeholders e.g. {{customerName}} -> variables.customerName
|
|
Object.keys(variables).forEach((key) => {
|
|
const regex = new RegExp(`{{${key}}}`, 'g');
|
|
subject = subject.replace(regex, variables[key] || '');
|
|
htmlContent = htmlContent.replace(regex, variables[key] || '');
|
|
});
|
|
}
|
|
|
|
const transporter = nodemailer.createTransport({
|
|
host: process.env.EMAIL_HOST || 'smtp.mailtrap.io',
|
|
port: process.env.EMAIL_PORT || 2525,
|
|
auth: {
|
|
user: process.env.EMAIL_USER || '',
|
|
pass: process.env.EMAIL_PASS || ''
|
|
}
|
|
});
|
|
|
|
const mailOptions = {
|
|
from: process.env.EMAIL_FROM || '"Antigravity Guitars" <noreply@guitars.com>',
|
|
to,
|
|
subject,
|
|
html: htmlContent
|
|
};
|
|
|
|
if (process.env.NODE_ENV !== 'test' && process.env.EMAIL_USER) {
|
|
await transporter.sendMail(mailOptions);
|
|
console.log(`[Email Sent]: Template "${templateName}" to ${to}`);
|
|
} else {
|
|
console.log(`[Email Logged (Mock)] To: ${to} | Subject: ${subject}`);
|
|
}
|
|
return true;
|
|
} catch (error) {
|
|
console.error(`[Email Sender Exception]: ${error.message}`);
|
|
return false;
|
|
}
|
|
};
|
|
|
|
module.exports = { sendEmail };
|
|
|