Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adds labels to gmail threads if members are in contacts group
// Add Gmail labels by contact group
// komarov.vitaliy@gmail.com, 2018
// Inspired by https://github.com/thirschbuechler/GmailContactGroupLabels
// BTW: see readme in mentioned github repo ^^^
function applyGroupLabels() {
var MY_GROUP_NAME = "My-contact-group-name"; // Change right side of this line to match your contact group
var MY_LABEL_NAME = "My-label-name"; // This as well, insert the Gmail label
var QUERY = 'in:all -in:trash -in:spam'; // This as well, insert the query
var labeledThreads = [];
var emailAddresses = getEmailAddressesFromContactsGroup(MY_GROUP_NAME);
var threads = getAllThreadsByQuery(QUERY);
threads.forEach(function (thread) {
// Main logic here:
emailAddresses.forEach(function (emailAddress) {
var messages = thread.getMessages();
messages.forEach(function (message) {
if (message.getTo().indexOf(emailAddress) > -1) {
labeledThreads.push(thread);
} else if (message.getFrom().indexOf(emailAddress) > -1) {
labeledThreads.push(thread);
}
});
});
});
var label = GmailApp.getUserLabelByName(MY_LABEL_NAME);
label.addToThreads(labeledThreads);
}
function getEmailAddressesFromContactsGroup(groupName) {
var emailAddresses = [];
var groupContacts = ContactsApp.getContactGroup(groupName).getContacts();
// Collect all email addresses from contact group
groupContacts.forEach(function (contact) {
var contactEmailAddresses = contact.getEmails();
contactEmailAddresses.forEach(function (emailAddress) {
emailAddresses.push(emailAddress.getAddress());
});
});
return emailAddresses;
}
function getAllThreadsByQuery(query) {
var threadLength = 1;
var i = 0;
var allThreads = [];
var threads;
var start;
var step;
while (threadLength) {
if (i === 0) {
threads = GmailApp.search(query);
threadLength = step = threads.length;
allThreads.push.apply(allThreads, threads);
} else {
start = step * i;
threads = GmailApp.search(query, start, step);
threadLength = threads.length;
allThreads.push.apply(allThreads, threads);
}
i++;
}
return allThreads;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment