Home > front end >  How to send pdf via gmail api
How to send pdf via gmail api

Time:04-01

I have implemented gapi/ 0Auth2 elsewhere in my code and everything works, except the attached PDF is broken. The PDF can not be previewed and is empty when downloaded.

´´´

function stuffer() {
var sender = "[email protected]";
var receiver = "[email protected]";

let dem = pdfCon("ny brab verder");
console.log(dem);

var mail = [
  'Content-Type: multipart/mixed; boundary="foo_bar_baz"\r\n',
  "MIME-Version: 1.0\r\n",
  "From: "   sender   "\r\n",
  "To: "   receiver   "\r\n",
  "Subject: Subject Text\r\n\r\n",

  "--foo_bar_baz\r\n",
  'Content-Type: text/plain; charset="UTF-8"\r\n',
  "MIME-Version: 1.0\r\n",
  "Content-Transfer-Encoding: 7bit\r\n\r\n",

  "The actual message text goes here\r\n\r\n",

  "--foo_bar_baz\r\n",
  "Content-Type: application/pdf\r\n",
  "MIME-Version: 1.0\r\n",
  "Content-Transfer-Encoding: base64\r\n",
  'Content-Disposition: attachment; filename="generated.pdf"\r\n\r\n',

  dem,
  "\r\n\r\n",

  "--foo_bar_baz--",
].join("");
return sendMessage(mail);

}

  function sendMessage(message) {
    var base64EncodedEmail = btoa(message)
      .replace(/\ /g, "-")
      .replace(/\//g, "_");
    gapi.client.gmail.users.messages
      .send({
        userId: "me",
        resource: {
          raw: base64EncodedEmail,
        },
      })
      .then(function (response) {
        console.log(response);
      });
  }

  function pdfCon(content) {
    var pdf = new jsPDF();
    pdf.text(content, 10, 10);
    pdf.setProperties({
      title: "new Report",
    });
    return pdf.output("datauristring");
  }

´´´

I have tried premade PDF, rather than jsPDF.

I have followed the documentation on google and looked at different post, but there seem to be no documentation for this specifik problem.

CodePudding user response:

From your script, I thought that the returned value from pdfCon("ny brab verder") is the data URL. So, how about the following modification?

From:

let dem = pdfCon("ny brab verder");

To:

let dem = pdfCon("ny brab verder").split(",")[1];
  • In this modification, the header is removed from the data URL. By this, only the base64 data is retrieved.
  • Related