Using Google Script to send an email with a Word d

2019-09-03 16:29发布

问题:

I have a google script that sends an email with a Word doc as an attachment. It used to work until google deprecated OAuth 1.0

This is the line that's failing:

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

If I remove the second parameter, i.e. function call to OAuth, it should work? Why do I need to authenticate? It should be able to fetch the document using an ID from google drive. It appears to work (because I don't see any errors), however, when I get an email there is a corrupt word doc attachment.

So, I tried implementing OAuth 2.0. But I'm not getting anywhere. Here's my code:

function getDriveService() {
  return OAuth2.createService('drive')

      .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')

      .setClientId(CLIENT_ID)
      .setClientSecret(CLIENT_SECRET)

      .setCallbackFunction('authCallback')

      .setPropertyStore(PropertiesService.getUserProperties())

      .setScope('https://www.googleapis.com/auth/drive')
      .setParam('login_hint', Session.getActiveUser().getEmail())
      .setParam('access_type', 'offline');
      //.setParam('approval_prompt', 'force');
}

function authCallback(request) {
  var driveService = getDriveService();
  var isAuthorized = driveService.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this tab');
  }
}

var oauth2Service = getDriveService();
var token = oauth2Service.getAccessToken();
var parameters = { method : 'get',
                    headers : {'Authorization': 'Bearer '+ token}};

var options =
    {
      "method" : "get"
    };    

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

I'm getting a generic error [Access not granted or expired]. All I want is to be able to send an email with an attachment that is a document (format doc or docx) stored from my Google drive. Seems impossible! I'm able to attach this doc as a pdf but NOT a Microsoft document.

Any help will be greatly appreciated!

回答1:

https://github.com/googlesamples/apps-script-oauth2 - look at setup

...

Have you added OAuth 2.0 in the libraries?

Resources -> Libraries -> then add 'MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48'