I'm trying to add a user to a Google Group using Google Apps Script.
Here's the code I've tried:
// Adds a user to a Google Group
function addUsertoGroup(userEmail) {
var userEmail = 'Name@gmail.com'
var groupEmail = "group-name@domain.com"; // you can only add users with a script to groups in your domain.com (not googlegroups.com)
var group = GroupsApp.getGroupByEmail(groupEmail);
// 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, groupEmail);
When running, I receive an error:
API call to directory.groups.get failed with error: Domain not found.
Any help would be appreciated.
Clarification:
AdminDirectory
function (or to have the ability to add users to a group via Apps Script.gmail
or any other non-same domain users based on the group setting you configure via https://groups.google.comSolution:
I have a G Suite account via script.gs
and I tested the code that you've shared - its perfect :) Except for the following that you need to enable, from a G Suite account.
Navigate to Resources > Advanced Google Services... and enable Admin Directory API
That's it. I created the group, enabled all settings, made the group accessible to everyone and it worked like a charm.
Let me know if you require any further clarification or assist as well.
Edit notes:
So, this is also what I had to follow to ensure everyone (even folks outside the domain could be added as users), as documented on Set Groups for Business sharing options. When you go to Groups for Business and navigate through the settings, you'd get to enable the following option that's critical -
Obviously, you're free to tweak all the other settings, as required.