使用Meteor触发SendGrid模板邮件

5
我正在使用sendgrid发送电子邮件。我希望将模板作为电子邮件发送给用户。下面的代码只是发送基于简单文本的电子邮件,而没有定义头部部分并使用模板id。
if (Meteor.isServer) {
    Email.send({
        from: "from@mailinator.com",
        to: "abc@mail.com",
        subject: "Subject",
        text: "Here is some text",
        headers: {"X-SMTPAPI": {
            "filters" : {
                "template" : {
                    "settings" : {
                        "enable" : 1,
                        "Content-Type" : "text/html",
                        "template_id": "3fca3640-b47a-4f65-8693-1ba705b9e70e"
                    }
                }
            }
        }
        }



    });
}

非常感谢您的帮助。

最好的祝福


1
从sendgrid文档中看,你似乎做的一切都正确。Meteor方面也是如此。邮件头信息是否能够正常传递? - Michel Floyd
2
你尝试过将 X-SMTPAPI 头部转换为字符串吗? - MasterAM
你解决了吗? - Nicholas Tsaoucis
1个回答

4
要发送SendGrid事务模板,您有不同的选项。
1)通过SendGrid SMPT API
在这种情况下,我们可以使用Meteor电子邮件包(就像您正在尝试的那样)。
要添加Meteor电子邮件包,我们需要在终端中键入:
meteor add email

根据SendGrid文档,在这种情况下:

text属性将被替换成文本模板的<%body%>,而html则将被替换为HTML模板的<%body%>。如果存在text属性但不存在html属性,则邮件只会包含文本模板的版本,不包括HTML模板。

因此,在您的代码中,您还需要提供http属性,这就是全部内容。
这可能是您的服务器代码:
// Send via the SendGrid SMTP API, using meteor email package
Email.send({
  from: Meteor.settings.sendgrid.sender_email,
  to: userEmail,
  subject: "your template subject here",
  text: "template plain text here",
  html: "template body content here",
  headers: {
    'X-SMTPAPI': {
      "filters": {
        "templates": {
          "settings": {
            "enable": 1,
            "template_id": 'c040acdc-f938-422a-bf67-044f85f5aa03'
          }
        }
      }
    }
  }
});

2) 通过SendGrid Web API v3

您可以使用meteor http包来使用SendGrid Web API v3 (这里是文档)。在这种情况下,我们可以使用Meteor http包。

要添加Meteor http包,请在shell中键入:

meteor add http

接着在您的服务器代码中,您可以使用

// Send via the SendGrid Web API v3, using meteor http package
var endpoint, options, result;

endpoint = 'https://api.sendgrid.com/v3/mail/send';

options = {
  headers: {
    "Authorization": `Bearer ${Meteor.settings.sendgrid.api_key}`,
    "Content-Type": "application/json"
  },
  data: {
    personalizations: [
      {
        to: [
          {
            email: userEmail
          }
        ],
        subject: 'the template subject'
      }
    ],
    from: {
      email: Meteor.settings.sendgrid.sender_email
    },
    content: [
      {
        type: "text/html",
        value: "your body content here"
      }
    ],
    template_id: 'c040acdc-f938-422a-bf67-044f85f5aa03'
  }
};

result = HTTP.post(endpoint, options);

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