Monday 16 September 2019

Python Google/Gmail API

In order to have something tap into your Google API, you need to set up OAuth. Now before I continue, I just to be able to tap into my Gmail account, using the python imaplib, I am no longer able to access the account through python anymore.  Google claims that the Gmail API is no substitution for imap, but i am not sure. So anyone who has some insights on imaplib and gmail and if it still works without OAuth, please leave a comment below.

Yes, so out of necessity I started looking into OAuth, python and Gmail, and it actually does not look that bad.


What is OAuth?

OAuth is essentially a way, to avoid having to write all sorts of authentication code into your application (in our case the pythin script).





I dont want to dwell on Oauth to much, as this post is more of an instruction on how to access the google GMAIL API. 



Instructions

1-Open google account or use existing one and go to Developers section.

2-https://developers.google.com/gmail/api/

3-Go to the Guides TAB (see below), which pretty much tells you everything I was gonna tell you but without the spelling mistakes.




4- run the pip install:


pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib


5-download the client configuration file, which contains the client ID and token. Put this in same directory as the python file you are about to add.

6. Create python script:


from __future__ import print_functionimport pickleimport os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])
if __name__ == '__main__':
    main()
from __future__ import print_functionimport pickleimport os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def main():     """Shows basic usage of the Gmail API.     Lists the user's Gmail labels.     """     creds = None     # The file token.pickle stores the user's access and refresh tokens, and is     # created automatically when the authorization flow completes for the first     # time.     if os.path.exists('token.pickle'):         with open('token.pickle', 'rb') as token:             creds = pickle.load(token)     # If there are no (valid) credentials available, let the user log in.     if not creds or not creds.valid:         if creds and creds.expired and creds.refresh_token:             creds.refresh(Request())         else:             flow = InstalledAppFlow.from_client_secrets_file(                 'credentials.json', SCOPES)             creds = flow.run_local_server(port=0)         # Save the credentials for the next run         with open('token.pickle', 'wb') as token:             pickle.dump(creds, token)     service = build('gmail', 'v1', credentials=creds)     # Call the Gmail API     results = service.users().labels().list(userId='me').execute()     labels = results.get('labels', [])     if not labels:         print('No labels found.')     else:         print('Labels:')         for label in labels:             print(label['name']) if __name__ == '__main__':     main()
from __future__ import print_functionimport pickleimport os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def main():     """Shows basic usage of the Gmail API.     Lists the user's Gmail labels.     """     creds = None     # The file token.pickle stores the user's access and refresh tokens, and is     # created automatically when the authorization flow completes for the first     # time.     if os.path.exists('token.pickle'):         with open('token.pickle', 'rb') as token:             creds = pickle.load(token)     # If there are no (valid) credentials available, let the user log in.     if not creds or not creds.valid:         if creds and creds.expired and creds.refresh_token:             creds.refresh(Request())         else:             flow = InstalledAppFlow.from_client_secrets_file(                 'credentials.json', SCOPES)             creds = flow.run_local_server(port=0)         # Save the credentials for the next run         with open('token.pickle', 'wb') as token:             pickle.dump(creds, token)     service = build('gmail', 'v1', credentials=creds)     # Call the Gmail API     results = service.users().labels().list(userId='me').execute()     labels = results.get('labels', [])     if not labels:         print('No labels found.')     else:         print('Labels:')         for label in labels:             print(label['name']) if __name__ == '__main__':     main()

Now when you run the script, it will generate an authorization link:






This link is basically a confirmation authorization, i.e. grant authorization to the application to access the API. I will prompt you to grant access to the python "application" to be able to access the gmail account.



This is a once off, after this, tokens will be exchanged.

For access to your API and to down oad the client json file:


https://console.developers.google.com


This particular python code, prints all the labels in the gmail account.

No comments:

Post a Comment