2012-12-06 34 views
3

我正在編寫一些代碼,通過Mailgun email service發送帶附件的電子郵件。他們在API docs using CURL中給出了以下示例,我需要弄清楚如何在Node.js中執行相同的操作(最好使用請求庫)。如何使用Node.js和請求庫將文件附加到POST請求到Mailgun的API

curl -s -k --user api:key-3ax6xnjp29jd6fds4gc373sgvjxteol0 \ 
    https://api.mailgun.net/v2/samples.mailgun.org/messages \ 
    -F from='Excited User <[email protected]>' \ 
    -F to='[email protected]' \ 
    -F cc='[email protected]' \ 
    -F bcc='[email protected]' \ 
    -F subject='Hello' \ 
    -F text='Testing some Mailgun awesomness!' \ 
    -F html='\<html\>HTML version of the body\<\html>' \ 
    -F [email protected]/cartman.jpg \ 
    -F [email protected]/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)) 

回答

5

對於必須設置正確的標題和發送編碼的用戶名和密碼的base64基本授權部分。有關更多信息,請參閱此SO question。你可以使用headers這個選項。

如何發送與表單字段POST請求在request docs描述:

var r = request.post('http://service.com/upload') 
var form = r.form() 
form.append('from', 'Excited User <[email protected]>') // 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: "[email protected]", 
    to: "[email protected]", 
    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帳戶,但它應該工作沒有測試它。

+0

我遵循上面的模式追加文件和Mailgun發回一個錯誤,說''從'參數丟失「,這讓我認爲我做錯了什麼。 node-mailgun不支持附件(或者對於這個問題的html電子郵件......)我沒有想過使用nodemailer。它確實支持附件和Mailgun,雖然通過SMTP網關,這很好,但我仍然好奇 –

+0

我是如何將當前代碼添加到問題的。 –

+0

是否將'url =「https:// api:[email protected]/v2/samples.mailgun.org/log」;''授權參數添加到'mailgun_uri'?我在回答中添加了一些nodemailer的代碼。 – zemirco