How to use "not" in Gmail filters?

Google Apps-ScriptFilterGmail

Google Apps-Script Problem Overview


I need to create a Google App Script to respond to machine generated emails, except those also sent to one colleague or contain a particular topic outside my responsibility.

I've been trying to use the GmailApp.search API which includes all mail from user X but NOT those emails which are also addressed to user Y NOR those containing "junk_term". I want the emails archived and to skip the inbox.

I created a query like so:

 "from:([email protected]) -{user_Y@address.com OR junk_term}"

But it appears not to return any results.

Google Apps-Script Solutions


Solution 1 - Google Apps-Script

Fixing this problem requires understanding two things:

  1. If a label has been placed on an existing email by a filter, the label stays even if that filter were deleted. One must delete the label itself, and then re-create a new filter in order to get your edits to "take".

  2. There is a bug in the Gmail filter system. If you try to set up complex Boolean such as

    from:[email protected] -to:[email protected] -junk_term

It will work fine on the initial search, but if you use it to create a filter, the terms, especially the NOTs, will be garbled.

The correct syntax, (hat tip to chenghuayang) is to ignore the to's and from's.

user1@me.com -user2@me.com -junk_term

Solution 2 - Google Apps-Script

You could use labels to flag your emails and process them accordingly, based on those labels:

  1. matches from: [email protected] then apply label Label_X
  2. matches from: [email protected] then apply label Label_Y
  3. matches junk_term then apply label Label_Y
  4. matches label:label_X AND -label:Label_Y then respond

The condition of the last rule has to be added to the Includes the words field.

Here is a list of further attributes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpterandonView Question on Stackoverflow
Solution 1 - Google Apps-ScriptpterandonView Answer on Stackoverflow
Solution 2 - Google Apps-ScriptCarsten HagemannView Answer on Stackoverflow