Is it possible to get all domain email addresses (#example.com) to a variable? (the domain is of course connected with Gmail). I was searching and have found just ContactsApp class, which can give contacts from address books, but I need all company's email addresses.
To get user information like this for your entire domain, you need to use the Admin SDK Directory API. You will need to query Google Apps for your domain's users.
var optionalArgs = {"customer":"my_customer"},
response,
users = []
;
response = AdminDirectory.Users.list(optionalArgs);
users = response.users;
This will get you your first page of users, so you may need to create a loop to fetch all of them. You will need to understand the User resource, which is returned for each of your users. Both their primary domain email and their aliases can be found in this resource:
var email,
aliases
;
email = users[0].emails[0]; // if email.primary is true, email.address is the primary domain email for this user
aliases = users[0].aliases; // list of user's alias email addresses
More information can be found in the documentation
This is the function to get all the users email address list in appscript .
function listAllUsers1() {
var pageToken;
var page;
do {
page = AdminDirectory.Users.list({
domain: 'abc.com',
orderBy: 'givenName',
maxResults: 100,
pageToken: pageToken,
});
var users = page.users;
Logger.log(users);
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
Logger.log(user);
Logger.log('%s (%s)', user.name.fullName, user.primaryEmail);
}
} else {
Logger.log('No users found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
}
Related
I have a script (using Google Apps Script) that uses the Contacts API to pull the emails from a contactgroup, then sends an email to the group of contacts. Attempting to convert to the PeopleAPI and cannot seem to replicate the functionality. Here's the relevant script sample with the working ContactsAPI code included but commented out:
function sharereport() {
//var CGroup = ContactsApp.getContactGroup('group_name');
//var Dist = CGroup.getContacts();
var CGroup = People.ContactGroups.get('contactGroups/498ba6e40f63a476')
var Dist = People.People.getBatchGet('CGroup','people.email_addresses');
.
.
.
for (var i = 0; i < Dist.length; i++) {
var nextemail = Dist[i].getEmails();
var usethisemail = nextemail[0].getAddress();
Drive.Permissions.insert(
// #ts-ignore
{
'role': 'writer',
'type': 'user',
'value': usethisemail,
},
MyID,
{
'sendNotificationEmails': 'false',
});
MailString = MailString + ',' + usethisemail;
};
I'm sure I'm missing something really simple here to get the PeopleAPI to return an array of contacts that I can get the email addresses out of so I can populate the drive permissions and email to: field.
Since I did not found any methods getting them directly, I did use People.People.Connections.list and filtered the data till I get the emails. This should what your code will look like.
function sharereport() {
var CGroup = ContactsApp.getContactGroup('label1');
var Emails = CGroup.getContacts().map(function (contact) {
return contact.getEmailAddresses();
});
// Show emails of people belonging to the group label1
Logger.log(Emails);
var PGroup = People.People.Connections.list('people/me', {
personFields: 'emailAddresses,memberships'
});
// resource name of label1
var resourceName = 'contactGroups/7086c0fa8e7b006b';
var Emails2 = [];
PGroup.connections.forEach(function (person) {
person.memberships.forEach(function (membership) {
if (resourceName == membership.contactGroupMembership.contactGroupResourceName) {
var addresses = [];
person.emailAddresses.forEach(function (emailAddress){
// people can have multiple email addresses, add them all
addresses.push(emailAddress.value);
});
Emails2.push(addresses);
}
});
});
Logger.log(Emails2);
}
Behavior:
get all the people connections under you.
get all their memberships
check if their memberships resource name is equal to the one you want. (they can belong to multiple memberships)
loop all emails of that certain person (they can have multiple emails), then push into one array.
push that array into final array containing all emails of all people belonging to the resource name.
Output:
Logged both ContactsApp and People API results, below shows that they were the same.
Resources:
people.connections/list
advanced/people
Here's a more efficient way of doing what you want:
var group = People.ContactGroups.get('contactGroups/50e3b0650db163cc', {
maxMembers: 25000
});
Logger.log("group: " + group);
var group_contacts = People.People.getBatchGet({
resourceNames: group.memberResourceNames,
personFields: "emailAddresses"
});
Logger.log("emails: " + group_contacts.responses.map(x => {
var emailObjects = x.person.emailAddresses;
if (emailObjects != null) {
return emailObjects.map(eo => eo.value);
}
}));
First call gets all the group's members (resourcesNames AKA contactIds)
Second call gets all the members' email-addresses.
Then we just get the actual value of the email from the response (via map)
I need to find USER_ID of all the users in our current organization. We have Google Workspace - Basic plan and have 120+ users.
Please refer here for what USER_ID I'm talking about
https://developers.google.com/hangouts/chat/reference/message-formats/basic#messages_that_mention_specific_users
What is the easiest way to fetch the USER_ID? The solution can be something like where Google Sheet is updated with the new user and its USER_ID.
Answer
It is not possible to get this USER_ID of all the users in a specific domain. This is what the documentation says about this id:
To determine the USER_ID for a user, examine the sender field of the incoming message from the user.
Also, if you were to use the space.members.list method to get a membership (or a user) resource, they do not contain any id.
Work around
There is a sample code in the documentation that shows how to get all the users in a Google Workspace domain. I have modified it to get the user ids and finally create a Sheet with all the information.
Code
function listAllUsers() {
var pageToken;
var page;
var userList = []
do {
page = AdminDirectory.Users.list({
domain: 'example.com',
maxResults: 100,
pageToken: pageToken
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
userList.push([user.id, user.name.fullName, user.primaryEmail])
Logger.log('u:%s, %s (%s)', user.id, user.name.fullName, user.primaryEmail);
}
} else {
Logger.log('No users found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
var nusers = userList.length
var ss = SpreadsheetApp.create('usersList')
ss.getActiveSheet().getRange(1,1,nusers,3).setValues(userList)
console.log(ss.getUrl())
}
References
Admin SDK Directory Service: List all users
Chat API: Method spaces.members.list
Chat API: Resource Membership
Chat API: Resource User
I have users in our Gsuite domain who use several email aliases. I need to setup different email signatures depending on the sender email alias. Is there a way to do this without having to pay for external software?
Thanks folks!
Since you have tagged apps script you can create a script where you can use G Suite Admin SDK and Gmail API to retrieve all the users and then set up a signature for each alias of the user.
This is an example on Apps Script for users: list:
/**
* Lists users in a G Suite domain.
*/
function listUsers() {
var optionalArgs = {
customer: 'my_customer',
maxResults: 10,
orderBy: 'email'
};
var response = AdminDirectory.Users.list(optionalArgs);
var users = response.users;
if (users && users.length > 0) {
Logger.log('Users:');
for (i = 0; i < users.length; i++) {
var user = users[i];
Logger.log('%s (%s)', user.primaryEmail, user.name.fullName);
}
} else {
Logger.log('No users found.');
}
}
Using Users: list (from Admin SDK) you will get all the users on your domain, and from that you can use path or update (from Users.settings.sendAs) to create a signature.
Is there a method in google apps script to get the files of a suspended owner based on his/her email id? I am literally trying to implement transfer drive files to a new owner using google apps script, I am using this code to find the details of all the suspended users:
/**
* Fetches the suspended user details from the AdminDirectory.
*/
function fetchUser() {
// Set the constant options only once.
const options = {
domain: 'xyz.com',
orderBy: 'email',
query: 'isSuspended=true',
maxResults: 500,
fields: "nextPageToken,users"
};
// Could log the options here to ensure they are valid and in the right format.
const results = [];
do {
var search = AdminDirectory.Users.list(options);
// Update the page token in case we have more than 1 page of results.
options.pageToken = search.nextPageToken;
// Append this page of results to our collected results.
if(search.users && search.users.length)
Array.prototype.push.apply(results, search.users);
} while (options.pageToken);
//Logger.log(results);
for(var k = 0; k < results.length; k++){
var fullEmail = results[k].primaryEmail;
Logger.log(fullEmail);
fetchFiles(fullEmail);
}
}
/**
* Fetches the files of the suspended users based on their email.
*/
function fetchFiles(email){
var pageToken;
var filesList = Drive.Files.list({ // Invalid value error is thrown here, I am not sure if this the right way to use Drive API in google script
domain: 'xyz.com',
orderBy: 'email',
q: "'email' in owners",
maxResults: 500,
pageToken: pageToken
});
Logger.log('filesList:' +filesList);
}
I am trying to implement something like Transfer ownership of a file to another user in Google Apps Script, but is there some way by which I can fetch the files of the user from the details obtained from the above code which basically returns the following output:
[
{
orgUnitPath = /,
ipWhitelisted = false,
gender = {type = other},
creationTime = 2017-06-13T14:38:44.000Z,
isMailboxSetup = true,
isEnrolledIn2Sv = false,
kind = admin#directory#user,
suspensionReason = ADMIN,
isAdmin = false,
suspended = true,
emails = [{
address = john.seb#xyz.com,
primary = true
}],
lastLoginTime = 2017-09-12T00:27:00.000Z,
isDelegatedAdmin = false,
isEnforcedIn2Sv = false,
changePasswordAtNextLogin = false,
customerId = v12idsa,
name = {
givenName = John,
familyName = Seb,
fullName = John Seb
},
etag = "npJcgeAc7Xbfksfwer22344/sfasdfaffUDsfdsjfhsfhsdfw-ec",
id = 1033392392142423424,
primaryEmail = john.seb#xyz.com,
agreedToTerms = true,
includeInGlobalAddressList = true
},
...
]
I am trying to use the Drive API in the google apps script in order to access the files of suspended users using their email, but its throwing
"Invalid Value" error
for the line Drive.Files.list, I am not sure if this is the right way to use the DRIVE API in google script, is there any other way to use this api in google script?
In your function fetchFiles, you never use the input argument email. Instead, you query the Drive REST API for the literal text 'email' in owners. Since the text string 'email' is not a valid email address, you correctly receive the error message "Invalid value".
Rather than this code:
/**
* Fetches the files of the suspended users based on their email.
*/
function fetchFiles(email){
var pageToken;
var filesList = Drive.Files.list({
domain: 'jerseystem.org',
orderBy: 'email',
q: "'email' in owners",
maxResults: 500,
pageToken: pageToken
});
Logger.log('filesList:' +filesList);
}
You should perform the substitution first, to set up all constant options (as I mentioned and demonstrated in your other question), and then repeatedly query the Drive API for the files owned by the user with that email address:
function fetchAllFilesOwnedByEmail(email) {
const searchParams = {
corpora: 'some corpora',
orderBy: 'some ordering criteria',
q: "'" + email + "' in owners",
fields: 'nextPageToken,items(id,title,mimeType,userPermission)'
};
const results = [];
do {
var search = Drive.Files.list(searchParams);
if (search.items)
Array.prototype.push.apply(results, search.items);
searchParams.pageToken = search.nextPageToken;
} while (searchParams.pageToken);
return results;
}
You need to review the Drive REST API documentation, see Drive.Files.list and Search for Files at minimum. Don't forget to enable the Drive advanced service if you haven't.
Also note that while the above code will resolve the "Invalid Value" error you get, it won't necessarily make the user's files show up, even if you're executing the code as the G-Suite admin. Your research should have turned up at least these two related questions:
How can an Admin access the Google Drive contents of all the users in a particular domain?
Most efficient process for transferring ownership of all of a user's files using the Google Drive API
I create a script to get all the users in one SpreadSheet, Name and Email, but I'm not able to get the users that are created under the secondary domain.
This is my code:
function writeToSpreadsheet(){
var values = [],
users = [],
userListQuery = {},
nextPageToken = '',
listObject = {
domain:'the domain name',
maxResults: 500,
},
i = 0,
activeSpreadsheet;
do {
if (nextPageToken && nextPageToken !== '') {
listObject.pageToken = nextPageToken;
}
userListQuery = AdminDirectory.Users.list(listObject);
// if there are more users than fit in the query a nextPageToken is returned
nextPageToken = userListQuery.nextPageToken;
// Add the query results to the users array
users = users.concat(userListQuery.users);
} while (nextPageToken);
for (i = 0; i < users.length; i += 1) {
values.push([users[i].name.fullName, users[i].primaryEmail]);
}
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange(2, 1, values.length, values[0].length).setValues(values);
}
Use the Google Admin Settings API, it allows administrators of Google Apps domains to retrieve and change settings of their domains in the form of Google Data API feeds.
To retrieve from secondary domain, you may send HTTP GET to the account information administrator secondary email address feed URL and include an Authorization header as described in Authenticating to the Admin Settings service
A successful response returns an HTTP 200 OK, along with the administrator's secondary email address.
Sample HTTP GET request:
https://apps-apis.google.com/a/feeds/domain/2.0/{domainName}/accountInformation/adminSecondaryEmai