如何在 mailgun 电子邮件模板(Node js)中分配变量?

Par*_*ity 3 javascript node.js mailgun

我制作了一个谷歌云函数,在其中我发送了一封电子邮件,其中包含我从另一个地方收到的一些变量。我正在使用mailgun.js并且我正在尝试使用我已经在 mailgun 中创建的模板发送电子邮件。问题是我找不到替换模板中占位符变量的方法。

这是代码:

mg.messages.create('domain', {
    from: 'email',
    to: [email],
    subject: 'subject',
    template: 'template',
    // How to replace the template variables???
  })
  .then(res => console.log('Resolved >>>>> ', res))
  .catch(err => console.log('MAILGUN ERROR >>>> ', err))
Run Code Online (Sandbox Code Playgroud)

mailgun文档这样说:

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'alice@example.com',
  subject: 'Hello',
  template: 'template.test',
  h:X-Mailgun-Variables: '{"title": "API Documentation", "body": "Sending messages with templates"}' // Notice this
};
Run Code Online (Sandbox Code Playgroud)

据我所知,不能将 " h:X-Mailgun-Variables"写为任何对象中的键。

有人知道我需要把它放在哪里或如何放吗?

我认为它应该作为标题发送,但mailgun/mailgun-jshighcaffeinated/mailgun-js 都没有指定如何传递标题。

kut*_*iah 6

根据Mailgun 模板文档,您可以使用下面提供的 2 个选项中的任何一个传递模板数据,

选项1

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'alice@example.com',
  subject: 'Hello',
  template: 'template.test',
  h:X-Mailgun-Variables: '{"title": "API Documentation", "body": "Sending messages with templates"}'
};
Run Code Online (Sandbox Code Playgroud)

在这个例子中,h:X-Mailgun-Variables这是我实现像这样更新我的对象的棘手部分。

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'alice@example.com',
  subject: 'Hello',
  template: 'template.test',
  'h:X-Mailgun-Variables': JSON.stringify({
    title: "API Documentation",
    body: "Sending messages with templates"
  })
};
Run Code Online (Sandbox Code Playgroud)

选项 2

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'alice@example.com',
  subject: 'Hello',
  template: 'template.test',
  'v:title': 'API Documentation',
  'v:body': 'Sending messages with templates'
};
Run Code Online (Sandbox Code Playgroud)

最后,根据他们的文档

不推荐第二种方式(在我们的例子中是选项 2),因为它仅限于简单的键值数据。如果您有数组、值中的字典或复杂的 json 数据,您必须通过X-Mailgun-Variables标头提供变量。