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

Using the sendgrid node-module, how do I send a SendGrid Template Engine email?

我已经通过 SendGrid 的模板引擎创建了一个 "Thanks for subscribing" 电子邮件模板。

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

我在文档中没有看到任何关于此的信息。

您似乎需要使用 SMTPAPI 的 app(filters) 方法来发送模板。我不相信网络 API 还支持它。这是一些文档:

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

是的,这真的很简单,您只需将其添加为过滤器即可。它应该是这样的:

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.

的博客 post

要使其与版本 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