I'm trying to send a file along with other fields on the state in Nextjs using node-fetch. the goal is not to store the file on the server (even temporarily) but to stream it from the web browser as the user submits the form to the Nodemailer, and then to be emailed from Nodemailer as an attachment along with other information.
client:
const handleFile = (e) => {
let file = e.target.files[0];
let attachment = new FormData();
attachment.append("file", file);
fetch(`route`, {
method: "POST",
headers: {},
body: attachment,
})
.then((response) => {
if (response.ok) console.log("Uploaded");
else console.log("Error");
})
.catch((error) => {
console.log(error);
});
SMTP:
const nodemailer = require("nodemailer");
async function main(subject, html, to, file) {
let transporter = nodemailer.createTransport({
// mail server setup
});
let attachment = [];
if (file) {
attachment = [
{
filename: file.file[0].originalFilename,
path: file.file[0].path,
},
];
}
const mailOptions = {
from: from,
to: to,
subject: subject,
html: html,
attachments: attachment,
};
try {
let info = await transporter.sendMail(mailOptions);
console.log(info);
} catch (error) {
console.error(error, "fail to send email");
}
API :
const express = require("express");
const router = express.Router();
const multiparty = require("multiparty");
const sendEmail = require("../../utilities/SMTP");
router.post("/route", (req, res) => {
var form = new multiparty.Form();
form.parse(req, function (err, fields, files) {
sendEmail(
"Career Attachment",
contactEmail(fields),
"to@mail.com",
files
);
res.send("Your Request Sent Successfully");
});
});
Edit: I'm able to stream the file as an attachment with the above code.
- Needs improvements.