【发布时间】:2022-01-16 09:49:24
【问题描述】:
我正在尝试使用 node-fetch 发送文件以及 Nextjs 中状态的其他字段。 目标不是将文件存储在服务器上(即使是暂时的),而是在用户将表单提交到 Nodemailer 时从 Web 浏览器流式传输,然后从 Nodemailer 以附件的形式发送电子邮件以及其他信息。
客户:
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");
});
});
编辑:我可以使用上述代码将文件作为附件流式传输。
- 需要改进。
【问题讨论】:
标签: stream attachment nodemailer node-fetch