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.