使用sendgrid节点模块,如何发送SendGrid模板引擎电子邮件?

时间:2015-03-13 11:33:34

标签: node.js sendgrid

我通过SendGrid的模板引擎创建了一个“感谢订阅”电子邮件模板。

现在,当有人订阅我的网站时,我想向该人发送该模板。我可以使用sendgrid-nodejs包吗?

我在文档中没有看到任何相关内容。

3 个答案:

答案 0 :(得分:14)

是的,这很简单,您只需要将其添加为过滤器即可。以下是它的外观:

var cardEmail = new sendgrid.Email({
  to: "theuser@somedomain.com",
  from: "bignews@yourdomain.com",
  subject: process.env.SUBJECT,
  html: '<h2>Thanks for requesting a business card!</h2>', // This fills out the <%body%> tag inside your SendGrid template
});

// Tell SendGrid which template to use, and what to substitute. You can use as many substitutions as you want.
cardEmail.setFilters({"templates": {"settings": {"enabled": 1, "template_id": "325ae5e7-69dd-4b95-b003-b0109f750cfa"}}}); // Just replace this with the ID of the template you want to use
cardEmail.addSubstitution('-greeting-', "Happy Friday!"); // You don't need to have a substitution, but if you want it, here's how you do that :)

// Everything is set up, let's send the email!
sendgrid.send(cardEmail, function(err, json){
  if (err) {
    console.log(err);
  } else {
    console.log('Email sent!');
  }
});

我希望能帮到你。如果您需要更深入了解它,请查看我撰写的关于using Template Engine with sendgrid-nodejs的博客文章。

答案 1 :(得分:4)

要使其与版本4.x.x一起使用,请使用:

var helper = require('sendgrid').mail;
var from_email = new helper.Email('test@example.com');
var to_email = new helper.Email('test@example.com');
var subject = 'I\'m replacing the subject tag';
var content = new helper.Content('text/html', 'I\'m replacing the <strong>body tag</strong>');
var mail = new helper.Mail(from_email, subject, to_email, content);
mail.personalizations[0].addSubstitution(new helper.Substitution('-name-', 'Example User'));
mail.personalizations[0].addSubstitution(new helper.Substitution('-city-', 'Denver'));
mail.setTemplateId('13b8f94f-bcae-4ec6-b752-70d6cb59f932');

Full example

答案 2 :(得分:0)

您似乎需要使用SMTPAPI的应用(过滤器)方法来发送模板。我不相信它仍然受到Web API的支持。这是一些文档:

https://sendgrid.com/docs/API_Reference/SMTP_API/apps.html#templates