Skip to content

Google - Gmail

Interact and perform various operations through a Google account. Send, retrieve and reply to email messages easily via the BotCity plugin for Gmail.

Installation

pip install botcity-gmail-plugin

Importing the Plugin

After you installed this package and get the Google credentials file, the next step is to import the package into your code and start using the functions.

from botcity.plugins.gmail import BotGmailPlugin

Setting up the email

First, let's configure the gmail account and the credentials that we will use in the code.

# Set the path of the credentials json file
credentials = './resources/credentials.json'

# Instantiate the plugin
gmail = BotGmailPlugin(credentials, "<your_gmail_account>")

Info

Your gmail account must be the same as the one used to generate the credentials.

Searching for some messages

With the account properly configured, let's filter and search for some emails.

# Search for all emails with subject: Hello World
messages = gmail.search_messages(criteria="subject:Hello World")

# For each email found: prints the subject, sender address and text content of the email
for msg in messages:
    print("\n----------------------------")
    print("Subject => " + msg.subject)
    print("From => " + msg.from_)
    print("Msg => " + msg.text)

In this example, only the subject attribute was used as a filter. However, the Gmail API offers different possibilities, using other combinations and operators. See more details about search operators in this link.

Operations with returned messages

With this plugin we were able to perform several operations with messages that were obtained after the search method.

# Search for all emails where:
# The subject is "Important!"
# It was sent by the email address: some_sender@gmail.com
# It was sent after the date of 01/04/2022
messages = gmail.search_messages(criteria="subject:Important! from:some_sender@gmail.com after:01/04/2022")

# For each email found:
# Mark as read
# Download files in attachments
# Reply with the text: "Received!"
for msg in messages:
    gmail.mark_as_read(msg)
    gmail.download_attachments(msg, '/my_folder')
    gmail.reply(msg, "Received!")

As mentioned before, emails can be filtered using different combinations, separating the operators and their respective values by a blank space.

With the returned messages, we were able to perform various operations for each specific message, such as downloading attachments, replying, etc.

Managing labels

In the Gmail API we have the concept of labels that can be assigned to messages. Using labels, we are able to change the status of an email, the folders where it will be displayed and much more.

With this plugin it is also possible to manage these labels, being able to create new ones, add labels to a message and also remove them.

from botcity.plugins.gmail import BotGmailPlugin, GmailDefaultLabels

# Instantiate the plugin
gmail = BotGmailPlugin(credentials, "<your_gmail_account>")

# Create a new label on email
gmail.create_new_label("My Custom Label")

# Search for all emails with subject: Test Message
messages = gmail.search_messages(criteria="subject:Test Message")

for msg in messages:
    # Returns all labels that the message contains
    print(msg.labels)

    # Adds to the message one of the standard gmail labels and also a custom label, created by the user.
    gmail.add_labels_to_message(msg, default_labels=[GmailDefaultLabels.STARRED], customized_labels=['My Custom Label'])

As demonstrated in the example above, it is possible to add standard Gmail labels to the message, such as STARRED or IMPORTANT, and also add labels created by the user.

The default Gmail labels that can be used are defined as an Enum in the GmailDefaultLabels class, to select a value use GmailDefaultLabels.LABEL_NAME.

The personalized labels must have a unique name, and when used, the exact name of each desired label must be passed in the operation.

Info

To see more details about labels and what are their differences, visit this link.

Using labels as filters

In addition to our criteria string, we can also use email labels as a filter for the messages we want to return

from botcity.plugins.gmail import BotGmailPlugin, GmailDefaultLabels # Usage: GmailDefaultLabels.<LABEL_NAME>

# Instantiate the plugin
gmail = BotGmailPlugin(credentials, "<your_gmail_account>")

# Returning messages that have the "TRASH" label, only messages that are in the trash will be considered
msgs_on_trash = gmail.search_messages(default_labels=[GmailDefaultLabels.TRASH])

# Searching using criteria, default labels and custom labels as filters
msgs = gmail.search_messages(criteria="before:04/04/2022", default_labels=[GmailDefaultLabels.STARRED, GmailDefaultLabels.UNREAD], customized_labels=['My Custom Label 1', 'My Custom Label 2'])

In this way, we can combine and create filters the way we want. Only messages that have these characteristics and are marked with the informed labels will be returned.

We also have the option of not using any labels in the filters. In this case, the messages that are in the INBOX will be considered by default.

Sending messages

In addition to accessing received emails, we are also able to reply, forward and send new messages.

# Instantiate the plugin
gmail = BotGmailPlugin(credentials, "<your_gmail_account>")

# Defining the attributes that will compose the message
to = ["<RECEIVER_ADDRESS_1>", "<RECEIVER_ADDRESS_2>"]
cc = ["<ANOTHER_ADDRESS>"]
subject = "Hello World"
body = "Hello! This is a test message!"
files = ["my_file.txt"]

# Sending the email message
gmail.send_message(subject, body, to, cc, attachments=files, use_html=False)

Replying or forwarding messages

# Searching for all emails that have been starred
messages = gmail.search_messages(default_labels=[GmailDefaultLabels.STARRED])

# For each email, reply or forward depending on the subject
for msg in messages:
    if msg.subject == "Reply this msg!":
        gmail.reply_to_all(msg, "Hey!")
    else:
        gmail.forward(msg, to=["<RECEIVER_ADDRESS_1>", "<RECEIVER_ADDRESS_2>"])