使用 Google Apps 脚本将用户添加到 Google 组

Add users to Google Group using Google Apps Script

我正在尝试使用 Google Apps 脚本将用户添加到 Google 群组。

这是我试过的代码:

// Adds a user to a Google Group
function addUsertoGroup(userEmail) {
  var userEmail = 'Name@gmail.com'
  var groupId = "group-name@googlegroups.com";
  var group = GroupsApp.getGroupByEmail(groupId);

  // If email is already in group
  try { var hasMember = group.hasUser(userEmail);}
  catch(e){Logger.log(userEmail+" is already in the group"); return}

  var newMember = {email: userEmail, role: "MEMBER"};

  // This is the line which is throwing an error
  AdminDirectory.Members.insert(newMember, groupId);

当 运行 时,我收到一个错误:

API call to directory.groups.get failed with error: Domain not found.

如有任何帮助,我们将不胜感激。

澄清:

  • 您需要一个 G Suite 帐户才能使用 AdminDirectory 功能(或能够通过 Apps 脚本将用户添加到群组。
  • 您可以根据您通过 https://groups.google.com
  • 配置的组设置添加 gmail 或任何其他非同一域用户

解决方法:

我通过 script.gs 拥有一个 G Suite 帐户,我测试了您共享的代码 - 非常完美 :) 除了您需要从 G Suite 帐户启用以下内容。

导航至资源>高级Google服务...并启用管理目录API

就是这样。我创建了群组,启用了所有设置,让每个人都可以访问群组,而且效果非常好。

如果您还需要任何进一步的说明或帮助,请告诉我。

编辑笔记:

所以,这也是我必须遵循的,以确保 每个人 (甚至可以将域外的人添加为用户),如 Set Groups for Business sharing options. When you go to Groups for Business 和浏览设置,您将启用以下关键选项 -

显然,您可以根据需要自由调整所有其他设置。

您正在尝试使用 AdminDirectory 服务,该服务仅适用于 G Suite 域中的 G Suite 管理员。因此,您需要拥有自己的域,如果您将域中的用户添加到域中的一组,它就会起作用。

即用户@domain.com 添加到组@domain.com

根据您的示例代码,您尝试将 gmail.com 用户添加到 public Google 组,但您不能使用管理目录 API 因为您不是管理 public 组的域的管理员。

并且在这种情况下,就像您所做的那样,您只能使用 GroupsApp 服务,并且该服务只允许您检查用户是否在 ggroups 中或角色是什么。

=> 使用 GroupsApp 服务无法将用户添加到 public google 组。

史蒂芬