Search code examples
google-apps-scriptgoogle-workspace

Why is getBlob() in Google Apps Script not fetching the latest version of the document?


I am developing a Google Apps Script application that, when a form is submitted, takes the data from Google Sheets and inserts it into a Google Doc, which is then sent to the person who submitted the form. All of the code works correctly, except the part where the Doc is attached to the email.

The code

MailApp.sendEmail({
    to: email,
    subject: "Subject line",
    body: "Body",
    attachments: [doc.getBlob()]
  })

What I expect to happen

The program, after injecting the data into the Doc, should convert the current document to a PDF and email it.

What actually happens

The PDFs that are sent out are not the latest versions of the Doc. For example, they could have data from a previous test run. It appears that Apps Script is somehow caching the blobs of the document. It is important to note that the data is actually being injected into the document: when I open the file, it shows me the data from the latest form submit.

Can someone tell me a way to get a blob of the latest doc, or a way to clear the cache for the blob?


Solution

  • You need to flush and apply the pending changes with saveAndClose().

    Try this:

    doc.saveAndClose();
    
    MailApp.sendEmail({
        to: email,
        subject: "Subject line",
        body: "Body",
        attachments: [doc.getBlob()]
      })