Pass variable to html template in nodemailer - javascript

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?

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

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/");
}

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}}

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.

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,
}

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.

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.
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)
})
})
}

This can be done without templates.
Try changing it to this:
`Hello ${username}!`
Make sure that these are not inverted commas but back ticks.

There is one easy way to insert variable inside html in nodemailer.
html:"<p>Your message "+variable1+".Message continueous "+variable 2+"</p>"

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,
};
}

Related

react add data from MongoDB to email

pretty new to react only been doing it for a couple of weeks and I'm working on a project for personal use to send an email to my email using nodemailer which I have managed to do. the next part I want to do is add data to the email that will come from my MongoDB database like the order number, customer name and status of the job I've searched high and low on youtube and google and not really finding anything on the issue
also, it only runs when I type node server.js and then it automatically sends the email which I don't want I want it to run when submit is clicked when a status is updated in the database.
Here is the code for what I have on server.js
require('dotenv').config();
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
let mailOptions = {
from: 'group2021#gmail.com',
to: 'edge#gmail.com',
subject: 'Project Update',
text: 'Hello {{name}} please find this email as an update to you project.'
};
transporter.sendMail(mailOptions, function(err, data) {
if(err) {
console.log('Error Occured!', err);
} else {
console.log('Email Sent!')
}
});
I'm not sure how your application looks like, I assume it's SPA react application.
I suggest you to create simple http server using Expressjs and creating endpoint which you will call from the client (react app) e.g. (the code is not tested is just an example)
const express = require('express');
const app = express();
const port = 3000;
const nodemailer = require('nodemailer');
app.get('/mail/:someID', async (req, res) => {
// someID is identifier to find data in db
// it will come from localhost:PORT/mail/>>someID<<
const { someID } = req.params;
let data;
try {
data = await mongoCol.FindOne({
/* query */
}); // reads data from mongo
} catch (err) {
return res.status(500).json(err);
}
// prepare content
var text =
'Hello {{name}} please find this email as an update to you project.\n' + data;
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
let mailOptions = {
from: 'group2021#gmail.com',
to: 'edge#gmail.com',
subject: 'Project Update',
text: text
};
transporter.sendMail(mailOptions, function (err, data) {
if (err) {
console.log('Error Occured!', err);
return res.status(500).json(err);
} else {
console.log('Email Sent!');
return res.sendStatus(200);
}
});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
You should add some kind of authorization to not allow other people to send email by your server.
also, it only runs when I type node server.js and then it automatically sends the email which I don't want
This happens because your code is not in function and any time you import or start file (module) it will execute.

Trying to separate my SendGrid html email templates on my node server

I'm running a node server and I'm sending emails with SendGrid. I need to separate my email HTMLs from my js files so I can modify them from a single base. What I have now is this:
const express = require('express')
const config = require('config')
const sgMail = require('#sendgrid/mail')
const sendKey = config.get('SENDGRID_API_KEY')
sgMail.setApiKey(sendKey)
const msg = {
to: "test#test.com",
from: "test#test.com",
subject: 'Welcome To The App',
text: 'Text is here',
html: <strong>HTML HERE</strong>
}
sgMail.send(msg)
I want to call my HTML property outside of my current js file instead of writing HTML inside my msg object.
How can I have a separate welcomeEmail.html file and add it to my msg object in my js file?
I've tried fs module but all I have is
Error: ENOENT: no such file or directory, open './welcomeEmail.html'
I couldn't be able to read my HTML file anyway.
Any idea of what I'm missing?
You can use fs, you probably have read from wrong path.
Use this:
fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{//do Something});
Make sure welcomeEmail.html is in the right place in your project.
Please remember readFile is async so you should do the rest of your code in the callback, so your code should be something like this (depends on what is the use case):
const express = require('express')
const config = require('config')
const sgMail = require('#sendgrid/mail')
const sendKey = config.get('SENDGRID_API_KEY')
const fs = require('fs')
sgMail.setApiKey(sendKey)
fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{
if(err){
console.log(err);
}
else{
let msg = {
to: "test#test.com",
from: "test#test.com",
subject: 'Welcome To The App',
text: 'Text is here',
html: content
}
sgMail.send(msg)
}
});

How to add image in my email, nodemailer and handlebars?

I am using nodemailer along with handlebars in my node project. The email is working fine but I am not able to attach image in the html template created by handlebars. I tried giving it in img src tag directly in the html but still not working. What i have is that the image is in svg form and in my assets folder of the project.
I also tried the example on the official nodemailer site which did not work as well. Please help me out!
https://nodemailer.com/message/embedded-images/
This is my function which will be called when I get the request from the client.
sendEmail.js
var nodemailer = require("nodemailer");
const emailConfig = require("../readEmailConfigFile");
//reading username and password from json file
let fromemail = emailConfig.readFromEmail();
let password = emailConfig.readFromPassword();
var handlebars = require("handlebars");
var fs = require("fs");
const readHTMLFile = function(path, callback) {
fs.readFile(path, { encoding: "utf-8" }, function(err, html) {
if (err) {
throw err;
callback(err);
} else {
callback(null, html);
}
});
};
/* Method for sending Email */
const sendEmail = (details) => {
var transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: fromemail,
pass: password
}
});
readHTMLFile(
__dirname + "/../emailTemplates/EmailTemplate.html",
function(err, html) {
var template = handlebars.compile(html);
var replacements = {
firstName: details.firstName,
lastName: details.lastName,
address: details.address,
};
var htmlToSend = template(replacements);
var mailOptions = {
from: fromemail,
to: details.email,
subject: "ABC",
html: htmlToSend
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
callback(error);
} else {
console.log("Email Sent : " + info.response);
}
});
}
);
};
This is my html-template file
EmailTemplate.html
<html>
<head>
<title> </title>
</head>
<body>
<p>
Dear {{{firstName}}} {{{lastName}}}, your address is {{{address}}}</span
>
</p>
</body>
</html>
I want to embed an svg image in this html!
just add attachments parameter to your mailoptions object :
var mailOptions = {
from: fromemail,
to: details.email,
subject: "ABC",
attachments: [{
filename: 'imagename.svg',
path: __dirname +'/assets/imagename.svg',
cid: 'imagename'
}],
html: htmlToSend
};
then add the img tag in your HTML <img src="cid:imagename">

Node email template not working on windows

I want to use email templates for different emails (signup, forgot pass etc).
I tried to use node-email-templates but getting nothing while rending email template.
Please see my code below:
var path = require('path'),
templatesDir = path.join(__dirname, '..', 'views/mailer'),
emailTemplates = require('email-templates');
emailTemplates(templatesDir, function (err, template) {
// Render a single email with one template
var locals = {
username: 'John'
};
template('signup', locals, function (err, html, text) {
console.log(html);
console.log(err);
});
});
I am getting "undefined" for both "html" and "err". Please suggest some solution.

How export a module in node.js

emailConfirmation.js:
var configAuth = require('../../authentication/sendgrid');
var sendgrid = require('sendgrid')(configAuth.sg.username, configAuth.sg.password);
var from_address = "mycompany#pubcrawlsp.com";
var text_body = "sometextbody";
var html_body = "somehtml";
Them i need export in my routes, to use in a post route, like this:
app.post('/', function(req, res) {
sendgrid.send({
to: req.body.email,
from: the from_adrres variable from the other file,
subject: "Some subjec",
text: the text_body variable from the other file
html: the html_body variable from the other file
}, function(err, json) {
if (err) {
return console.error(err);
}
console.log(json);
});
});
How can i export the emailConfirmation.js and use like that??
Start by creating a file just for your code.
At the end of the file, you would "expose" parts of the code to a consumer. For example:
In your case you could wrap your code like so:
module.exports.set = function(app) {
app.post('/', function(req, res) {
/* the post code goes here */
});
};
You could consume it with app.js like so on app.js:
require('./sendgrid').set(app);
This would effectively set your route(s) for sendgrid.

Categories

Resources