如何使用Gmail API,OAuth2 for Apps脚本和域范围委派为G Suite域中的用户别名设置电子邮件签名

时间:2017-12-21 21:48:53

标签: email google-apps-script gmail-api google-apps google-oauth2

这是此问题的延续:How to use the Gmail API, OAuth2 for Apps Script, and Domain-Wide Delegation to set email signatures for users in a G Suite domain

它展示了一种使用Oauth2,Apps脚本和域范围委派为另一个帐户设置签名的方法。

但是,当我遇到这种情况时,它对我不起作用:我在G-Suite帐户中有一个域别名,其中myuser@aliasdomain.com是myuser@maindomain.com的别名。我想为myuser@aliasdomain.com设置签名。先前问题的示例仅执行myuser@maindomain.com。

有可能吗?

我试过这个(从先前问题的示例代码修改):

var credentials = {
  "type": "service_account",
  "project_id": "project-id-4606494xxxxxxxxx3",
  "private_key_id": "8481966716a20fe34615daxxxxxxxxa",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXbOAiODt\n-----END PRIVATE KEY-----\n",
  "client_email": "xxxxxxxxxxxx@project-id-46064949xxxxxxxxxxxx.iam.gserviceaccount.com",
  "client_id": "112076306220190xxxxxxxxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxxxxxxx%40project-id-4606494951xxxxxxxxxxxxxx.iam.gserviceaccount.com"
}

function setSignatureTest() {

  var loginEmail = 'myuser@maindomain.com';
  var sendAsEmail = 'myuser@aliasdomain.com';

  var signature = 'test for awesome signature';

  var test = setSignature(loginEmail, sendAsEmail, signature);

  Logger.log('test result: ' + test);

}


function setSignature(loginEmail, sendAsEmail, signature) {

  Logger.log('starting setSignature');

  var signatureSetSuccessfully = false;

  var service = getDomainWideDelegationService('Gmail: ', 'https://www.googleapis.com/auth/gmail.settings.basic', loginEmail);

  if (!service.hasAccess()) {

    Logger.log('failed to authenticate as user ' + loginEmail);

    Logger.log(service.getLastError());

    signatureSetSuccessfully = service.getLastError();

    return signatureSetSuccessfully;

  } else Logger.log('successfully authenticated as user ' + loginEmail);

  var resource = { signature: signature };

  var requestBody                = {};
  requestBody.headers            = {'Authorization': 'Bearer ' + service.getAccessToken()};
  requestBody.contentType        = "application/json";
  requestBody.method             = "PUT";
  requestBody.payload            = JSON.stringify(resource);
  requestBody.muteHttpExceptions = false;

  var loginEmailForUrl = encodeURIComponent(loginEmail);
  var sendAsEmailForUrl = encodeURIComponent(sendAsEmail);

  var url = 'https://www.googleapis.com/gmail/v1/users/' + loginEmailForUrl + '/settings/sendAs/' + sendAsEmailForUrl;

  var maxSetSignatureAttempts     = 10;
  var currentSetSignatureAttempts = 0;

  do {

    try {

      currentSetSignatureAttempts++;

      Logger.log('currentSetSignatureAttempts: ' + currentSetSignatureAttempts);

      var setSignatureResponse = UrlFetchApp.fetch(url, requestBody);

      Logger.log('setSignatureResponse on successful attempt:' + setSignatureResponse);

      signatureSetSuccessfully = true;

      break;

    } catch(e) {

      Logger.log('set signature failed attempt, waiting 3 seconds and re-trying');

      Utilities.sleep(3000);

    }

    if (currentSetSignatureAttempts >= maxSetSignatureAttempts) {

      Logger.log('exceeded ' + maxSetSignatureAttempts + ' set signature attempts, deleting user and ending script');

      throw new Error('Something went wrong when setting their email signature.');

    }

  } while (!signatureSetSuccessfully);

  return signatureSetSuccessfully;

}


function getDomainWideDelegationService(serviceName, scope, email) {

  Logger.log('starting getDomainWideDelegationService for email: ' + email);

  return OAuth2.createService(serviceName + email)
      // Set the endpoint URL.
      .setTokenUrl(credentials.token_uri)

      // Set the private key and issuer.
      .setPrivateKey(credentials.private_key)
      .setIssuer(credentials.client_email)

      // Set the name of the user to impersonate. This will only work for
      // Google Apps for Work/EDU accounts whose admin has setup domain-wide
      // delegation:
      // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
      .setSubject(email)

      // 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(scope);

}

它的工作原理是我将loginEmail和sendAsEmail设置为loginEmail,但设置为域别名时则不行。

我很感激任何想法/帮助。

感谢。

0 个答案:

没有答案