Codementor Events

Retrieving Email and Phone No. for a Desktop App from Google Contacts using Python and Gmail API | by Aritra Roy | Analytics Vidhya | Medium

Published Oct 27, 2020
Retrieving Email and Phone No. for a Desktop App from Google Contacts using Python and Gmail API | by Aritra Roy | Analytics Vidhya | Medium

Though python has been created by Guido van Rossum as a hobby project in the 90’s decade, it has become the most popular language now. Due to its ability to work in various fields and easy syntax python is now used in Big-Data Analysis, ML & AI, Deep-learning, image-processing as well as in web development, game development, and so on. Moreover, it has plenty of libraries which one can use to easily and quickly complete the task.

Receiving the phone no and email id can be received from Google contact by using there API service. In order to access one’s google contact, we need that particular permission from the user via the API access level. Here ‘Gmail API’ comes to rescue us easily. Though Google provides two more API aka Contact API version 3.0(is scheduled for sunset on June 15, 2021 ) and People API, from my point of view, the ‘Gmail API’ seems to be a lot easier to do the job.

Requirements:

We’ve used python to fetch the phone no and email id from Google contacts. For this, the followings are required —
Python 2.6 or greater
The pip package management tool
A Google account with Gmail enabled

Process:

Step 1: Turning on the Gmail API
Go to the link below to enable the Gmail API — https://developers.google.com/gmail/api/quickstart/python#step_1_turn_on_the
1*uzeizDdap_C3gNCRE_69pQ.jpeg
2. Then one will need to provide a project name and click on the ‘Next’ button.
1*J7vrNEM04MMkv8Cg1d4oJA.jpeg
3. The next step is configuring the OAuth client. If one wants to retrieve the data on his computer, then he’ll need to set it as the ‘Desktop app’. Otherwise, one can choose his choice or according to his requirement and click on the ‘Create’ button.
1*_dDakVlZ5vdjsKVaDmXbpw.jpeg
4. The final step of ‘Enabling Gmail API’ is to download the ‘Client Configuration’. Note that, one has to download the ‘Client Configuration’ specifically in the project folder to successfully enable the API.
1*b5NLbBwtLCk8MPiyUeNPzw.jpeg
Step 2: Installing the Google Client Library
We have to use/install Google Client Library python library to access. To install it via pip —
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
1*a0kLsXYp_BjCpeqW6NZ52g.jpeg
Step 3: Setting up with code

Sample code given by Google Client

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from 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()

Please note that the project name(given at the time of enabling Gmail API) and the python file name should be the same. We’ve run the python file from ‘Windows PowerShell’ —
1*weYTS39nfhfuIIRayvAkjw.jpeg
It’ll open a localhost browser window for accessing your Gmail account(from where the contacts will be retrieved) and the following steps are —
1*0k6qC4yFYkN-G1LIQBBEHw.jpeg
Choosing one Gmail account from where the contacts will be retrieved
There’ll be an alert message saying ‘This app isn’t verified’. The ‘Advanced’ option should be clicked
Thereafter ‘Go to Quickstart(unsafe)’ option should be clicked for further proceeding. Note that, this ‘Quickstart’ word will be replaced by the project name if one chooses a different project name while Enabling the Gmail API (step 1).
The ‘Allow’ option should be selected for permitting our application.
Again, the ‘Allow’ option should be selected for allowing our application to see and download our contacts from Google Contacts.
After completing all the previous steps, a message saying ‘The authentication flow has completed. You may close this window.’ should be shown in the browser window. The browser window can be closed now.
After closing the window, if we take a look in the Windows Powershell, we’ll be able to see that our program has finished all the tasks giving us a message like following —
1*p6uqY2Xq5zQDAzlfWNurjQ.jpeg
Now if we run the specific python file from Windows PowerShell, it’ll give a result like below —
1*sq9MZ0E26iWZJ7YtoqaC9Q.jpeg
Note that, it has fetched different folder headings and contact headings only while we were using the sample code given by the ‘Gmail API Guide’.

Code to retrieve Email and Phone No.

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import json

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/contacts.readonly']

def main():
    """Shows basic usage of the People API.
    Prints the name of the first 10 connections.
    """
    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('people', 'v1', credentials=creds)

    # Call the People API
    print('List of all name with email id and phone number:\n')
    results = service.people().connections().list(
        resourceName='people/me',
        pageSize=1500,
        personFields='names,emailAddresses,phoneNumbers').execute()
    connections = results.get('connections', [])
    i=1
    for person in connections:
        names = person.get('names', [])
        emails = person.get('emailAddresses', [])
        phones = person.get('phoneNumbers')

        if names and emails:
            name = names[0].get('displayName')
            email = emails[0]['value']
            phone = phones[0]['value']
            print(f"\n{i}. {name} - {email}     {phone}")
            i+=1

if __name__ == '__main__':
    main()

All the steps up to ‘authentication’ i.e. previously described process 1 has to be performed. After that, if one runs the above code that’ll give a result like following—
1*2izvPyy8b40lLyw0jRnHbw.jpeg
Note that, All the names, their email ids, and phone numbers have been retrieved from ‘Google Contacts’ associated with that Google account.

Note:

One can’t fetch all the emails and phone numbers from Google Contacts if he doesn’t take permission from the user via the API access level.
It is an easy way to retrieve all the email ids and phone numbers from ‘Google contacts’ without ‘Django’.
One can manipulate the results according to his choice whether to fetch only name-email id or name-phone number or name-both or anything by changing as per his requirement.
The output can be used in any further work such as one can send mail using voice assistant or make a phone call.
The ‘Client Configuration’ will be downloaded as credentials.json
All the details will be saved in the token.pickle file and no further retrieving will be occurred if there is no change.
All the files should be in the same folder path for the process
This project has been done in windows 10. But one can further take it forward for Linux and iOS.

Thank you for reading.
I hope you found this ‘Email and Phone No. Retrieving Process’ helpful. Please > > leave any comments to let us know your thoughts.

Follow Me:

GitHub — https://github.com/aritraroy24
LinkedIn — https://www.linkedin.com/in/aritraroy24/

Discover and read more posts from Aritra Roy
get started