Python Gmail API
Introduction
Gmail API is a powerful and easy-to-use Google API that can be integrated in any Python application. This API allows you to access and manage the Gmail messages, labels, drafts, and history. You can send emails, get emails, search emails, reply emails, and delete emails using the Gmail API.
Syntax
First, you need to enable the Gmail API for your Google account and install the google-auth
, google-auth-oauthlib
, and google-auth-httplib2
Python libraries. Then, you can authenticate and authorize the API using the following code snippet:
from google.oauth2.credentials import Credentials
creds = Credentials.from_authorized_user_file('path_to_credentials.json', SCOPES)
where path_to_credentials.json
is the path to the credentials file and SCOPES
are the permissions you want to grant to the API (e.g., ['https://www.googleapis.com/auth/gmail.readonly']
for read-only access).
Once you have authenticated and authorized the API, you can use the following methods to interact with the Gmail:
Send email
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google.oauth2.credentials import Credentials
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
def send_email(to, subject, body, image=None):
try:
service = build('gmail', 'v1', credentials=creds)
message = MIMEMultipart()
text = MIMEText(body, 'html')
message.attach(text)
if image:
img = MIMEImage(open(image, 'rb').read(), name='image.png')
message.attach(img)
message['to'] = to
message['subject'] = subject
create_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
send_message = (service.users().messages().send(userId="me", body=create_message).execute())
print(F'sent message to {to} Message Id: {send_message["id"]}')
except HttpError as error:
print(F'An error occurred: {error}')
send_message = None
return send_message
Get email
def get_email(email_id):
service = build('gmail', 'v1', credentials=creds)
message = service.users().messages().get(userId='me', id=email_id, format='full').execute()
payload = message['payload']
headers = payload['headers']
for d in headers:
if d['name'] == 'From':
sender = d['value']
if d['name'] == 'Delivered-To':
recipient = d['value']
if d['name'] == 'Subject':
subject = d['value']
if d['name'] == 'Date':
date = d['value']
parts = payload['parts']
for part in parts:
data = part['body']['data']
print(F'From: {sender}, To: {recipient}, Subject: {subject}, Date: {date}, Body: {data}')
Search email
def search_email(query):
service = build('gmail', 'v1', credentials=creds)
result = service.users().messages().list(userId='me', q=query).execute()
messages = result.get('messages', [])
for msg in messages:
get_email(msg['id'])
Delete email
def delete_email(email_id):
service = build('gmail', 'v1', credentials=creds)
delete_message = service.users().messages().delete(userId='me', id=email_id).execute()
print(F'message deleted: {delete_message}')
Example
Here is an example of how to send an email using the Gmail API:
to = 'example@example.com'
subject = 'Test Email'
body = '<h1>Hello from Gmail API</h1>'
image = 'image.png'
send_email(to, subject, body, image)
Output
The above code will send an email to the specified recipient with subject "Test Email" and body "Hello from Gmail API" and an image named "image.png" attached to it.
Explanation
The send_email
method creates a MIME message object, adds a HTML body and an inline image to it, sets the recipient and subject, encodes the message in base64, and sends it using the service.users().messages().send()
method.
The get_email
method retrieves the message with the specified ID, extracts the sender, recipient, subject, date, and body from its payload, and prints them to the console.
The search_email
method searches for the messages matching the specified query (e.g., "from:jane@example.com subject:hello"), and calls the get_email
method to print their details.
The delete_email
method deletes the message with the specified ID from the Inbox.
Use
You can use the Gmail API to build email clients, email marketing tools, email automation scripts, and many other email-related applications. The API provides a convenient and secure way to access and manage your Gmail messages programmatically.
Important Points
- To use the Gmail API, you need to create a Google Cloud Platform project, enable the Gmail API, and obtain credentials for your application.
- You can authenticate and authorize the API using the
google-auth
library and the OAuth2 protocol. - You can interact with the Gmail API using the
google-api-python-client
library, which provides a Python wrapper around the Gmail REST API. - The Gmail API supports a wide range of operations, such as sending emails, getting emails, searching emails, and deleting emails. You can also manage labels, drafts, and history using the API.
- The Gmail API has rate limits and quotas that you need to respect in order to avoid errors and disruptions.
Summary
In this tutorial, you learned how to use the Gmail API in Python to send and receive emails, search for messages, and delete messages. You also learned how to authenticate and authorize the API, and how to use the google-api-python-client
library to interact with the Gmail REST API.