how to fix err:Failed to load PDF document once se

2019-08-22 02:51发布

问题:

I got an app which sending emails with attachments using Nodemailer. First I'm using multer to save the attachment on the server (working well) so I can pass the path of the file to attachments in the nodemailer route. The email and attachment is successfully sent but the attachment failed to be opened/read!

Here is the nodemailer route:

 app.post("/send",  function(req,res){

var transporter = nodemailer.createTransport({
 service: 'gmail',
 auth: {
        user: 'my gmail',
        pass: 'my pass'
    }
});

var quotename = req.params.id;
console.log(quotename);

var storage = multer.diskStorage({
    destination: function (req,file, callback){
        callback(null, './uploads');
    },

    filename: function (req, file, callback){
        callback(null, "Q" + quotename + ".pdf");
    }
});

var upload = multer ({storage : storage}).single("myFile");


upload(req, res, function(err){
    if(err){
        console.log(err);
    } else {        

        const mailOptions = {
          from: req.body.fr, // sender address
          to: req.body.to, // list of receivers
          bcc: req.body.fr,
          subject: req.body.subject, // Subject line
          html: '<h4>Dear ' + req.body.contname+ '</h4>' + '<p>'+ 
         req.body.message + '</p>' + '<p>Kind Regards</p>' + 
           req.body.user,// html body
          attachments: [  
                {   // filename and content type is derived from path
                  filePath: '/constimator/uploads/Q' + quotename + '.pdf',
                },   
            ], 
        };

        transporter.sendMail(mailOptions, function (err, info) {
           if(err){
             return console.log(err);
           }else{
            console.log(req.body.myFile)
            res.redirect("/submitted"); }
          });
        });
     });

I don't know if it's because of filepath/path issue or something else. I tried path(instead of filePath) as well but the same problem

回答1:

I solve the problem myself after lots of trial and error, googling, thinking. For the future refrence and for the people with the same problem, I post my answer as follows:

I have changed the attachments to this and it worked perfectly:

    {   // filename and content type is derived from path
                  filename: "Q" + quotename + ".pdf",
                  contentType: 'application/pdf',
                  path: '/constimator/uploads/Q' + quotename + '.pdf',
                },   
            ],

It was very simple, by adding filename, content type and change filepath to path, probelm solved