2012-10-15 171 views
0

我試圖從發佈請求發送電子郵件。我正在使用Express和nodemailer。我對'fs'感到困惑我的電子郵件正在發送,但圖像不包含在附件中。我檢查了文檔,但它們似乎都發送了靜態文件,而不是從表單請求中傳輸的文件。Node.js使用nodemailer發送帶圖像附件的電子郵件

var smtpTransport = nodemailer.createTransport("SMTP",{ 
    service: "Gmail", 
    auth: { 
    user: "[email protected]", 
    pass: "password_for_gmail_address" 
    } 
}); 

app.get('/', function(req, res){ 
    res.send('<form method="post" enctype="multipart/form-data">' 
     + '<p>Post Title: <input type="text" name="title"/></p>' 
     + '<p>Post Content: <input type="text" name="content"/></p>' 
     + '<p>Image: <input type="file" name="image"/></p>' 
     + '<p><input type="submit" value="Upload"/></p>' 
     + '</form>'); 
    }) 

app.post('/', function(req, res, next){ 
    var mailOptions = { 
    from: "[email protected]", // sender address 
    to: "[email protected]", // list of receivers 
    subject: req.body.title, // Subject line 
    text: req.body.content, // plaintext body 
    attachments:[ 
     { 
     fileName: req.body.title, 
     streamSource: req.files.image 
     } 
    ] 
    } 

    smtpTransport.sendMail(mailOptions, function(error, response){ 
    if(error){ 
     console.log(error); 
     res.send('Failed'); 
    }else{ 
     console.log("Message sent: " + response.message); 
     res.send('Worked'); 
    } 
    }); 
}); 

回答

1

假設req.files.imageFile對象,而不是一個可讀的流,你需要爲它創建一個讀操作流,你可以在附件中使用:

streamSource: fs.createReadStream(req.files.image.path) 
+0

我提出的附件對象看起來像這樣 '附件:[ { 文件名: 「JPG」 req.body.title +, 的StreamSource:fs.createReadStream(req.files.image.path) } ]' – PaulWoodIII

0

而不是streamSource嘗試使用contents

contents: new Buffer(req.files.image, 'base64') 
+0

這是作爲一個附件得到它,但它不被視爲我的電子郵件客戶端的圖像。我認爲它可以工作,但不像複製粘貼容易JohnnyHK的答案 - 但謝謝! – PaulWoodIII

1

這個工作對我來說:

attachments: [{ // stream as an attachment 
      filename: 'image.jpg', 
      content: fs.createReadStream('/complete-path/image.jpg') 
     }] 
相關問題