Automation: Exporting Action Items from Gmail Emails to Trello

Updated on July 5, 2020
butterontoasts profile image

Joann is a software developer who specializes in automating repetitive tasks.

Introduction

In a previous article, I showed you how to create boards, lists, and cards in Trello using Python and the Trello API. We read text files that contain to do lists and automatically exported them to our Trello board.

In this article, I will show you how we can apply this automation to real work scenarios. Work usually involves meetings and minutes are often sent via email. Action items are discussed and later on distributed to the attendees this way but in a sea of emails and heavy workloads, we sometimes:

  • Forget to read it
  • Find it tedious to transfer them to our to do lists manually
  • Have trouble keeping track of which date those minutes are for

To solve these problems, we'll use the Gmail API together with the Trello API. We'll search for emails that have a specific subject, setup a template to identify where the action items are, and export those action items to Trello. This will allow us to manage our tasks efficiently.

Requirements

Python

I'm using Python 3.8.2 but you can use other versions. Some syntax could be different especially for Python 2 versions.

Trello API Key And Token

You need the key and token to connect and make requests to your Trello account. Sign in to your Trello account from the browser and follow the instructions to get your key and token. Take note of the your key and token.

Gmail API Client Configuration

Sign in to your Google account and go to Python Quickstart. Click the "Enable the Gmail API" button, select "Desktop app", and click the "Create" button. Download the client configuration as "credentials.json".

Project Structure

Before we dive into writing code, I want to show you how our project structure looks like so we can avoid confusion on where each script should go.

  • The main.py file is the main script that we will run.
  • The modules folder contains three files:
    • The credentials.json file is downloaded from the Google Developers website.
    • The gmail.py file contains the methods that will assist us in accessing, searching, and reading the emails we need from our Gmail account.
    • The trello.py file contains the methods that will assist us in creating boards, lists, and cards in our Trello board.
  • The requirements.txt file contains the libraries we need to make things work
  • The settings.py file contains the configurations such as key, token, etc.

The project structure.
The project structure.

Setting Up

Create a "settings.py" file with similar contents as in the sample code below.

  1. email_address - Replace this with your Gmail email address.
  2. scopes - We'll only be reading emails so we can keep this as is.
  3. key - The key you get from Trello following the steps in the "Requirements" section above.
  4. token - The token you get from Trello following the steps in the "Requirements" section above.
  5. subject - The subject of the email we'll be looking for.
  6. item_start and item_end - The action items between these two will be retrieved and copied over to Trello.

settings.py

email_address = "email_address"
scopes = ["https://www.googleapis.com/auth/gmail.readonly"]
key = "key"
token = "token"
subject = "Minutes of the Meeting"
minutes_date = "*Date:*"
items_start = "*Action Items*"
items_end = "*Other Notes*"

Here's a list of the libraries we're gonna need. To install them, simply enter "pip install -r requirements.txt" in the command line.

requirements.txt

google-api-python-client==1.7.11
google-auth==1.6.3
google-auth-httplib2==0.0.3
google-auth-oauthlib==0.4.1

Using the Trello API

The "trello.py" script will be used to create boards, lists, and cards. For a full explanation on this script, you may refer to the previous tutorial.

trello.py

import requests
from settings import key, token


def create_board(board_name):
    """
    Creates a board based on the given board name.
    """

    url = "https://api.trello.com/1/boards/"
    querystring = {"name": board_name, "key": key, "token": token}
    response = requests.request("POST", url, params=querystring)
    board_id = response.json()["shortUrl"].split("/")[-1].strip()
    return board_id


def create_list(board_id, list_name):
    """
    Creates a list based on the given list name.
    """

    url = f"https://api.trello.com/1/boards/{board_id}/lists"
    querystring = {"name": list_name, "key": key, "token": token}
    response = requests.request("POST", url, params=querystring)
    list_id = response.json()["id"]
    return list_id


def create_card(list_id, card_name):
    """
    Creates a card based on the given card name.
    """

    url = "https://api.trello.com/1/cards"
    querystring = {"name": card_name, "idList": list_id, "key": key, "token": token}
    response = requests.request("POST", url, params=querystring)
    card_id = response.json()["id"]
    return card_id

Using the Gmail API

The "gmail.py" script will be used to access the emails in our Gmail account.

gmail.py

import os.path
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from apiclient import errors


def create_service(scopes):
    """
    Creates a Gmail service based on the credentials.json found in the current directory.
    """

    creds = None
    if os.path.exists("modules/token.pickle"):
        with open("modules/token.pickle", "rb") as token:
            creds = pickle.load(token)

    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(
                "modules/credentials.json", scopes)
            creds = flow.run_local_server(port=0)
        with open("modules/token.pickle", "wb") as token:
            pickle.dump(creds, token)

    service = build("gmail", "v1", credentials=creds)
    return service


def query_messages(service, user_id, subject):
    """
    Searches the mailbox for a matching subject.
    """

    try:
        query = f"subject: {subject}"
        response = service.users().messages().list(userId=user_id, q=query).execute()
        messages = []
        if "messages" in response:
            messages.extend(response["messages"])
        while "nextPageToken" in response:
            page_token = response["nextPageToken"]
            response = service.users().messages().list(userId=user_id, q=query, \
                                                       pageToken=page_token).execute()
            messages.extend(response["messages"])
        return messages
    except errors.HttpError as error:
        print("An error occurred.", error)


def read_message(service, user_id, msg_id):
    """
    Read the contents of the email.
    """

    try:
        message = service.users().messages().get(userId=user_id, id=msg_id).execute()
        return message
    except errors.HttpError as error:
        print("An error occurred.", error)

Sample Email

Below are the sample emails we will use. Notice that the words we are looking for are in bold text - Date:, Action Items, and Other Notes. Gmail wraps words in asterisks (*) to indicate that they are in bold text. This is why in our "settings.py" file, we look for "*Action Items*" instead of simply "Action Items".

Two sample emails with the same subject but different contents.
Two sample emails with the same subject but different contents.

Writing the Main Script

Now that we created the modules needed to access both Trello and Gmail, we will bring them together in a main script.

In line 8, we query the mailbox for any emails that match the subject in the "settings.py" file. In this case, the subject it will look for is "Minutes of the Meeting".

From line 11, we loop through the emails that matched our query and read their contents. Inside this loop, the following steps are performed:

  • In lines 17 to 18, we split the body of the email line by line, look for the line that contains the date label specified in the "settings.py". In this case, it's "*Date:*". We retrieve only the part that contains the actual date and use it later on to name our Trello board.
  • In line 19, we retrieve all the texts in the body from the item_start to item_end. In our "settings.py" file, these are "*Action Items*" and "*Other Notes*"
  • In line 22, we create a board with the subject and date combination as the title and in the same line, we also create a list with "Action Items" as the title.
  • From line 23, we read the lines under "Action Items", clean them up, and create a card for each of them.

main.py

import base64
from modules.gmail import create_service, query_messages, read_message
from modules.trello import create_board, create_list, create_card
from settings import email_address, scopes, subject, minutes_date, items_start, items_end


service = create_service(scopes)
messages = query_messages(service, email_address, subject)

# Go through each email that matches the subject
for message in messages:
    body = read_message(service, email_address, message.get("id"))
    message = base64.b64decode([part["body"]["data"] for part in body["payload"]["parts"] \
                               if part["mimeType"] == "text/plain"][0]).decode("utf-8")

    # Find the parts of the message from items_start to items_end inclusive
    lines = message.split("\r\n")
    subject_date = next(line.split()[1].replace("'", "") for line in lines if minutes_date in line)
    lines = lines[lines.index(items_start): lines.index(items_end)]

    # Create Trello board and list
    list_id = create_list(create_board(f"{subject} - {subject_date}"), items_start.replace("*", ""))
    for item in lines[1:-1]:
        item = item.strip()
        if item != "":
            create_card(list_id, item[2:])

Running main.py

When you first run the code, a window will pop up asking you to grant access to your email. If you have multiple Google accounts logged in, simply select the account you indicated in the email_address variable in the "settings.py" file.

After this, you will notice that a "token.pickle" file is created in your modules folder. The next time you run the script, you will no longer be asked to grant access. If you want to use a different email address, simply change the email_address value, replace the "credentials.json" file, and delete the "token.pickle" file so that you will be prompted to grant access again where you can select a different account.

Finally

When you access your Trello, you will find that two boards are created with different dates. Each board has a list named "Action Items" and under it are the actual items. You can modify the code to suit your needs. Maybe you only want one board with multiple lists where each list represents one date or you want to use the actual date the email was sent instead of what's in the body.

Two boards with different dates.
Two boards with different dates.
The contents of the two boards.
The contents of the two boards.

© 2020 Joann Mistica

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)