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

Kyl*_*ews 3 request node.js mailgun

我正在编写一些代码,通过Mailgun电子邮件服务发送带附件的电子邮件.他们使用CURL在他们的API文档中给出了以下示例,我需要弄清楚如何在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
Run Code Online (Sandbox Code Playgroud)

我当前的代码(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))
Run Code Online (Sandbox Code Playgroud)

zem*_*rco 5

对于基本授权部分,您必须设置正确的标头并发送用户名和密码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'))
Run Code Online (Sandbox Code Playgroud)

在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');
});
Run Code Online (Sandbox Code Playgroud)

没有测试它,因为我没有mailgun帐户,但它应该工作.