google-apps-scripturlfetchgoogle-data-api

Sending attachment in Word format does not work in Google Script


I've been able to send attachment in PDF format successfully but when I try to send attachment in Word format, I get this error:

"Request failed for https://docs.google.com returned code 404. Truncated server response:

I've tried several ways suggested in this site but I just couldn't make it work.

Will very much appreciate any help on this topic. I'm a newbie in Google Script.

Here's my code:

//=================================================
//  Email Employment Letter as Word format, not PDF
//=================================================

function EmailCertAsWordDoc(requestor, name, newCopyID) {
  var email = requestor; 
  var id = DocumentApp.openById(newCopyID);
  var subject = "Auto-generated Employment Letter"; 
  var body = "\n\nAttached is the Employment Letter that you created for " + name + ". \n\n\n\n\n ";

  var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&format=docx&access_token=" + ScriptApp.getOAuthToken();
  var docx = UrlFetchApp.fetch(url).getBlob();

  if (MailApp.getRemainingDailyQuota() > 0) 
    GmailApp.sendEmail(email, subject, {
      Body: body,
      attachments:[docx]     
    });
}


Solution

  • Two things:

    1. To obtain the export url, you need to use the file id, no the file itself - in your case it is newCopyID

    2. Sending word files as attachments is unfortunately a little bit more complicated than pdfs. To make it work, you can create a word file on your drive, and then send it as an URL within your email body.

    Sample:

    function EmailCertAsWordDoc(requestor, name, newCopyID) {
      var email = requestor; 
      var fileName = DocumentApp.openById(newCopyID).getName();
      var subject = "Auto-generated Employment Letter"; 
      var body = "\n\nAttached is the Employment Letter that you created for " + name + ". \n\n\n\n\n ";
    
      var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + newCopyID + "&format=docx&access_token=" + ScriptApp.getOAuthToken();
      var docx = UrlFetchApp.fetch(url).getBlob();
      var file=DriveApp.createFile(docx).setName(fileName).getUrl();
      body+=" "+file;
      if (MailApp.getRemainingDailyQuota() > 0) 
        GmailApp.sendEmail(email, subject, body);
    }