Last active
October 3, 2018 07:33
-
-
Save Webbrother/810acd9d73a066ab1cdb295d9f1d2122 to your computer and use it in GitHub Desktop.
Adds labels to gmail threads if members are in contacts group
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add Gmail labels by contact group | |
// [email protected], 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