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

3
我正在尝试使用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内容?

编辑

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

有什么建议吗?


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - bvanvugt
我发现sendgrid确实开发了一个模板引擎。我还深入研究了源代码,并找到了一个解决方案。我会发布它。 - Claudiu S
太棒了,谢谢你的跟进! - bvanvugt
2个回答

4
我已经查看了源代码,有一种方法可以传入动态变量。 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
});

1
在这种情况下,电子邮件HTML文件存储在磁盘上,但是SendGrid允许您通过其Web UI创建模板,我们如何利用这些模板? - mingxiao
我猜他们应该有相关的文档。下面的链接可能会有所帮助,虽然我自己没有使用过他们的模板系统:https://sendgrid.com/docs/User_Guide/Templates/index.html - Claudiu S

2
您需要将模板转换为字符串。请尝试以下方法:
var fs = require('fs');
var stringTemplate = fs.readFileSync("welcome.html", "utf8");

然后:

sendgrid.send({
 ...

template: stringTemplate })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接