Twigjs in Node/Express returns raw HTML and not populated HTML in email

158 Views Asked by At

In my NodeJS app, using Express and TwigJS, and node-mailjet for the email SMTP relay, I have the following logic that renders a template and passes that into an email to be sent:

import config from "../../middleware.config";
const Twig = require('twig');       // Render function

interface emailParameters {
    receipient:string,
}

/**
 *
 * @param {object} data
 * @returns {Promise<any>}
 */
export const returnTemplate = (data:object):Promise<any> => {
    return new Promise((resolve)=>{
        Twig.renderFile('./views/Email/test.twig', data, (err, html) => {
                resolve(html);
        });
    })
};

/**
 *
 * @param {emailParameters} options
 * @param {object} emailData
 */
export const emailLongPositions = (options:emailParameters,emailData:object) => {
    returnTemplate(emailData).then((res)=>{
        const Mailjet = require('node-mailjet').connect(config.smtp.key, config.smtp.password);
        const sendEmail = Mailjet.post('send');

        const emailData = {
            'FromEmail': '[email protected]',
            'FromName': 'My Name',
            'Subject': 'Subject of Email v2',
            'Text-part': res,
            'Recipients': [{'Email': options.receipient}]
        };

        sendEmail
            .request(emailData)
            .then((res)=>{
                console.log('success then '+res)
            })
            .catch((res)=>{
                console.log('failed catch '+res)
            });
    });
};

The email is received, but the email renders raw HTML of my Twig template, but not the populated HTML. It's as if this is being returned as a raw string but not a populated template. What am I missing to send an email with populated HTML?

0

There are 0 best solutions below