MindWire
MindWire

Reputation: 4089

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

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);

Upvotes: 10

Views: 39686

Answers (2)

Angel M.
Angel M.

Reputation: 2742

Maybe this will be useful for someone, as this question is already answered.

I'm working with jade and it was quite challenging figuring it out, at the end turned out to be very simple :)

(PS: this code is not optimized, is just an example)

Js part with nodemailer:

var nodemailer = require('nodemailer')
var jade = require('jade');
var config = {
  // config for sending emails like username, password, ...
}
var emailFrom = '[email protected]';
var emailTo = '[email protected]';
var templateDir = 'path/to/templates/';
var transporter = nodemailer.createTransport(config);

var username = 'thisUsername'
// rendering html template (same way can be done for subject, text)
var html = jade.renderFile(templateDir+'/html.jade', {username: 'testUsername'});

//build options
var options = {
   from: emailFrom,
    to: emailTo,
    subject: 'subject',
    html: html,
    text:'text'
};

transporter.sendMail(options, function(error, info) {
  if(error) {
    console.log('Message not sent');
    console.log(info);
    return false;
  }
  else{
    console.log('Message sent: ' + info.response);
    console.log(info);
    return true;
  };
});

html.jade

p test email html jade
p
| Username:
| !{username}

Here is the example for using email-templates and nodemailer.

js file:

var path = require('path');
var EmailTemplate = require('email-templates').EmailTemplate;
var transporter = nodemailer.createTransport(config);

var templateDir = path.join(__dirname, '/yourPath/emailTemplates', 'subdir');
var template = new EmailTemplate(templateDir)
var username = 'testUsername';


var transport = nodemailer.createTransport(config)
template.render(locals, function (err, results) {
  if (err) {
    return console.error(err)
  }
  // replace values in html template
    console.log('template render')
    console.log(err);

    // default is results.html in this case
    // read template and replace desired values
    var res1 = results.html.toString();
    var str = res1.replace('__username__', username);
    console.log(str);
    console.log('end template render')

  transport.sendMail({
    from: emailFrom,
    to: emailTo,
    subject: 'subject',
    html: str,
    text: results.text
  }, function (err, responseStatus) {
    if (err) {
      return console.error(err)
    }
    console.log(responseStatus)
  })
})

html.html

test email html
username:

<div>
__username__
</div>

Upvotes: 4

soulcheck
soulcheck

Reputation: 36777

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'});

Upvotes: 21

Related Questions