How to Attach Doc/Word file as attachment using Google appscript?

I am new to GAS, Can anyone please tell me how to send Google Doc File as an attachment using appscript. I know how to send as PDF but I need the Doc File to get attached as Word File from Google Drive.

What I am trying to do is fill a template doc file with data from google sheet with onEdit trigger and attach the new file as a document attachment.

function davitFill(e) {

 if (e.range.columnStart != 19 || e.value != "Yes") return;
 const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1xEEEiLfil1qfetSwZRhr02Q9uoXvWtCxq22JywTu5mo/edit#gid=1554622983").getSheetByName("TDataBase");
 const rData = ss.getRange(e.range.rowStart,1,1,19).getValues();
 var fname = rData[0][1];
 var add = rData[0][3];
 var dist = rData[0][4];
 var state = rData[0][5];
 var pc = rData[0][6];
 var brand = rData[0][10];
 var cal = rData[0][16];
 var email = rData[0][2];

 var tfile = 
 DriveApp.getFileById("1xMWm2CBA2vLkf5GzFQnHRViLVoJZdbebazUgp0OipV4");
 var savefol = DriveApp.getFolderById("1RzjCSdKU9lwxdonGPBPpIob4KVZ2z80-R");
 var tfolder = DriveApp.getFolderById("1MgmGTCf-_RYBZOHloIYJP_9C68kF67I9H");

 const tempFile = tfile.makeCopy("davit for "+fname, folder);
 const tempDocFile = DocumentApp.openById(tempFile.getId());
 const body = tempDocFile.getBody();
  body.replaceText("{{Full name}}", fname);
  body.replaceText("{{Brand}}", brand);
  body.replaceText("{{Address}}", add);
  body.replaceText("{{Dist}}", dist);
  body.replaceText("{{Class}}", cal);
  body.replaceText("{{State}}", state);
  body.replaceText("{{pc}}", pc);
  var ffile = tempDocFile.saveAndClose();


  var url = tempDocFile.exportLinks[MimeType.MICROSOFT_WORD];
  var oauthToken = ScriptApp.getOAuthToken();

  var blob = UrlFetchApp.fetch(url, {
  headers: {
  'Authorization': 'Bearer ' + oauthToken
  }
  }).getBlob().setName(docFile.title+'.docx');

  MailApp.sendEmail('email', 'WORD ATTACHMENT', 'Test', {attachments: blob});

}



Read more here: https://stackoverflow.com/questions/65724295/how-to-attach-doc-word-file-as-attachment-using-google-appscript

Content Attribution

This content was originally published by Ovais Majid at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: