Skip to content

Querying

Jeremy Ephron Barenholtz edited this page Dec 27, 2020 · 3 revisions

If you want to perform a search for specific messages, you can use the query parameter available with all the get convenience functions. This query behaves identically to typing into the search bar on the Gmail client, so you can use all the search operators available there. Simple Gmail also provides a construct_query function for constructing these searches more programmatically; the output of construct_query is a string you could paste into the Gmail search bar.

Let's say I wanted to search for all unread messages received within the past two days that contain a Google Drive attachment.

First, import the construct_query function, and set up the Gmail object per usual:

from simplegmail import Gmail
from simplegmail.query import construct_query

gmail = Gmail()

Then, construct the query (the full list of options and usage can be read in the function docstring of construct_query):

query_params = {
    'unread': True,
    'newer_than': (2, 'day'),
    'drive': True
}

query = construct_query(query_params)
# equivalent to the following:
#   query = construct_query(unread=True, newer_than=(2, 'day'), drive=True)
#   query = '(is:unread newer_than:2d has:drive)'

msgs = gmail.get_messages(query=query)

There are many different ways of achieving the same results with queries. Particularly, since you can layer queries on top of any of the get convenience functions, we can exclude the unread parameter and instead write:

query_params = {
    'newer_than': (2, 'day'),
    'drive': True
}

query = construct_query(query_params)

msgs = gmail.get_unread_messages(query=query)

Building More Complex Queries

All the query parameters inside a dictionary will be AND'd together, while you can provide multiple dictionaries of queries to be OR'd together. For instance, if I wanted to match all unread messages received within the past two days that have a Google Drive attachment or unread messages received after December 1, 2020 that have a Word document attached, I can write:

query_params_1 = {
    'newer_than': (2, 'day'),
    'drive': True
}
query_params_2 = {
    'after': '2020/12/01',
    'spec_attachment': 'docx'
}

query = construct_query(query_params_1, query_params_2)
# query = '{(newer_than:2d has:drive) (after:2020/12/01 filename:docx)}'

msgs = gmail.get_unread_messages(query=query)
Clone this wiki locally