Search code examples
google-apps-scriptgmailgoogle-oauthgmail-api

Gmail API call returning blank with no errors, but not applying change for delegate creation


I'm trying to call the Gmail API in App Script while impersonating a user account using Google's Oauth2 library for App Script to set a delegate for their inbox. Using Google's examples as a base, I created the following function to call the service and provide the right information to create a new Delegate on an inbox:

function setGmailDelegate() {
  var formObject = {
    delegateReaderEmail: "[email protected]",
    delegateTargetEmail: "[email protected]"
  };

  var userEmail = formObject.delegateReaderEmail;
  var boxEmail = formObject.delegateTargetEmail;
  Logger.log("Letting "+userEmail + " read " + boxEmail);

  var service = getGmailAddDelegateService_(boxEmail);
  if (service.hasAccess()) {
    var url = 'https://www.googleapis.com/gmail/v1/users/' + boxEmail +'/settings/delegates';
    var response = UrlFetchApp.fetch(url, {
      headers: {
        Authorization: 'Bearer ' + service.getAccessToken()
      },
      body: {
        "delegateEmail": userEmail,
        "verificationStatus": "accepted"
      }
    });
    var result = JSON.parse(response.getContentText());
    Logger.log(result);
  } else {
    Logger.log(service.getLastError());
  }
}

This function returns nothing - there's no error message but the delegate is not created. According to the API I should be getting a delegates resource back but I'm not. What am I doing wrong?

This is the function that defines the OAuth service creation:

function getGmailAddDelegateService_(boxEmail) { 
  return OAuth2.createService('Gmail:' + boxEmail)
      // Set the endpoint URL.
      .setTokenUrl('https://oauth2.googleapis.com/token')

      // Set the private key and issuer.
      .setPrivateKey(PRIVATE_KEY)
      .setIssuer(CLIENT_EMAIL)

      // Set the name of the user to impersonate.
      .setSubject(boxEmail)

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getScriptProperties())

      // Set the scope. This must match one of the scopes configured during the
      // setup of domain-wide delegation.
      .setScope(['https://mail.google.com/','https://www.googleapis.com/auth/gmail.settings.sharing']);
}

I've tried changing the scopes around but to no avail. I can't see anything in the execution logs of the G Suite audit logs that point to any issues.


Solution

  • Found the answer: URLApp requires that your specify you're POSTing data:

    var response = UrlFetchApp.fetch(url, {
          method: 'post',
          headers: {
            Authorization: 'Bearer ' + service.getAccessToken()
          },
          body: {
            "delegateEmail": userEmail,
            "verificationStatus": "accepted"
          }