Skip to content
Advertisement

How to send pdf via gmail api

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 = "sender@gmail.com";
var receiver = "reciver@hotmail.com";

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

var mail = [
  'Content-Type: multipart/mixed; boundary="foo_bar_baz"rn',
  "MIME-Version: 1.0rn",
  "From: " + sender + "rn",
  "To: " + receiver + "rn",
  "Subject: Subject Textrnrn",

  "--foo_bar_bazrn",
  'Content-Type: text/plain; charset="UTF-8"rn',
  "MIME-Version: 1.0rn",
  "Content-Transfer-Encoding: 7bitrnrn",

  "The actual message text goes herernrn",

  "--foo_bar_bazrn",
  "Content-Type: application/pdfrn",
  "MIME-Version: 1.0rn",
  "Content-Transfer-Encoding: base64rn",
  'Content-Disposition: attachment; filename="generated.pdf"rnrn',

  dem,
  "rnrn",

  "--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.

Advertisement

Answer

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.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement