Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include an html email template in a node js application

Tags:

node.js

I have an html template that we use to send to new website registrations. It is a simple html file that I would like to load into a variable so that I can replace certain parts before sending out using nodemailer (eg [FIRST_NAME]). I am trying to avoid having to paste a large chunk of html into my exports function. Any ideas on how I could go about doing that?

For a clearer idea, what I need to know is how to actually do this:

var first_name = 'Bob';  
var html = loadfile('abc.html').replace('[FIRST_NAME]', first_name);
like image 538
MindWire Avatar asked Sep 28 '14 12:09

MindWire


People also ask

How do I use an email template in node?

In the root of your project, create a folder called views . Inside, create a file called email. handlebars , which will hold the HTML code and styles for our emails. Handlebars is a templating language, so we can add variables to our HTML, then substitute the variables for the values we want in our final email.

How do you load HTML in Node JS?

_compile( code, path ); // 3 }; In the beginning, you fetch the content of the HTML file (1). Then you insert it into the code of a very simple JavaScript module that wraps HTML into a Hogan template (2). The code prepared in this way is then compiled using module.

Can you send emails with Node JS?

Whether you're building the next Gmail, cutting-edge email marketing software, or just want to program notifications into your Node. js app, it's easy to send emails using readily-made tools and services. Node. js is one of the most popular (if not the most popular) server-side runtime environment for web applications.


1 Answers

Here's an example of how to do it using ejs, but you can use any templating engine:

var nodemailer = require("nodemailer");
var ejs = require('ejs');

var transport = nodemailer.createTransport("SMTP", {
        service: <your mail service>,
        auth: {
            user: <user>,
            pass: <password>
        }
});

function sendMail(cb) {
    var user = {firstName : 'John', lastName: 'Doe'};

    var subject = ejs.render('Hello <%= firstName %>', user);
    var text = ejs.render('Hello, <%= firstName %> <%= lastName %>!', user);


    var options = {
        from: <from>,
        replyTo: <replyto>,
        to: <to>,
        subject: subject,
        text: text
    };

    transport.sendMail(options, cb);

}

To load the template file just us the fs module. Here's how to do it synchronously when the file is encoded in utf-8:

var fs = require('fs');

var template = fs.readFileSync('abc.html',{encoding:'utf-8'});
like image 170
soulcheck Avatar answered Sep 22 '22 02:09

soulcheck