将变量传递给nodemailer中的html模板
问题描述:
我想使用HTML模板通过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: '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);
}
});
假设我要在emailWithPDF.html中输入以下内容:
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>'
...
但我希望将其保存在单独的html文件中.有可能吗?
but I want it in separate html file. Is it possible?
答
您可以做的是使用节点中的fs
模块读取HTML文件,然后使用handlebars
替换要在html字符串中更改的元素.
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) {
throw 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) {
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);
callback(error);
}
});
});