Google Workspace GMail API 为模拟帐户创建标签

问题描述 投票:0回答:1

我是 Google Workspace 超级管理员,拥有全域委派和服务帐号设置。使用 Apps 脚本,我尝试向模拟用户添加标签(这意味着我无法使用 GMailApp 客户端)。我已成功阅读消息并从消息中删除标签),因此我确信我已解决权限问题。

我在这里引用API:https://developers.google.com/gmail/api/reference/rest/v1/users.labels/create

并遵循此处的模型:https://github.com/googleworkspace/apps-script-oauth2/blob/main/samples/Google.gs

这是我的代码:

/**
 * Adds a label to the account
 */
function addLabel(){

  USER_EMAIL = "[email protected]"; // Set the user to be impersonated

  var service = getService_();
  if (service.hasAccess()) {
    var url = 'https://gmail.googleapis.com/gmail/v1/users/me/labels';
    var response = UrlFetchApp.fetch(url, {
      headers: {
        Authorization: 'Bearer ' + service.getAccessToken()
      },
      payload: {
        "name": "New Label",
        "messageListVisibility": "show",
        "labelListVisibility": "labelShow"
      }

    });
    var result = JSON.parse(response.getContentText());

  } else {
    Logger.log(service.getLastError());
  }
  return "";
}

/**
 * Configures the mail service for the user to be impersontated
 */
function getService_() {
  return OAuth2.createService('GMail:' + USER_EMAIL)
      // 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(USER_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('https://mail.google.com/');
}

我总是收到错误代码 400,无效请求,状态为 INVALID_PARAMETER。如果删除有效负载,我将不再收到错误(但当然它不会添加标签)。

请问有什么想法吗?

google-apps-script label gmail-api google-workspace
1个回答
0
投票

我真的不明白我的初始代码到底出了什么问题,但这现在对我有用:

/**
 * Adds a label to the account
 */
function addLabel(){

  var data = {
    'name': 'New Label',
    'messageListVisibility': 'show',
    'labelListVisibility': 'labelShow'
  };

  USER_EMAIL = "[email protected]"; // Set the user to be impersonated

  var service = getService_();
  if (service.hasAccess()) {
    var url = 'https://gmail.googleapis.com/gmail/v1/users/me/labels';
    var response = UrlFetchApp.fetch(url, {
      'method': 'post',
      'headers': {
        Authorization: 'Bearer ' + service.getAccessToken()
      },
      'contentType': 'application/json',
      'payload': JSON.stringify(data)

    });
    var result = JSON.parse(response.getContentText());

  } else {
    Logger.log(service.getLastError());
  }
  return "";
}
© www.soinside.com 2019 - 2024. All rights reserved.