Libraries used
google-auth-oauthlibgoogle-auth-httplib2google-api-python-client
How do we let google know its us?
This is our first step, to tell user that its us who’s trying to get the gmail access. For that you need to set up an app in G cloud and get the credentials file from there. This file will be our base that’ll be used to get user permissions later.
Now, we use the set of libraries we have installed.
from google_auth_oauthlib.flow import InstalledAppFlow
# client_secrets_file is the credentials json that we downloaded.# scopes is an array of what services you need to get access for, here ["https://mail.google.com/"]flow=InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes=scopes)
# local port better be 0, since it assigns the empty port number in the system.# or you can assign a specific empty portcreds=flow.run_local_server(port=local_port)The creds variable now will store the token that we require. The token will be used in gmail api, so that google knows whose email account we are going to use to get email data.
Time to feed on the data
Lets create a service class to use everywhere, while fetching data.
from googleapiclient.discovery import build
# here credentials are the token file we fetched in prev step.service=build("gmail", "v1", credentials=creds, cache_discovery=False)Now we use this service class everywhere
Searching messages
res = service.users().messages().list(userId=user_id, q=query, maxResults=max_results).execute() return res.get("messages", [])Reading email message
Requires message id we got from the message list. It includes the payload (attachments).
userid can be saved as “me”
res = service.users().messages().get(userId=user_id, id=message_id, format=format).execute()