【问题标题】:Does Mailgun.js offer the possibility to send a template?Mailgun.js 是否提供发送模板的可能性?
【发布时间】:2019-04-11 17:53:56
【问题描述】:

所以MailGun 提供了通过实现API 的Node 库发送电子邮件的可能性:

var mailgun = require('mailgun-js')({ apiKey: api_key, domain: DOMAIN });

var filepath = path.join(__dirname, 'sample.jpg');

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'foo@example.com, baz@example.com, bar@example.com',
  cc: 'baz@example.com',
  bcc: 'bar@example.com',
  subject: 'Complex',
  text: 'Testing some Mailgun awesomness!',
  html: "<html>HTML version of the body</html>",
  attachment: filepath
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

它们还提供了设计和创建Email Templates 的可能性。有没有办法通过他们的 API 发送带有一些自定义变量的模板化电子邮件?比如:

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'foo@example.com, baz@example.com, bar@example.com',

  template: "withdraw_request_approved", //Instead of 'html'
  vars: { firstName: 'John', lastName: 'Doe' }
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

如果没有,您能否推荐一些其他提供这种功能的邮件服务? (我已经跳过了Mandrill,因为它目前显然已经关闭,没有明确估计它何时会再次可用)

【问题讨论】:

    标签: node.js email mailgun mailing


    【解决方案1】:

    是的,你可以,以下是你的情况:

    var data = {
      from: 'Excited User <me@samples.mailgun.org>',
      to: 'foo@example.com, baz@example.com, bar@example.com',
    
      template: "withdraw_request_approved", //Instead of 'html'
      'v:firstName': 'John',
      'v:lastName': 'Doe'
    };
    

    【讨论】:

    • 谢谢,你是救生员!我一直按照文档尝试“h:X-Mailgun-Variables”,但它根本不起作用!
    • 你是我的救星!谢谢!
    【解决方案2】:

    根据Mailgun Template Documentation,您可以使用下面提供的 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"}'
    };
    

    在这个例子中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"
      })
    };
    

    选项 2

    虽然这已经在 previous answer 中进行了解释,但为了完整起见,我还是添加了这个。

    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'
    };
    

    最后,根据他们的文档

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多