[英]Node.js sending an email with image attachment using nodemailer
我正在嘗試通過發布請求發送電子郵件。 我正在使用 Express 和 nodemailer。 我對“fs”感到困惑我的電子郵件正在發送,但圖像未作為附件包含在內。 我檢查了文檔,但它們似乎都發送了靜態文件,而不是從表單請求中流式傳輸的文件。
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "gmail_address@gmail.com",
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: "gmail_address@gmail.com", // sender address
to: "somebodyelse@example.com", // 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');
}
});
});
這對我有用:
attachments: [{ // stream as an attachment
filename: 'image.jpg',
content: fs.createReadStream('/complete-path/image.jpg')
}]
假設req.files.image
是一個File
對象,而不是一個可讀流,您需要為它創建一個可以在附件中使用的讀取流:
streamSource: fs.createReadStream(req.files.image.path)
而不是streamSource
嘗試使用contents
contents: new Buffer(req.files.image, 'base64')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.