How to access Gmail using Python

If you a need to access mails and other data from Gmail to analyse them on the server, you can use the Gmail API to facilitate that. In the following post we will use Python to access the api and read some emails.

Installation

Turning on the Gmail api

You first need to enable Gmail api and get the required OAuth credentials from your Google account. The steps which are shown below.

1. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.

2. On the Add credentials to your project page, click the Cancel button.

3. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.

4. Select the Credentials tab, click the Create credentials button and select OAuth client ID.

5. Select the application type Other, enter the name “Gmail API Quickstart”, and click the Create button.

6. Click OK to dismiss the resulting dialog.

7. Click the Download JSON button to the right of the client ID.

8. Move this file to your working directory and rename it client_secret.json.

Install the Gmail api Python library.

Once the above process has been done run the following Python file and you will get the list of labels for your Gmail account.

Now to get an actual message from Gmail we will use the following code. The initial authorization code is the same, just the api calls change.

Detailed functions list for accessing the Gmail api is given here.

Leave a Reply

Your email address will not be published. Required fields are marked *