Handlebars as an email template

Ollie picture Ollie · Nov 6, 2017 · Viewed 7.5k times · Source

I've just inherited a codebase, and it's using handlebars as an email templating language.

I've googled around to try and get more information, but I can't find anyone else doing this.

I was just wondering if anyone could supply me some documentation or search terms to look for. I had no idea you could even use handlebars like this!

Thanks,

Ollie


Email sender

// Send new account email 
function sendNewAccountEmail(expert) {   
  ...
  return handlebars.render('views/emails/newAccountEmail.handlebars', {
    name: `${expert.firstName} ${expert.lastName}`,
    layout: false,
    expert,
    url: `${LIVE_URL}/expert/reset/${expert.resetPasswordToken}`,   
}).then(email => new Promise((resolve, reject) => {
      sendmail({
        from: SEND_EMAIL,
        to: recipient,
        subject: '',
        text: email,
      }, (err, reply) => {
        ...
      });
    })); }

newAccountEmail.handlebars

Hi {{name}},

You now have access to RARA Survey tool!
You can now access your dashboard and assigned campaigns by going to the following link and creating a password:

Login URL: {{url}}

Thanks!

Influencer Team

Answer

Marcio.Torquato picture Marcio.Torquato · Nov 6, 2017

To do the email sent based on files .hbs as templates, it's necessary the instalation using NPM of packages:

  1. nodemailer
  2. nodemailer-express-handlebars

It will be to set the host informations:

    var transport = nodemailer.createTransport({
        host: 'YOUR HOST',
        port: 'YOUR PORT',
        auth: {
            user: 'YOUR USER',
            pass: 'YOUR PASSWORD'
        },
        tls: {
            rejectUnauthorized: false
        }
    });

Now, we need configure the transport to it be able to use the template:

    transport.use('compile', hbs({    
        viewPath: 'YOUR PATH where the files are, for example /app/view/email',
        extName: '.hbs'
    }));



    exports.sendEmail = function (from, to, subject, callback) {

        var email = {
            from: 'YOUR FROM FOR EXAMPLE [email protected]',
            to: 'RECIPIENT',
            subject: 'SUBJECT',
            template: 'TEMPLATE NAME, DO NOT NEED TO PLACE  .HBS',
            context: {
                name: 'YOUR NAME',
                url: 'YOUR URL'
            }
        };

        transport.sendMail(email, function (err) {
            if (err) {
                return callback({ 'status': 'error', 'erro': err });
            }
            else {
                return callback({ 'status': 'success' });
            }
        })
    };