Python Create Gmail labels for Gmail account using Gmail API














































Python Create Gmail labels for Gmail account using Gmail API



Python
Create Gmail labels for Gmail account using Gmail API



Prerequisites :-

    1. Python 2.6 or greater

    2. The pip package management tool

    3. A Google account with Gmail enabled


STEP 1: Turn on the Gmail API


Before accessing the Gmail API from our python script, we need to authorize API requests from our app from a Google account. You can enable API requests here.


In this link click 'Enable the Gmail API' and save the file credentials.json to your working directory.


STEP 2: Install the Google Client Library


Run the following command on your terminal to install the library using pip


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


STEP 3: Defining the structure



       We have two files


      1) gmail_labels.py :- This file defines the GMailLabelUser class. An instance of this class has the ability Create, read, update, and delete labels only.


      2) create_label.py :- This is the main script to be run.


Input :-

1)   name:- name of the label


Output :-

Creates a label and prints the label id as returned by the Gmail API.


Errors :-

1)   Errors while authenticating google account.

2)   Errors while creating label.



 STEP 4: GMailLabelUser Class



 1)   Import the required dependencies


from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle

import os.path


 2) Define the constructor for this class 

class GMailLabelUser:
def __init__(self):
print('User Created')
self.scopes = ['https://www.googleapis.com/auth/gmail.labels']

The variable 'scopes' keeps track

of the scopes of Gmail API allocated to this class.


The different scopes available in

the Gmail API are given at the bottom of this page.


       creds = None


Here, 'creds' is the object that

holds the credentials necessary to authenticate a google account.


       if os.path.exists('token-label.pickle'):

with open('token-label.pickle', 'rb') as token:
creds = pickle.load(token)


We use 'pickle' to store/retrieve the authentication credentials from a file. This allows us to use the script without having to login everytime we run the script.


try:

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', self.scopes)
creds = flow.run_local_server(port=0)
with open('token-label.pickle', 'wb') as token:
pickle.dump(creds, token)



If the authentication for a user has expired or hasn't been made we authenticate the user and save the credentials in a file. 


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

except Exception as error:
print("Error occured while authenticating :-")
print(error)
print('GMail API auth completed')

 The variable 'service' is used to access the API.


     3)  Add a method to this class to create email message drafts.


def create_label(self, label_name):

label_obj = {'name': label_name}
try:
label = self.service.users().labels().create(userId=
'me', body=label_obj).execute()
print(
'Label with id: %s created' % label['id'])
return label
except Exception as error:
print(
'An error occurred while creating label: %s' % error)
return None



STEP 5: Main Script


from gmail_label import GMailLabelUser

if __name__ == '__main__':
print(
'Enter name of label :-')
name = input()
user = GMailLabelUser()
label = user.create_label(name)



Additional information


Gmail API Scopes :-


https://developers.google.com/gmail/api/auth/scopes 


Comments