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

2024-04-29

这是我之前发布的问题/答案的后续内容(如何使用 Google 电子邮件设置 API 和 OAuth2 for Apps 脚本库为 Google Apps 域中的用户设置电子邮件签名 https://stackoverflow.com/questions/30135119/how-to-use-the-google-email-settings-api-and-the-oauth2-for-apps-script-library/),但我正在创建一个新问题,因为电子邮件设置API https://developers.google.com/admin-sdk/email-settings/已被弃用,现在的过程有很大不同。

作为 G Suite 域的管理员,您如何使用邮箱API https://developers.google.com/gmail/api/v1/reference/通过 Google Apps 脚本以编程方式设置您域中用户的电子邮件签名?


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

Step 1:确保适用于应用程序脚本的 OAuth2 https://github.com/googlesamples/apps-script-oauth2库已添加到您的项目中。

Step 2:设置“域范围内的授权”。有一个页面here https://developers.google.com/drive/v2/web/delegation解释了如何为 Drive API 执行此操作,但对于任何 Google API(包括 Gmail API)来说几乎都是相同的。按照该页面上的步骤进行操作,直到“将域范围的权限委派给您的服务帐户”步骤(包括该步骤)。

Step 3:下面的代码包括如何在前面的步骤完成后设置签名:

function setSignatureTest() {

  var email = '[email protected] /cdn-cgi/l/email-protection';

  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);

}

请注意:do-while 循环与maxSetSignatureAttempts and currentSetSignatureAttempts变量不是必需的。我添加它是因为,如果您在创建 Google 帐户并分配 G Suite 许可证后尝试立即设置签名,有时 Gmail API 会返回错误,就好像用户尚未创建一样。如果出现错误,do-while 循环基本上会等待 3 秒,然后重试,最多 x 次。如果您为现有用户设置签名,则不应遇到此问题。另外,本来我只是固定10秒睡眠,但大多数时候不需要那么长时间,但其他时候仍然会失败。所以这个循环比固定的睡眠量要好。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐

  • VB.NET 使用 system.net.tcpclient 编写 telnet 客户端

    当我连接到我的Solaris盒子时这对我不起作用 服务器正在回传 有谁知道我做错了什么 Imports System Net Imports System Net Sockets Imports System Text Public Cla
  • 添加滑动删除UITableViewCell

    我正在制作一个清单应用程序UITableView 我想知道如何添加滑动删除UITableViewCell 这是我的 ViewController swift import UIKit class ViewController UIViewC
  • itunesconnect 应用程序 - 恢复到以前的版本

    我发布了我的应用程序的更新并获得批准 尽管它包含一个严重的本地化错误 大多数用户都得到了错误的语言 但它还是获得了批准 有什么方法可以快速恢复到以前的版本 暂停当前版本的当前下载 或者其他任何可能有助于解决此问题的方法 我几年前确实读过以下
  • nodejs 强大的改变 uploadDir

    我有一个项目正在努力完成我想上传图像 我可以上传图像 但不能上传应该上传的空中图像 好的 让我们编写代码 app post register function req res var form new formidable Incoming
  • Android 中客户端服务器通信的选项

    我目前正处于论文项目的研究阶段 我的项目是一个针对移动设备的订票系统 我选择以 Android 为目标 我预计需要带有中央服务器的客户端 服务器架构 因此目前正在研究 Android 如何与这样的服务器进行通信 服务器将授予客户端访问票务信
  • 观察嵌套对象的属性

    小提琴示例 http emberjs jsbin com aviyUnA 9 edit html js 输出 http emberjs jsbin com aviyUnA 9 edit html js output 这是我的模型 name
  • 使用参与者模型进行基于时间的模拟

    我们有一个单线程应用程序 可以模拟数十万个对象随着时间的推移与共享内存模型的交互 显然 它无法在多 CPU 硬件上进行扩展 在阅读了一些有关基于代理的建模和函数式编程 参与者模型的内容后 我正在考虑使用消息传递范例进行重写 这个想法非常简单
  • 为开发/QA/产品配置 Java EE 6

    我有一个使用 Maven 构建的 Java EE 6 应用程序 在 NetBeans 7 中编写代码并部署在 GlassFish 3 1 2 上 当我接近完成时 我发现自己正在部署演示版本 问题是我没有任何非常简单的方法来构建不同的环境 例
  • ModemManager:mmcli 获取信号强度

    我无法检索 Sierre Wireless MC7304 上的信号强度 另外通过 mmcli 发送 AT 命令似乎不起作用 sudo mmcli m org freedesktop ModemManager1 Modem 0 signal
  • jquery 切换兄弟元素的可见性

    我在一个页面上有几个 div 每个 div 都有一个标题 我可以单击该标题来切换相应 div 的可见性 div 设置为display none默认情况下 我用过 ids在每个 div 的点击功能中 但是因为我在同一页面上有多个 div 我想
  • Typescript:声明与另一个变量具有相同类型的变量

    有没有办法用另一个变量的类型来声明一个变量 例如 我声明一个具有某种类型的类成员 然后我想在同一类型的函数中声明另一个变量 但我不想修改原来的声明 也不想重复它 看起来你应该能够做类似的事情 class Foo bar key string
  • 如何从扩展服务工作人员创建网络工作人员

    我将首先解释我想要实现的目标 我想创建一个扩展程序 可以在不同 chrome 窗口上的选项卡之间切换 并显示每个选项卡 X 时间 我发现了一个类似的扩展 但它是使用manifest V2完成的 并且不支持多个窗口 我想通过为每个窗口创建一个
  • Nestjs拦截并修改传出的http请求

    所以我可能错过了一些东西或者做错了一些事情 我有一个 NestJS 应用程序正在尝试向外部 API 发出 http 请求 我希望能够拦截此传出请求并在执行之前修改其标头 我尝试使用拦截器 但没有成功 传入的 http 请求被拦截 但传出的请
  • 由于权限被拒绝,无法绑定到某些端口

    在过去 3 个月左右的时间里 我遇到了随机错误 无法绑定身份服务器在本地开发工作站上运行的特定端口 起初我以为是我的机器坏了 所以我重置了所有东西 这在两个月内解决了这个问题 现在它又回来了 与此同时 其他开发人员也看到了同样的问题 我们所
  • Eclipse 调试器 - 跳转到或仅显示挂起的线程

    我有一个带有很多线程的 Java 应用程序 在调试时 当一个线程中的执行被断点停止时 在所有线程之间滚动以查找挂起的线程是非常烦人的 有没有办法 按钮 快捷键等 跳转到挂起的线程 或者更好 隐藏所有未挂起的线程 我同意这很烦人 而且答案非常
  • Python Pandas 检查某个值在同一天内是否出现多次

    我有一个 Pandas 数据框 如下所示 我想做的是检查一个电台是否有变量yyy以及同一天的任何其他变量 如station1 如果这是真的 我需要删除包含的整行yyy 目前我正在使用iterrows 并循环搜索该变量出现的日期 将变量更改为
  • django redis celery 和 celerybeats 的正确设置

    我一直在尝试设置 django celery redis celery beats 但它给我带来了麻烦 文档非常简单 但是当我运行 django 服务器 redis celery 和 celerybeats 时 没有打印或记录任何内容 我所
  • 如何使用ggplot2在地图上添加经度和纬度线?

    我现在正在使用绘制加拿大地图ggplot2 因为默认的投影方式是 aea 阿尔伯斯等积 所以地图上的经度和纬度都是直线 我想知道如何在地图上以 110W 100W 90W 和 50N 60N 70N 的形式显示经度和纬度 它们应该是曲线 多
  • 如何使用rest-api执行spring cloud任务

    我知道可以安排云任务 也可以使用要执行的流进行配置 作为一名开发人员 我想使用 Rest api 执行我的 Spring Cloud 任务 以便我可以按需执行任务 基本上我有一个工作流程管理系统 我们正在使用 control m 代理 所以
  • 如何使用 Gmail API、OAuth2 for Apps 脚本和域范围委派为 G Suite 域中的用户设置电子邮件签名

    这是我之前发布的问题 答案的后续内容 如何使用 Google 电子邮件设置 API 和 OAuth2 for Apps 脚本库为 Google Apps 域中的用户设置电子邮件签名 https stackoverflow com quest