email template fo rreplacements

This commit is contained in:
Dobromir Popov
2024-04-05 23:44:27 +03:00
parent bac4f4c7d5
commit fa5d3f4f99
4 changed files with 207 additions and 72 deletions

View File

@ -39,6 +39,53 @@ exports.SendEmail = async function (to, subject, text, html) {
};
};
exports.SendEmailHandlebars = async function (to, templateName, model) {
// Ensure the sender and mailtrapTestClient are correctly defined or imported
// Load and compile the main template
const mainTemplateSource = fs.readFileSync(path.join(__dirname, 'src', 'templates', 'emails', 'main.hbs'), 'utf8');
const mainTemplate = Handlebars.compile(mainTemplateSource);
// Dynamically load and compile the specified template
const templateSource = fs.readFileSync(path.join(__dirname, 'src', 'templates', 'emails', `${templateName}.hbs`), 'utf8');
// Extract subject and optional text version from the template source
const subjectMatch = templateSource.match(/{{!-- Subject: (.*) --}}/);
const textMatch = templateSource.match(/{{!-- Text: ([\s\S]*?) --}}/);
const subject = subjectMatch ? subjectMatch[1].trim() : 'Default Subject';
const textVersion = textMatch ? textMatch[1].trim() : null;
// Remove the subject and text annotations from the template source
const cleanTemplateSource = templateSource.replace(/{{!-- Subject: .* --}}/, '').replace(/{{!-- Text: [\s\S]*? --}}/, '');
// Compile the cleaned template
const template = Handlebars.compile(cleanTemplateSource);
// Render the specified template with the provided model
const templateHtml = template(model);
// Render the main template, inserting the specific template HTML
const html = mainTemplate({ body: templateHtml });
// Generate a plain text version if not explicitly provided
const text = textVersion || html.replace(/<[^>]*>?/gm, ''); // Simple regex to strip HTML tags. Might need refinement.
const message = {
from: sender, // Ensure 'sender' is defined
to,
subject,
text,
html,
};
// Assuming mailtrapTestClient is correctly set up to send emails
await mailtrapTestClient
.send(message)
.then(console.log)
.catch(console.error);
};
exports.SendEmail_Test = async function (to, subject, text, html) {
const message = {
from: sender,