Sendgrid:使用模板发送电子邮件

Sendgrid: Send email with template

我正在尝试使用 SendGrid 发送电子邮件,并尝试针对不同的情况使用多个模板。我的函数如下所示:

var file = "welcome.html"

sendgrid.send({
    to:      to,
    from:     from,
    subject:  subject,
    data: {
        //template vars go here
        email: to,
        confirmLink: confirmLink
    },
    template: "./" + file
}, function(err, json) {
    if (err) { return console.error(err); }
        console.log(json);
});

但是当我发送电子邮件时,我收到

[Error: Missing email body]

是否有任何方法可以附加 html 模板,因为我不想使用具有 html 内容的硬编码字符串?

编辑

读取文件并将其转换为字符串是可行的,但我不确定如何将动态变量传递到模板中..

有什么建议吗?

您需要将模板转换为字符串。试试这个:

var fs = require('fs');
var stringTemplate = fs.readFileSync("welcome.html", "utf8");

然后:

sendgrid.send({
 ...

template: stringTemplate })

我查看了源代码,有一种方法可以传入动态变量。

welcome.html

<p>Welcome %email%</p>

email.js

var file = "welcome.html"
var stringTemplate = fs.readFileSync("./" + file, "utf8");

//create new Emaik object
var email = new sendgrid.Email();

email.addTo(to);
email.setFrom(from);
email.setSubject(subject);
email.setHtml(stringTemplate); //pass in the string template we read from disk
email.addSubstitution("%email%", to); //sub. variables

sendgrid.send(email, function(err, res){
  //handle callbacks here
});