Gmail API in Python

To use the Gmail API in Python, you will first need to enable the Gmail API and obtain your credentials from the Google Cloud Console. Here are the steps:

  1. Go to the Google Cloud Console (https://console.cloud.google.com/).
  2. Create a new project or select an existing project.
  3. Enable the Gmail API. To do this, click on “APIs & Services” in the left sidebar, then click on “Dashboard”. From there, click on the “+ ENABLE APIS AND SERVICES” button, search for “Gmail API”, and select it. Then click on “Enable”.
  4. Create credentials. To do this, click on “Create Credentials” in the top-right corner, then select “OAuth client ID”. Choose “Desktop app” as the application type, give it a name, and click on “Create”. Then, download the credentials JSON file and save it somewhere safe.

Once you have your credentials, you can start using the Gmail API in Python. Here’s an example of how to get the labels from your Gmail account:

import os
import google.auth
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

# Replace with the path to your credentials file
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/credentials.json"

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

creds = None
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = google.auth.default(scopes=SCOPES)
        creds = flow.run_local_server(port=0)

    # Save the credentials for the next run
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

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'])

This code will prompt you to authorize the app and then print out a list of labels from your Gmail account. Note that you will need to install the following packages:

google-auth
google-auth-oauthlib
google-auth-httplib2
google-api-python-client

Installation of Required libraries:

To use the Gmail API in Python, you will need to install the following libraries:

  • google-auth
  • google-auth-oauthlib
  • google-auth-httplib2
  • google-api-python-client

You can install them using pip, the Python package manager. Open a command prompt or terminal and run the following command:

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

This will install all four libraries. Once they are installed, you can use the code I provided earlier to access the Gmail API.

Enabling Gmail APIs in our device:

To enable the Gmail API in your device, you will need to follow these steps:

  1. Go to the Google Cloud Console (https://console.cloud.google.com/).
  2. Create a new project or select an existing project.
  3. Enable the Gmail API. To do this, click on “APIs & Services” in the left sidebar, then click on “Dashboard”. From there, click on the “+ ENABLE APIS AND SERVICES” button, search for “Gmail API”, and select it. Then click on “Enable”.
  4. Create credentials. To do this, click on “Create Credentials” in the top-right corner, then select “OAuth client ID”. Choose “Desktop app” as the application type, give it a name, and click on “Create”. Then, download the credentials JSON file and save it somewhere safe.
  5. Install the required libraries. To use the Gmail API in Python, you will need to install the following libraries: google-auth, google-auth-oauthlib, google-auth-httplib2, and google-api-python-client. You can do this using pip, the Python package manager, by running the command pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client in a command prompt or terminal.
  6. Start coding! You can now use the Gmail API in Python by importing the required libraries, loading your credentials from the JSON file, and making API calls using the googleapiclient library. You can find sample code and documentation for the Gmail API in the Google Developers website.

Performing Actions using Gmail APIs in Python:

You can perform various actions using the Gmail API in Python. Here are some examples:

  1. Get all messages in the inbox:
import os
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

# Replace with the path to your credentials file
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/credentials.json"

service = build('gmail', 'v1', credentials=Credentials.from_authorized_user_file('/path/to/token.json'))

# Call the Gmail API to get messages
result = service.users().messages().list(userId='me', q='in:inbox').execute()
messages = result.get('messages', [])

if not messages:
    print("No messages found.")
else:
    print("Messages:")
    for message in messages:
        msg = service.users().messages().get(userId='me', id=message['id']).execute()
        print(f"- {msg['snippet']}")

This code will list all the messages in your inbox and print their snippets.

  1. Send an email:
import base64
from googleapiclient.errors import HttpError
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import os

# Replace with the path to your credentials file
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/credentials.json"

service = build('gmail', 'v1', credentials=Credentials.from_authorized_user_file('/path/to/token.json'))

def send_email(to, subject, body):
    try:
        message = MIMEMultipart()
        message['to'] = to
        message['subject'] = subject

        text = MIMEText(body, 'html')
        message.attach(text)

        # attach an image
        img_path = '/path/to/image.jpg'
        with open(img_path, 'rb') as f:
            img_data = f.read()
        image = MIMEImage(img_data, name=os.path.basename(img_path))
        message.attach(image)

        create_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
        send_message = (service.users().messages().send(userId="me", body=create_message).execute())
        print(F'The email was sent to {to} with Email Id: {send_message["id"]}')

    except HttpError as error:
        print(F'An error occurred: {error}')
        send_message = None
    return send_message

send_email("[email protected]", "Test Email", "<h1>Hello World!</h1>")

This code will send an email to the specified recipient, with a subject and body. You can also attach an image or other files by modifying the code accordingly.

These are just a couple of examples of what you can do with the Gmail API in Python. You can also search for messages, create labels, and more. For more information, check out the Gmail API documentation on the Google Developers website.

Conclusion:

In this conversation, we discussed how to use the Gmail API in Python. We covered the installation of required libraries, enabling the Gmail API in your device, and performing actions using the Gmail API in Python, such as getting all messages in the inbox and sending an email.

The Gmail API provides a powerful tool for managing emails in Gmail and can be used to automate various email-related tasks. By following the steps outlined above, you can get started with the Gmail API in Python and explore its capabilities further.