Search code examples
javascriptgoogle-workspace

email a docx file with googlescript


I'm only a beginner with using google script, so please be kind if this is a very stupid question :)

My script currently e-mails a pdf, created from a google drive file like this:

var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");

I'd like to also e-mail a docx file, but of course it's less easy. I found one way to do this:

Using Google Script to send an email with a Word doc attachment

... but it seems to use an old solution which no longer works. Code:

var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=doc&format=doc&id='+copyId,
googleOAuth_('docs',url)).getBlob();

Error:

Execution failed: ReferenceError: "googleOAuth_" is not defined.

Am I using the right method but with a mistake, or is there a better method to export a docx?

Thanks very much for your help and patience!


Solution

  • If you are still looking for the solution, how about this answer? In order to convert Google Document to docx and export docx, please use access token. In your case, you can use ScriptApp.getOAuthToken() for the access token. So how about the following modification?

    From :

    var url = 'https://docs.google.com/feeds/';
    var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=doc&format=doc&id='+copyId,
    googleOAuth_('docs',url)).getBlob();
    

    To :

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

    Note :

    • You can use the access token as a query parameter.
    • In your question, you want a docx file. But in your script, it seems that you want a doc file.
      • In this modification, the docx is used. If you want a doc file, please modify it.
    • At the modified script, docx is the blob of docx. Please use this instead of pdf of your script.

    If I misunderstand your question, I'm sorry.

    Updated: February 7, 2020

    From January, 2020, the access token cannot be used with the query parameter like access_token=###. Ref So please use the access token to the request header instead of the query parameter. It's as follows.

    var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});