Mailgun.js是否提供发送模板的可能性



因此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);
});

他们还提供了设计和创建电子邮件模板的可能性。有没有办法通过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,因为它目前显然已经停机,没有明确估计何时可以再次使用(

是的,你可以,下面是你的情况下的格式:

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

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

选项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

虽然这已经在前面的回答中解释过了,但为了完整性,我添加了这一点。

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标头提供变量。

最新更新