2

I am generating a PDF client side with jsPDF. I need to send it to my Express server using Axios. At the end I need to send it via email with Nodemailer. Where am I wrong?

Client side code:

//doc creation ....
var res = doc.output('datauristring');   //this line!!!!
axios.post('/mailsender', res).then((res) => {
    if(res.status === 'ok') console.log("Yeah!");
    else console.log(":(");
});

Server side code:

...

api_router.post('/mailsender', (req, res) => {
    mail.send(req.body, (res) => {
        res.status(200).json({"status": res ? 'ok' : 'error' });
    });
});

mail.js that is:

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
    host: 'smtp.mail.yahoo.com',
    port: 465,
    secure: true,
    auth: {
        user: 'example@yahoo.it',
        pass: 'password'
    }
});


exports.send = function (data, callback) {
    let mailOptions = {
        from: '"My application" <example@myapp.com>',
        to: "receiverAddress",
        subject: "Attachment experiment",
        text: "My <3",
        attachments: [
            {
                filename: 'attachment.pdf',
                content: data,
                contentType: 'application/pdf',
                encoding: 'base64'    //this line!!!!
            }
        ]
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
            callback(false);
        }
        callback(true);
    });
}

All is working fine, except that if I try to open the attachment in the received mail, Preview says that the file is damaged. The same if I try to open it with google chrome or with other PDF readers. Probably, the two lines with a comment has to be changed. Thank you for your attention!

Luca Di Liello
  • 1,486
  • 2
  • 17
  • 34
  • I stumbled upon your post after trying to solve a similar issue. I tried your way of doing it but still not getting the right results. Is there any way you could look at my post and see if you can help me? https://stackoverflow.com/questions/61754787/render-pdf-using-jspdf-and-html2canvas-and-attach-in-email-using-nodemailer – Michael May 12 '20 at 16:06

3 Answers3

3

It was very simple: I had only to change the the attachment part in this way:

attachments: [
    {
        path: data
    }
]
Luca Di Liello
  • 1,486
  • 2
  • 17
  • 34
  • How do I save generated `datauristring` as a .pdf file in to the `mongodb` through the express.js server ?. – Sanjay Shr Aug 25 '18 at 09:37
  • This answer should help you: https://stackoverflow.com/questions/38559604/how-encode-in-base64-a-file-generated-with-jspdf-and-html2canvas – Luca Di Liello Aug 25 '18 at 11:46
  • Thank you soooo much! This was the only post I could find that resolved the issue: I generate the pdf content using doc.output('datauristring'), and then put the content directly in as: attachments: [{path: content}] – Dean Jan 30 '20 at 22:34
  • 1
    You can set the attachment filename also in the same attachment object: { path: content, filename: 'bla.pdf' } – Dean Jan 30 '20 at 22:47
0

Below code worked for me , i used axios in client to post the pdf and nodemailer in server side in node.js to send pdf as attachment

Client :

const out = pdf.output('datauristring');
const response = await axios.post(`/email/sendReport`, {
  pdf: out.split('base64,')[1],
});

Server:

let mailOptions = {
    from: '"My application" <example@myapp.com>',
    to: "receiverAddress",
    subject: "Attachment experiment",
    text: "My <3",
    attachments: [
        {
            filename: 'attachment.pdf',
            content: req.body.pdf,
            contentType: 'application/pdf',
            encoding: 'base64'
        }
    ]
};
Pallav Gupta
  • 101
  • 1
  • 3
0

I am saving pdf on the server and also sending pdf in Laravel mail from jsPDF.I'm posting my code.perhaps it helps someone.

 sendPdfInMail() { 
      const doc = new jsPDF() 
      doc.text('Pdf from jspdf!', 10, 10)  
      var formData = new FormData()
      formData.append('file',          doc.output('datauristring').split('base64,')[1])
      axiosIns
        .post('auth/currency_statement', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        .then(function (response) {
          console.log(response)
        })
        .catch(function (err) {
          console.log(err.response)
          alert('error')
        })
    },
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

PHP Laravel (Server Code)

public function send_currency_statement(Request $request) {

  $data["email"] = "text@money.com";
  $data["title"] = "Currency statement";
  $data["body"] = "Please check your invoice";



  $fileName = time().
  '.pdf';
  $path = public_path('temp/').$fileName;
  //Decode pdf content
  $pdf_decoded = base64_decode($request - > file);
  //Write data back to pdf file
  $pdf = fopen('temp/'.$fileName, 'w');
  fwrite($pdf, $pdf_decoded);
  //close output file
  fclose($pdf);


  Mail::send('emails.myTestMail', $data, function($message) use($data, $path) {
    $message - > to($data["email"], $data["email"]) -
      >
      subject($data["title"]);
    $message - > attach($path);
  });



  return response() - > json(['message' => 'send successfully']);

}
FAZAL HAKIM
  • 89
  • 1
  • 5