Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use handlebars with nodemailer to send email?

I am using nodemailer to send emails using the following nodemailer-express-handlebars plugin. I used this {dead blog post} as reference

The code is compiling the welcome template but is not using the layout

My code is as below:

var nodemailer = require('nodemailer');
var mg = require('nodemailer-mailgun-transport');
var hbs = require('nodemailer-express-handlebars');

var config = {auth: {api_key: "key-xxx",domain: "mydomain.com}}
var nodemailerTransport = nodemailer.createTransport(mg(config));

var options = {
    viewEngine: {
        extname: '.handlebars',
        layoutsDir: 'views/email/',
        defaultLayout : 'layout',
    },
    viewPath: 'views/email/'
}

nodemailerTransport.use('compile', hbs(options));

nodemailerTransport.sendMail({
        from: '[email protected]',
        to: '[email protected]',
        subject: 'Welcome to the XXX',
        template: 'welcome'
    }, function (err, results) {
        if (err) console.log('Error: ' + err);
        else console.log('Response: ' + results);
});

My layout.handlebars has the following code

<html>
<body>
{{> _header }}
    {{{body}}}
{{> _footer }}
</body>
</html>
like image 865
Masade Avatar asked Jul 25 '17 11:07

Masade


People also ask

What is Nodemailer Express handlebars?

Nodemailer-express-handlebars is a useful plugin for Nodemailer that allows you to use Handlebars templates in your HTML emails | Link. The documentation on that page does not provide a full usage example and is really short on details.

How do I use handlebars in node js?

HandleBars can be used to render web pages to the client side from data on the server-side. To use handlebars in express, we need to store HTML code into a . hbs extension in the 'views' folder in the source directory as hbs looks for the pages in the views folder. Now, we need to change the default view engine.


1 Answers

You are missing a partialsDir option.

I have tested with the following options and it works fine :

 var options = {
   extName:'.hbs', /* or '.handlebars' */
   viewPath:__dirname+'/views/email/',
   layoutsDir:__dirname+'/view/email',
   defaultLayout:'template',
   partialsDir:__dirname+'/views/email/partials/'
 }

To use my directory structure :

  1. Where the script is place a folder : views
  2. Inside of it place a folder called email (here store 'template.hbs')
  3. Inside of the email folder create a partials folder (here as example store 'header.hbs')
like image 58
EMX Avatar answered Oct 18 '22 15:10

EMX