constfileUpload=require("express-fileupload");// I don't know whyapp.use(express.urlencoded({extended:true}));// But this is required. I dropped itapp.use(fileUpload({createParentPath:true// and it stopped working.}));constsendEmail=async(data)=>{letform=document.querySelector('form');constformData=newFormData(form);const{file}=data;for(let[index,value]ofObject.entries(file)){formData.append(value.name,file[index]);}axios({method:'post',url:'http://localhost:3001/send',data:formData,});}
and on the backend:
app.post('/send',async(req,res)=>{constdocs=Object.keys(req.files).map(key=>{return{filename:req.files[key].name,content:req.files[key].data}});letmailOptions={from:'whoever@whereever.net',to:'to-mail@mail.go',subject:`Message from: Whoever`,html:'<html></html>',attachments:docs// <--- All you need here!!};transporter.sendMail(mailOptions,function(err,data){if(err){res.json({status:'fail',});}else{console.log('== Message Sent ==');res.json({status:'success',});}});});
I edited it a dozen times to make sure I had it just right, for posterity. I really hope this helps someone later, because it was a pain to figure out, and searching yielded bits and pieces, but NOTHING on the backend portion.
Yeah it definitely will. I had a hard time finding quality full stack nodemailer stuff before putting this article together with bits and pieces that I found that worked. What really surprised me is how you were able to receive the file data on the api without needing a middleware package like multer. I’ll for sure be trying this.
That’s awesome! You mind sharing? Really curious to see what you came up with
This works with multi-file attachments too.
My handleChange()
So, in my API calling method I did:
and on the backend:
Nice! Solid work. Glad you figured it out and thanks for sharing
I edited it a dozen times to make sure I had it just right, for posterity. I really hope this helps someone later, because it was a pain to figure out, and searching yielded bits and pieces, but NOTHING on the backend portion.
Yeah it definitely will. I had a hard time finding quality full stack nodemailer stuff before putting this article together with bits and pieces that I found that worked. What really surprised me is how you were able to receive the file data on the api without needing a middleware package like multer. I’ll for sure be trying this.
I had to update. I took a part out I thought was no longer needed, and I was wrong. I guess there is your middleware you were talking about.
Thanks @chris and @jlong4223 for sharing this information.