2012-10-15 167 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') 
     }] 
相关问题