代码之家  ›  专栏  ›  技术社区  ›  Claudiu S

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

  •  3
  • Claudiu S  · 技术社区  · 10 年前

    我正在尝试使用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模板?

    编辑

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

    有什么建议吗?

    2 回复  |  直到 10 年前
        1
  •  4
  •   Claudiu S    10 年前

    我已经研究了源代码,有一种方法可以传递动态变量。

    欢迎.html

    <p>Welcome %email%</p>
    

    电子邮件.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
    });
    
        2
  •  2
  •   cionescu    10 年前

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

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

    然后:

    sendgrid.send({
     ...
    
    template: stringTemplate })