Node.js sending an email with image attachment using nodemailer
14,745
Solution 1
Assuming req.files.image
is a File
object, not a readable stream, you'd need to create a read stream for it that you can use in the attachment:
streamSource: fs.createReadStream(req.files.image.path)
Solution 2
this worked for me:
attachments: [{ // stream as an attachment
filename: 'image.jpg',
content: fs.createReadStream('/complete-path/image.jpg')
}]
Author by
PaulWoodIII
Updated on June 04, 2022Comments
-
PaulWoodIII almost 2 years
I'm trying to send an email from a post request. I'm using Express and nodemailer. I'm confused by 'fs' My email is getting sent but the image is not included as an attachment. I checked the docs but they all seem to send up static files not files being streamed in from a form request.
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'); } }); });
-
PaulWoodIII over 11 yearsI made the attachments object look like this 'attachments:[ { fileName: req.body.title+".jpg", streamSource: fs.createReadStream(req.files.image.path) } ]'
-
PaulWoodIII over 11 yearsThis got it in as an attachment but it wasn't treated as an image by my email client. I think it could work but not as copy paste easy as JohnnyHK's answer - Thanks though!