将变量传递给 nodemailer 中的 html 模板 [英] Pass variable to html template in nodemailer

查看:40
本文介绍了将变量传递给 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?

推荐答案

你可以做的是使用 node 中的 fs 模块读取 HTML 文件,然后替换你想在 html 中更改的元素使用 handlebars

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

这篇关于将变量传递给 nodemailer 中的 html 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆