57

I want to send email with nodemailer using html template. In that template I need to inject some dynamically some variables and I really can't do that. My code:

var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');

smtpTransport = nodemailer.createTransport(smtpTransport({
    host: mailConfig.host,
    secure: mailConfig.secure,
    port: mailConfig.port,
    auth: {
        user: mailConfig.auth.user,
        pass: mailConfig.auth.pass
    }
}));
var mailOptions = {
    from: 'my@email.com',
    to : 'some@email.com',
    subject : 'test subject',
    html : { path: 'app/public/pages/emailWithPDF.html' }
};
smtpTransport.sendMail(mailOptions, function (error, response) {
    if (error) {
        console.log(error);
        callback(error);
    }
});

Let's say I want in emailWithPDF.html something like this:

Hello {{username}}!

I've found some examples, where was smth like this:

...
html: '<p>Hello {{username}}</p>'
...

but I want it in separate html file. Is it possible?

Wacław Łabuda
  • 575
  • 1
  • 4
  • 5

11 Answers11

98

What you can do is read the HTML file using fs module in node and then replace the elements that you want changed in the html string using handlebars

var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var handlebars = require('handlebars');
var fs = require('fs');

var readHTMLFile = function(path, callback) {
    fs.readFile(path, {encoding: 'utf-8'}, function (err, html) {
        if (err) {
           callback(err);                 
        }
        else {
            callback(null, html);
        }
    });
};

smtpTransport = nodemailer.createTransport(smtpTransport({
    host: mailConfig.host,
    secure: mailConfig.secure,
    port: mailConfig.port,
    auth: {
        user: mailConfig.auth.user,
        pass: mailConfig.auth.pass
    }
}));

readHTMLFile(__dirname + 'app/public/pages/emailWithPDF.html', function(err, html) {
    if (err) {
       console.log('error reading file', err);
       return;
    }
    var template = handlebars.compile(html);
    var replacements = {
         username: "John Doe"
    };
    var htmlToSend = template(replacements);
    var mailOptions = {
        from: 'my@email.com',
        to : 'some@email.com',
        subject : 'test subject',
        html : htmlToSend
     };
    smtpTransport.sendMail(mailOptions, function (error, response) {
        if (error) {
            console.log(error);
        }
    });
});
Ananth Pai
  • 1,939
  • 14
  • 15
23

I use it in all my projects. more clean and up to date and understandable. callback hell doesn't exist. sendMail.ts The html file reads with handlebar, puts the relevant variables into the contents, and sends.

import * as nodemailer from 'nodemailer';
import * as handlebars from 'handlebars';
import * as fs from 'fs';
import * as path from 'path';

export async function sendEmail(email: string, subject: string, url: string) {
  const __dirname = path.resolve();
  const filePath = path.join(__dirname, '../emails/password-reset.html');
  const source = fs.readFileSync(filePath, 'utf-8').toString();
  const template = handlebars.compile(source);
  const replacements = {
    username: "Umut YEREBAKMAZ"
  };
  const htmlToSend = template(replacements);
  const transporter = nodemailer.createTransport({
    host: "smtp.mailtrap.io",
    port: 2525, // 587
    secure: false,
    auth: {
      user: "fg7f6g7g67",
      pass: "asds7ds7d6"
    }
  });
  const mailOptions = {
    from: '"noreply@yourdomain.com" <noreply@yourdomain.com>',
    to: email,
    subject: subject,
    text: url,
    html: htmlToSend
  };
  const info = await transporter.sendMail(mailOptions);
  console.log("Message sent: %s", info.messageId);
  console.log("Preview URL: %s", "https://mailtrap.io/inboxes/test/messages/");

}
umutyerebakmaz
  • 887
  • 8
  • 18
  • 2
    Can you use local images in the HTML template this way? Tried using one but it wouldn't load. Using URLs does work of course. – Johnny Navarro Mar 15 '20 at 03:57
  • You can use it if you give absolute paths of the files on the server. for example: https://yourdomain.com/images/logo.png you can use it like traditional html. They explained a different way in the document on the offical site. https://community.nodemailer.com/using-embedded-images/ I still find my way easier and more flexible. I prepare my html template first and then I include it in the work. – umutyerebakmaz Apr 21 '20 at 16:22
  • I did the same. But my CSS is not getting linked with html. What might be the reason ? – rickster Dec 09 '21 at 14:16
  • If you are going to use css for emails, make sure to use inline style. – umutyerebakmaz Dec 10 '21 at 09:05
  • 1
    **2023** and this one is working during my testing. Though, I need to add `const __dirname = path.resolve();` to fix the `__dirname not define` issue in my case. Clean codes. Thank you! –  Jan 03 '23 at 19:50
11

String replace isn't a good idea because you'll have to restore old strings or create a backup file to be able to change them another time, also it won't be asynchrone and it will cause a problem in every way! you can do it much easier and more cleaner:

just go to your mail options and add context with your variables:

var mailOptions = {
  from: 'nginx-iwnl@gmail.com',
  to: 'username@gmail.com',
  subject: 'Sending email',
  template: 'yourTemplate',
  context: {                  // <=
    username: username,
    whatever: variable
  }
};

next thing to do is openning your html file and call your variables like:

{{username}}

larachiwnl
  • 337
  • 5
  • 10
8

Create one file emailTemplates.js there yo can store each template as a function

emailTemplates.js

const newsLetterEmail = (clientName) => `<p>Hi ${clientName}, here you have today news.</p>`
const welcomeEmail = (clientName, username) => `<p>Welcome ${clientName}, your username is ${username}.</p>`

export {newsLetterEmail, welcomeEmail}

Then in the controllers call any templateFunction and store in output varaible

controller.js

import {welcomeEmail} from './emailTeamplates.js'

const registerUser = async(req, res) => {
    const {name, usename, email} = req.body
    // User register code....
    const output = welcomeEmail(name, username)

    let mailOptions = {
        from: '"Welcome" <welcome@welcome.com>',
        to: 'client@gmail.com',
        subject: 'Welcome email!',
        text: 'Hello World',
        html: output,
    }
 
Cesar Moran
  • 123
  • 1
  • 9
6

If you're using Nodemailer 2.0.0 or higher, check this documentation: https://community.nodemailer.com/2-0-0-beta/templating/ There they explain how to make use of external rendering with templates like that:

// external renderer
var EmailTemplate = require('email-templates').EmailTemplate;
var send = transporter.templateSender(new EmailTemplate('template/directory'));

They also give this example:

// create template based sender function
// assumes text.{ext} and html.{ext} in template/directory
var sendPwdReminder = transporter.templateSender(new EmailTemplate('template/directory'), {
    from: 'sender@example.com',
});

where you see how to pass variables.

You will need the email-templates module: https://github.com/crocodilejs/node-email-templates and a template engine of your choice.

Also in the documentation of email-templates you'll find how to make your file structure in order that your templates can be found:

html.{{ext}} (required) - for html format of email

text.{{ext}} (optional) - for text format of email style.

{{ext}}(optional) - styles for html format subject.

{{ext}}(optional) - for subject of email

See supported template engines for possible template engine extensions (e.g. .ejs, .jade, .nunjucks) to use for the value of {{ext}} above.

You may prefix any file name with anything you like to help you identify the files more easily in your IDE. The only requirement is that the filename contains html., text., style., and subject. respectively.

Community
  • 1
  • 1
Michael Troger
  • 3,336
  • 2
  • 25
  • 41
4

For those using pug as templating engine

Just a quick way to render a template in a separate file using pug's render function:

// function to send an e-mail. Assumes you've got nodemailer and pug templating engine installed. 
// transporter object relates to nodemailer, see nodemailer docs for details
const nodemailer = require('nodemailer');
const pug = require('pug');
function send_some_mail(iterable){
var message = {
  from: 'from@example.com',
  to: 'to@example.com',
  subject: 'Message title',
  html: pug.renderFile(__dirname + 'path_to_template.pug', {iterable: iterable})
};
transporter.sendMail(message, function(err, info){...})
}

// template.pug
each item in iterable
li
  p #{item.name}

See https://pugjs.org/api/getting-started.html for further details. Note that this will cause template re-compilation every time a message is sent. That is fine for occasional e-mail deliveries. If you send tons of e-mails, you can cache the compiled template to work around that. Check out pug docs for that set up if you need it.

wondersz1
  • 757
  • 8
  • 15
3

You can use a Web Request to build an html template using handlebars or any other engine.

Create a template

First you must create an html template for the email body. In this example I used a handlebars hbs file.

enter image description here

Do your design stuff with html and add the variables that you will need in the message:

   <!DOCTYPE html>
   <html>
    <head>
        <meta name="viewport" content="width=device-width">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome Email Template</title>
    </head>
    <body>
     <p style="font-size: 14px; font-weight: normal;">Hi {{data.name}}</p>
    </body>
   </html>

Create a template request

You must create the access to this view. Then a request is created where we can send the template name as an url parameter to make the request parameterizable for other templates.

const web = express.Router()

web.post('/template/email/:template', function(req, res) {
  res.render(`templates/email/${req.params.template}`, {
    data: req.body        
  })
})

Mail function

Finally you can send the email after making the request to the template. You can use a function like the following:

const nodemailer = require('nodemailer')
const request = require("request")

function sendEmail(toEmail, subject, templateFile) {
    var options = {
        uri: `http://localhost:3000/template/email/${templateFile}`,
        method: 'POST',
        json: { name: "Jon Snow" } // All the information that needs to be sent
    };  
    request(options, function (error, response, body) {
        if (error) console.log(error)
        var transporter = nodemailer.createTransport({
            host: mailConfig.host,
            port: mailConfig.port,
            secure: true,
            auth: {
                user: mailConfig.account,
                pass: mailConfig.password
            }
        })
        var mailOptions = {
            from: mailConfig.account,
            to: toEmail,
            subject: subject,
            html: body
        }       
        transporter.sendMail(mailOptions, function(error, info) {
            if (error) console.log(error)
        })
    })
}
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
J.C. Gras
  • 4,934
  • 1
  • 37
  • 44
2

This can be done without templates.

Try changing it to this:

`Hello ${username}!`

Make sure that these are not inverted commas but back ticks.

Ethan
  • 4,295
  • 4
  • 25
  • 44
Omkar Kulkarni
  • 1,091
  • 10
  • 22
2

There is one easy way to insert variable inside html in nodemailer.

    html:"<p>Your message "+variable1+".Message continueous "+variable 2+"</p>"
0

You can also use async/await syntax or promises and avoid using callbacks, like I did here, using async/await:

const fs = require("fs").promises;
const path = require("path");
const handlebars = require("handlebars");
const relativeTemplatePath = "../../html/reset-pw-email-template.html";

function sendEmail(){
    const templatePath = path.join(__dirname, relativeTemplatePath);
    const templateFile = await fs.readFile(templatePath, 'utf-8');
    const template = handlebars.compile(templateFile);
    const replacements = {
        username:""
    };
    const finalHtml = template(replacements);
    const mailOptions = {
       from: "",
       to: "",
       subject: "",
       html: finalHtml,
    };
 }
AleP _C.P.
  • 13
  • 1
  • 4
0

For pug template: #{} way might not well supported.

- var url = thisIsTheVariable;
a(href='/' + url) Link

Doc is here

William Hu
  • 15,423
  • 11
  • 100
  • 121