无法使用nodemailer发送带附件的电子邮件

Can't send Emails with attachments with nodemailer

我用nodemailer发送带附件的邮件有如下功能,但有时会returns报错,文件路径存在也找不到。你能告诉我我的错误在哪里吗?

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\asd0a3e0f-2f16-4227-a886-873a8529737f\asd.pdf' 

路径存在

由于节点 Js 是单线程的、事件驱动的,这似乎是适当链接函数的问题。

您的 PDF 创建代码需要时间 return,但到那时您的发送邮件代码已经被调用,并且它发现文件夹尚未创建。

试试这个:

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);
    });
});
}