Search code examples
google-apps-scriptgoogle-people-api

Google Apps Script Google People API get contacts from contact group


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.


Solution

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