Stefan van Aalst
Stefan van Aalst

Reputation: 778

Send attachement as Word document via Google Script

Via Google Spreadsheet I like to send an attachment. The attachment is a Google Doc.

I can sent it as PDF file.getAs('application/PDF') -- however I need it as a Word document (or something that opens up in Word).

It is possible to do send an email manually as Word attachment, however this solution requires to do this automatically.

I tried: application/vnd.openxmlformats-officedocument.wordprocessingml.document (http://en.wikipedia.org/wiki/Internet_media_type) but that doesn't work.

Kind regards

Stefan

Upvotes: 0

Views: 2274

Answers (1)

Serge insas
Serge insas

Reputation: 46802

Google Apps Script can't export anything else than pdf natively but the document API does so you can use urlFetch with parameters to get what you want (don't change these parameters, the request is anonymous and can stay so).

Here is the code, it doesn't require too much explanations except that the urlFetch must be authorized (the process is not the usual one, you'll get a second authorization for this script.)

function emailDocTestasDocx() {
  var id = '1I9KIVTLieQbNnmz09zfOBSBNwZ9Tp7B0kfpysaf-ooY';// an example of Google doc
  var url = 'https://docs.google.com/feeds/';
  var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=doc&format=doc&id='+id,
                              googleOAuth_('docs',url)).getBlob();
  var me = Session.getEffectiveUser().getEmail();
  MailApp.sendEmail(me, 'test', 'see attachment', {attachments:[doc]});
}

function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey('anonymous');
  oAuthConfig.setConsumerSecret('anonymous');
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}

Upvotes: 2

Related Questions