适用于Apps脚本的电子邮件设置API和OAuth2:您无权访问此API(错误403)

时间:2018-04-17 23:05:20

标签: google-apps-script gmail-api google-oauth2 google-admin-sdk

我了解电子邮件设置API已弃用,将在2018年秋季关闭。但是,我需要创建一个代理域用户的脚本(作为管理员),而新的Gmail API不支持授权功能。

我将OAuth2库用于Google Apps脚本。我为该项目创建了一个服务帐户。我为服务帐户委派了域范围的委派权限。我在管理控制台中添加了范围“https://apps-apis.google.com/a/feeds/emailsettings/2.0/”。

Scope

OAuth2.0代码有效。我用它来成功设置域用户的签名。

但是,当我尝试使用以下代码添加带有Email Settings API的委托时,我收到此消息:

Error 403

您是否无法再访问已弃用的电子邮件设置API?任何指针都会受到赞赏。谢谢!

function addDelegate() {
  var email = "delegator@domain.com"
  var domainName = "domain.com"; 
  var username = email.split("@")[0];
  
  var authorizationScope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/';
  
  var service = getDomainWideDelegationService("Email Settings API:", authorizationScope, email);

  if (!service.hasAccess()) {
    Logger.log("failed to authenticate as user " + email);
    Logger.log(service.getLastError());
  } else {
    Logger.log("successfully authenticated as user " + email);
  }
  
  var xml = '<?xml version="1.0" encoding="utf-8"?>' + 
            '<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">' + 
              '<apps:property name="address" value="delegate@domain.com" />' + 
            '</atom:entry>';
       
  var base = "https://apps-apis.google.com/a/feeds/emailsettings/2.0/";

  var fetchArgs                = {};
  fetchArgs.headers            = {"Authorization": "Bearer " + service.getAccessToken()};
  fetchArgs.method             = "POST";
  fetchArgs.contentType        = "application/atom+xml";
  fetchArgs.payload            = xml;
  fetchArgs.muteHttpExceptions = true;
       
  var url = base + domainName + "/" + username + "/delegation";
  
  try {
    var response = UrlFetchApp.fetch(url, fetchArgs);     // Add delegate
    Logger.log("response = %s ", response.getContentText());
  } catch (e) {
    Logger.log("Add delegate failed: " + e);
  }
}

0 个答案:

没有答案