Search code examples
javascriptpdfgoogle-apps-scriptgmailgoogle-docs

PDF attachment sent with Gmail of Google doc is blank


My goal is to attach a PDF version of a google doc in a Gmail attachment. I have generated the document with apps script and saved it in a folder in Drive. The email is sent with an attachment in PDF, but the pdf file contains nothing (it is completely blank). The relevant code I'm using:

 var blob = DriveApp.getFileById(docID).getAs("application/pdf"); // problem line?

 GmailApp.sendEmail(clientEmail, 'subject', 'Please see the attached file.', { 
       attachments: [blob],
       name: 'Automatic Emailer Script',
   });

And I have already tried using the code from Google here:

var file = DriveApp.getFileById(docID);
MailApp.sendEmail(clientEmail, 'Attachment example', 'Please see attached.', {
    name: 'Automatic Emailer Script',
    attachments: [file.getAs(MimeType.PDF)]  // something going on here?
});

In both instances I recieve an email with a PDF attachement with the correct filename, but it is completely blank and doesn't contain the content of the (google doc) document it was supposedly generated from. Am I missing something when creating the blob? Are there document-specific parameters I need to correctly generate the blob?

I'm obviously missing something - sorry if it is very obvious!


Solution

  • The solution has been found on this post:

    Google apps script: Create a new document and send it using Gmail

    The document has to be saved one time to be able to be emailed.

    Using the function saveAndClose() on the script saves the document before sending it in case you want to send a newly generated document.