How to use template engines to send text as email in nodejs How to use template engines to send text as email in nodejs express express

How to use template engines to send text as email in nodejs


Well, you can do this a bunch of ways.

ES6 Template Literals

You're only doing string interpolation so you can very easily use a function with ES6 template literals..

function myTemplate(env) {    const template = `Hello ${env.friendName},                  Happy Birthday ${env.friendName}.                  Thank you,                  ${env.Name}`;    return template.replace(/\n/, '<br>');}var mailOptions={        to : req.query.to,        subject : req.query.subject,        text : myTemplate({friendName: "foo", Name: "Bar"});    };

You may want to trim it up a bit, but that'll get you started.

Fancy full featured template engine

Other template languages include Pugjs (previously Jade), Handlebars.js, and _.template. Typically these more professional third party templates compile down to a JavaScript function, and they're called the same way as our function above. All of the above engines have to be set up in their own fashion...

const pug = require('pug');const myTemplate = pug.compileFile('myPugPath.pug');myTemplate({friendName: "foo", Name: "Bar"});

Also, that you're sending email has nothing to do with this question. Just write an HTML string somehow (ex., using ES6 Template literals, or pug) and then send the email with the mime type properly set (text/html), and the body set to the html.

To load template from DB

If you have the template in your database then rather than using pug.compileFile you would simply use pug.compile(resultFromDb.pugTemplate). Check the documentation on pug for more information.