I like to apply labels to emails to and from certain contact groups in Gmail. While many Gmail users have requested from Google the ability to filter by contact groups for years, the feature has yet to come. Users are stuck with the traditional way of copying and pasting every email address in the contact group to the filter. Until Google implements this feature, I am simplifying this painstaking process using four lines of python codes.
In Gmail, click the grey arrow on the search bar:
In the search advanced search box, type in the name of your contact group in the From or To fields. Then copy all the contact info shown in the field:
In order to apply a label to ANY email address listed in the group, we need to separate the email addresses by "OR" and take off the contact names. We will automate this arduous task using Python.
In Python, import the
Declare a new variable and paste the contact info copied above. Enclose it with single quotation marks:
original = '<firstname.lastname@example.org>, "Choe Yong" <email@example.com>, "CLD Assistant Editor"...'
Replace the comma in
original with "OR" using the
replaceComma = original.replace(",", " OR")
Because Google filters cannot filter email addresses with contact names in between, we will proceed to substitute all names in the quotation marks with an empty space using the
Lastly, print the
Run the code in the interactive shell. The interactive shell will output the result like the one below with OR in between email addresses and no contact names:
<firstname.lastname@example.org> OR <email@example.com> OR <firstname.lastname@example.org>...
Back to Gmail, we can now paste the Python output to the From field (or the To field) and click "Create filter with this search":
Select the action you want to apply to your filtered contacts. In my case, I wanted to apply labels to all mails sending from those contacts. Don't forget to check "also apply filter to xx matching conversations" if you want the selected actions to apply to existing emails.
The drawback of this method is that the filter is not automatically updated when you update your contact group. Until Google integrates this feature, we will have to perform this manually unless we write more complex codes-- at least you can simplify the task with only four lines of codes! Here they are again:
original = '[insert email addresses copied from the contact group]' replaceComma = original.replace(",", " OR") result = re.sub(r'".*?"', '', replaceComma) print result