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:
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Enable the People API for your project.
Next, enable the Advanced People Service in your Apps Script project:
- Open the Apps Script editor (
Extensions > Apps Script
). - Click on the
+
icon next to “Services” in the left pane. - 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
- Label ID: Replace
'contactGroups/20012dac89796dca'
with the actual ID of the label you want to filter by. - 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.
- The
- Filtering Contacts:
- The
connections.filter
method filters contacts that have the specified label. contact.memberships
checks for label memberships, andmembership.contactGroupMembership.contactGroupResourceName
checks if the label ID matches.
- The
- 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
- Pagination Handling:
- Similar to the
getContactsByLabel
function, it fetches contacts in batches using pagination.
- Similar to the
- 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
- Open Script Editor: In your Google Sheets document, go to
Extensions > Apps Script
. - Add the Code: Copy and paste the complete code above into the script editor.
- Save the Script: Click on the disk icon or press
Ctrl + S
to save the script. - Authorize the Script: When you run the script for the first time, you will need to authorize it. Click on
Run > getContactsByLabel
orRun > 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.
