问题
I have the following function for sending emails with attachments using nodemailer, but sometimes It returns error enoent, the file path can't be found even if it exists. Can you tell me where is my mistake?
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 log:
ERROR kkkk Error: ENOENT: no such file or directory, open 'C:\Users\asd\Documents\Projects\asd\asd\010a3e0f-2f16-4227-a886-873a8529737f\asd.pdf'
the path exists
回答1:
As node Js is single threaded, event driven, this seems to be an issue of chaining your functions appropriately.
Your PDF creation code is taking time to return but by that time your send mail code is already called and it finds the folder is not yet created.
Try this:
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);
});
});
}
来源:https://stackoverflow.com/questions/44884455/cant-send-emails-with-attachments-with-nodemailer