Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to html template in nodemailer

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: '[email protected]',     to : '[email protected]',     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?

like image 242
Wacław Łabuda Avatar asked Sep 14 '16 11:09

Wacław Łabuda


People also ask

How do I send an HTML email with Nodemailer?

Sending email with Nodemailer is straightforward: all we need to do is call the sendMail method on the value returned from nodemailer. createTransport() that we stored in the smtp variable above, like this: smtp. sendMail({ ... })

Can we send HTML with Nodemailer module?

NodeMailer is the most famous module used for sending and receiving emails from NodeJS applications. It is a zero dependency module for your NodeJS apps. You can easily send emails as plain text, HTML, or attachments (image, document, etc.).


2 Answers

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);             throw 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) {     var template = handlebars.compile(html);     var replacements = {          username: "John Doe"     };     var htmlToSend = template(replacements);     var mailOptions = {         from: '[email protected]',         to : '[email protected]',         subject : 'test subject',         html : htmlToSend      };     smtpTransport.sendMail(mailOptions, function (error, response) {         if (error) {             console.log(error);             callback(error);         }     }); }); 
like image 94
Ananth Pai Avatar answered Sep 17 '22 16:09

Ananth Pai


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 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: '"[email protected]" <[email protected]>',     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/");  } 
like image 36
umutyerebakmaz Avatar answered Sep 20 '22 16:09

umutyerebakmaz