2
votes

I have an app script that is creating an PDF from a Google slide. If I send the PDF using Google's MailApp I can receive the PDF correctly.

 var pdf_file =   DriveApp.getFileById(certificate.getId()).getAs('application/pdf');
  GmailApp.sendEmail(email, subject, body,{attachments: pdf_file,name: subject});

So now that I don't want to use GMail but SendGrid instead, I changed just one line from above to no longer call the GMailApp.sendEmail and to now use this new sendGridEmail function:

sendGridEmail(toEmail,subject,body,fromEmail,pdf_file,subject +".pdf"); 

This is my SendGrid Mail function:

function sendGridEmail(toEmail,subject,body_details,fromEmail,myPDFfile,certificateName) {
  var SENDGRID_KEY ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';

  var headers = {
    "Authorization" : "Bearer "+ SENDGRID_KEY, 
    "Content-Type": "application/json" 
  }

  var cert = Utilities.base64Encode(myPDFfile);

  var body =
  {
  "personalizations": [
    {
      "to": [
        {
          "email": toEmail
        }
      ],
      "subject": subject
    }
  ],
  "from": {
    "email": fromEmail
  },
   "template_id":"d-xxxxxxxxxxxxxxxxxxxxxxxxxxx",
   "attachments": [
    {
      content: cert,
      filename: certificateName,
      type: "application/pdf",
    }
  ]
}

  var options = {

    'method':'post',
    'headers':headers,
    'payload':JSON.stringify(body)
  }

 var response = UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send",options);
 Logger.log(response);  

}

I receive the email. All works except the PDF is blank. I can see that when I send the PDF to my sendGridEmail function (it shows in the debugger as a PDF) and once I do the base64Encode, I see that it is a ton of numbers but when I get the email, I see only a blank pdf page. Any thoughts? This is my first time using base64encoding. I may not be doing it correctly.

1

1 Answers

1
votes

How about this modification?

Modification point:

  • From your script, pdf_file of var pdf_file = DriveApp.getFileById(certificate.getId()).getAs('application/pdf'); is sent to sendGridEmail(toEmail,subject,body,fromEmail,pdf_file,subject +".pdf");. Namely, pdf_file is the blob and this is used in sendGridEmail as myPDFfile.
  • In this case, data of Utilities.base64Encode(data) is required to be Byte[].

When above point is reflected to your script, please modify as follows.

Modified script:

var cert = Utilities.base64Encode(myPDFfile);
var cert = Utilities.base64Encode(myPDFfile.getBytes());

Note:

If this is not the direct solution of your issue, how about testing the script by adding the header to the base64 data?

References: