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"
                    }
                }
            }
        }
        }



    });
}

您的帮助将不胜感激。

最好的

4

1 回答 1

4

要发送 SendGrid 事务模板,您有不同的选择

1) 通过 SendGrid SMPT API

在这种情况下,我们可以使用 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(此处为 docs)。在这种情况下,我们可以使用 Meteor http 包。

在 shell 中添加 Meteor http 包类型:

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);
于 2017-11-21T21:09:10.847 回答