我有以下功能用于使用nodemailer发送带附件的电子邮件,但有时它返回错误enoent,即使文件路径存在也无法找到。你能告诉我我的错误在哪里吗?
function sendEmail(userEmail, htmlString, requestSnap, FIREBASE_WEB) {
fileName ="test.pdf";
folderName = "./" + uuid.v4();
mkdirp(folderName, function(err) {
if (err) console.error(err)
else console.log(folderName + ' folder created!')
});
pdf.create(htmlString + userEmail, options).toFile(folderName + '/' + fileName, function(err, res) { // if the file doesnt exist it will be created
if (err) return console.log(err);
console.log(res);
});
var transporter = nodemailer.createTransport(smtpTransport({
service: 'Gmail',
auth: {
user: '...',
pass: '...'
}
}));
console.log("\nPATH " + folderName + "/" + fileName);
var mailOptions = {
from: 'marija.lukaroska.cw@gmail.com',
to: userEmail,
subject: 'So mail vo pdf-ot',
text: 'Hellow',
attachments: [{
path: folderName + "/" + fileName
}]
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log("ERROR kkkk " + error);
} else {
console.log('Email sent: ' + info.response);
console.log("REQUEST SNAP " + JSON.stringify(requestSnap));
}
deleteFolderRecursive(folderName);
});
}
错误日志:
ERROR kkkk Error: ENOENT: no such file or directory, open 'C:\Users\asd\Documents\Projects\asd\asd\010a3e0f-2f16-4227-a886-873a8529737f\asd.pdf'
路径存在
答案 0 :(得分:1)
由于节点Js是单线程的,事件驱动的,这似乎是一个适当地链接你的函数的问题。
您的PDF创建代码需要时间才能返回,但到那时您的发送邮件代码已经被调用,并且它找到了尚未创建的文件夹。
试试这个:
function sendEmail(userEmail, htmlString, requestSnap, FIREBASE_WEB) {
fileName = "test.pdf";
folderName = "./" + uuid.v4();
mkdirp(folderName, function (err) {
if (err) console.error(err)
else console.log(folderName + ' folder created!')
});
pdf.create(htmlString + userEmail, options).toFile(folderName + '/' + fileName, function (err, res) { // if the file doesnt exist it will be created
if (err) return console.log(err);
console.log(res);
var transporter = nodemailer.createTransport(smtpTransport({
service: 'Gmail',
auth: {
user: '...',
pass: '...'
}
}));
console.log("\nPATH " + folderName + "/" + fileName);
var mailOptions = {
from: 'marija.lukaroska.cw@gmail.com',
to: userEmail,
subject: 'So mail vo pdf-ot',
text: 'Hellow',
attachments: [{
path: folderName + "/" + fileName
}]
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log("ERROR kkkk " + error);
} else {
console.log('Email sent: ' + info.response);
console.log("REQUEST SNAP " + JSON.stringify(requestSnap));
}
deleteFolderRecursive(folderName);
});
});
}