如何使用Node.js和Request库将文件附加到Mailgun API的POST请求?

3
我正在编写一些代码,通过Mailgun邮件服务发送带附件的电子邮件。他们在API文档中使用CURL给出了以下示例,我需要弄清楚如何在Node.js中执行相同的操作(最好使用Request库)。
curl -s -k --user api:key-3ax6xnjp29jd6fds4gc373sgvjxteol0 \
    https://api.mailgun.net/v2/samples.mailgun.org/messages \
    -F from='Excited User <me@samples.mailgun.org>' \
    -F to='obukhov.sergey.nickolayevich@yandex.ru' \
    -F cc='sergeyo@profista.com' \
    -F bcc='serobnic@mail.ru' \
    -F subject='Hello' \
    -F text='Testing some Mailgun awesomness!' \
    -F html='\<html\>HTML version of the body\<\html>' \
    -F attachment=@files/cartman.jpg \
    -F attachment=@files/cartman.png

我的当前代码(Coffescript)如下所示:

r = request(
  url: mailgun_uri
  method: 'POST'
  headers:
    'content-type': 'application/x-www-form-urlencoded'
  body: email
  (error, response, body) ->
    console.log response.statusCode
    console.log body
)
form = r.form()
for attachment in attachments
  form.append('attachment', fs.createReadStream(attachment.path))
1个回答

6
对于基本授权部分,您需要设置正确的标头并发送用户名和密码的base64编码。有关更多信息,请参见此SO问题。您可以使用headers选项来实现此功能。
如何使用表单字段发送POST请求在请求文档中有描述。
var r = request.post('http://service.com/upload')
var form = r.form()
form.append('from', 'Excited User <me@samples.mailgun.org>') // taken from your code
form.append('my_buffer', new Buffer([1, 2, 3]))
form.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png')) // for your cartman files
form.append('remote_file', request('http://google.com/doodle.png'))

还有一些现有的npm模块支持mailgun,比如:

一个使用nodemailer的示例:

var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Mailgun", // sets automatically host, port and connection security settings
    auth: {
        user: "api",
        pass: "key-3ax6xnjp29jd6fds4gc373sgvjxteol0"
    }
});

var mailOptions = {
  from: "me@tr.ee",
  to: "me@tr.ee",
  subject: "Hello world!",
  text: "Plaintext body",
  attachments: [
    {   // file on disk as an attachment
        fileName: "text3.txt",
        filePath: "/path/to/file.txt" // stream this file
    },
    {   // stream as an attachment
        fileName: "text4.txt",
        streamSource: fs.createReadStream("file.txt")
    },
  ]
}

transport.sendMail(mailOptions, function(err, res) {
  if (err) console.log(err);
  console.log('done');
});

我没有mailgun帐户,所以没有测试过,但应该可以工作。


我按照上述模式附加文件,但Mailgun返回了一个错误,说“缺少'from'参数”,这让我认为我做错了什么。node-mailgun不支持附件(或HTML电子邮件...)我没有考虑使用nodemailer。它支持附件和Mailgun,尽管通过SMTP网关,这很好,但我仍然很好奇 - Kyle Mathews
你有将授权参数添加到 mailgun_uri 中吗?类似这样:url = "https://api:key-3ax6xnjp29jd6fds4gc373sgvjxteol0@api.mailgun.net/v2/samples.mailgun.org/log"; 我在我的答案中添加了一些 nodemailer 的代码。 - zemirco
是的 - 我没有展示所有的代码。稍后我会尝试使用nodemailer。 - Kyle Mathews

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