Managing Google Contacts with Google Apps Script: Filtering by Labels and Listing All Contacts

Google Apps Script provides powerful tools to interact with Google services, including Google Contacts. In this blog post, we’ll explore how to use the Advanced People Service in Google Apps Script to filter contacts by a specific label and list all contacts along with their labels. We’ll walk through two key functions: getContactsByLabel and listContactsAndLabels.

Enabling the People API

Before we start, ensure that the People API is enabled for your project:

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Enable the People API for your project.

Next, enable the Advanced People Service in your Apps Script project:

  1. Open the Apps Script editor (Extensions > Apps Script).
  2. Click on the + icon next to “Services” in the left pane.
  3. In the “Add a service” dialog, scroll down to find “People API” and click on the “Add” button.

Function 1: Filtering Contacts by Label

The getContactsByLabel function retrieves contacts with a specified label.

function getContactsByLabel() {
// Replace 'your-label-id' with the actual label ID
const labelId = 'contactGroups/20012dac89796dca';

const pageSize = 100; // Adjust page size if needed
let connections = [];
let pageToken;

// Fetch all contacts with pagination
do {
const response = People.People.Connections.list('people/me', {
pageSize: pageSize,
pageToken: pageToken,
personFields: 'names,emailAddresses,memberships'
});

if (response.connections) {
connections = connections.concat(response.connections);
}
pageToken = response.nextPageToken;
} while (pageToken);

// Filter contacts by label
const contactsWithLabel = connections.filter(contact => {
return contact.memberships && contact.memberships.some(membership => membership.contactGroupMembership && membership.contactGroupMembership.contactGroupResourceName === labelId);
});

// Log the contacts
contactsWithLabel.forEach(contact => {
const name = contact.names ? contact.names[0].displayName : 'No name';
const email = contact.emailAddresses ? contact.emailAddresses[0].value : 'No email';
Logger.log(`Name: ${name}, Email: ${email}`);
});
}

Explanation

  1. Label ID: Replace 'contactGroups/20012dac89796dca' with the actual ID of the label you want to filter by.
  2. Pagination Handling:
    • The do-while loop fetches contacts in batches (pageSize is set to 100 but can be adjusted).
    • pageToken is used to handle pagination and ensure all contacts are retrieved.
  3. Filtering Contacts:
    • The connections.filter method filters contacts that have the specified label.
    • contact.memberships checks for label memberships, and membership.contactGroupMembership.contactGroupResourceName checks if the label ID matches.
  4. Logging Contacts:
    • Logs the name and email of each contact that matches the specified label.

Function 2: Listing All Contacts with Labels

The listContactsAndLabels function retrieves and logs all contacts along with their associated labels.

function listContactsAndLabels() {
const pageSize = 100; // Adjust page size if needed
let connections = [];
let pageToken;

// Fetch all contacts with pagination
do {
const response = People.People.Connections.list('people/me', {
pageSize: pageSize,
pageToken: pageToken,
personFields: 'names,emailAddresses,memberships'
});

if (response.connections) {
connections = connections.concat(response.connections);
}
pageToken = response.nextPageToken;
} while (pageToken);

// Iterate through the contacts and log their details
connections.forEach(contact => {
const name = contact.names ? contact.names[0].displayName : 'No name';
const email = contact.emailAddresses ? contact.emailAddresses[0].value : 'No email';
const labels = contact.memberships ? contact.memberships.map(m => m.contactGroupMembership.contactGroupResourceName).join(', ') : 'No labels';

Logger.log(`Name: ${name}, Email: ${email}, Labels: ${labels}`);
});
}

Explanation

  1. Pagination Handling:
    • Similar to the getContactsByLabel function, it fetches contacts in batches using pagination.
  2. Logging Contacts:
    • Iterates through each contact and extracts their name, email, and labels.
    • contact.memberships.map retrieves all labels associated with the contact and joins them into a single string for logging.

How to Use the Functions

  1. Open Script Editor: In your Google Sheets document, go to Extensions > Apps Script.
  2. Add the Code: Copy and paste the complete code above into the script editor.
  3. Save the Script: Click on the disk icon or press Ctrl + S to save the script.
  4. Authorize the Script: When you run the script for the first time, you will need to authorize it. Click on Run > getContactsByLabel or Run > listContactsAndLabels in the script editor and follow the prompts to authorize.

These functions will help you manage your Google Contacts by filtering them based on labels and listing all contacts with their labels, respectively. You can adapt and expand these functions to suit your specific needs, making your contact management more efficient and organized.