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

时间:2016-12-02 15:59:21

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

这是我发布的上一个问题/答案(How to use the Google Email Settings API and the OAuth2 for Apps Script Library to set email signatures for users in a Google Apps domain)的后续内容,但由于Email Settings API已被弃用,因此我创建了一个新问题过程现在有了很大的不同。

作为G Suite域的管理员,您如何使用Gmail API以编程方式通过Google Apps脚本设置域中用户的电子邮件签名?

1 个答案:

答案 0 :(得分:6)

此方法使用Gmail API,OAuth2 for Apps脚本库和"域范围的授权和#34;这是G Suite管理员代表其内部用户进行API调用的一种方式域。

第1步:确保OAuth2 For Apps Script库已添加到您的项目中。

第2步:设置"域范围的授权。"有一个页面here解释了如何为Drive API执行此操作,但对于任何Google API(包括Gmail API)来说几乎都是一样的。按照该页面上的步骤进行操作,并将“域名范围内的权限委派”授予您的服务帐户"步骤

第3步:以下代码包含在完成上述步骤后如何设置签名:

function setSignatureTest() {

  var email = 'test@test.com';

  var signature = 'test signature';

  var test = setSignature(email, signature);

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

}


function setSignature(email, signature) {

  Logger.log('starting setSignature');

  var signatureSetSuccessfully = false;

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

  if (!service.hasAccess()) {

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

    Logger.log(service.getLastError());

    signatureSetSuccessfully = service.getLastError();

    return signatureSetSuccessfully;

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

  var username = email.split("@")[0];

  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 emailForUrl = encodeURIComponent(email);

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

  var maxSetSignatureAttempts     = 20;
  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;

}

// these two things are included in the .JSON file that you download when creating the service account and service account key
var OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY  = '-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n';
var OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL = 'xxxxxxxxxxxxxxxxxxxxx.iam.gserviceaccount.com';


function getDomainWideDelegationService(serviceName, scope, email) {

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

  return OAuth2.createService(serviceName + email)
      // Set the endpoint URL.
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')

      // Set the private key and issuer.
      .setPrivateKey(OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY)
      .setIssuer(OAUTH2_SERVICE_ACCOUNT_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);

}

请注意:不需要包含maxSetSignatureAttemptscurrentSetSignatureAttempts变量的do-while循环。我添加了它,因为如果您在创建Google帐户并分配G Suite许可后立即尝试设置签名,则有时Gmail API会返回错误,就像用户尚未创建一样。 do-while循环基本上等待3秒,如果它出错,然后再次尝试,最多x次。如果您为现有用户设置签名,则不应该遇到此问题。此外,最初我只有一个固定的10秒睡眠,但大部分时间它不需要花那么长时间,但有时它仍然会失败。因此,这个循环优于固定的睡眠量。