Listen to New Emails in Gmail

In this guide, weโ€™ll:

  1. ๐Ÿ” Connect your Gmail account with Composio
  2. ๐Ÿ›  Enable Triggers to listen to new emails in Gmail
  3. ๐Ÿง  Pass these triggers event payloads to an AI language model to identify bank transactions
  4. โญ Execute an action from Gmail tool to add important label to relevant emails

Tools represent a group of actions specific to an app. Actions are operations you can perform - like starring a repo on GitHub or creating an issue in Linear.

1

Install Libraries

CLI
pip install composio-core composio_openai
2

Connect Your Gmail Account

Weโ€™ll use default as the user id, also known as entity id.

You need to have an active Gmail Integration. Learn how to do this here

composio login 
composio add gmail -e "default"

Donโ€™t forget to set your COMPOSIO_API_KEY and OPENAI_API_KEY in your environment variables.

3

Enable Triggers

composio triggers enable gmail_new_gmail_message
4

Create an Agent

def agent_function(thread_id: str, message: str, sender_mail: str):
    tools = toolset.get_tools(apps=[App.GMAIL])

    response = openai_client.chat.completions.create(
        model="gpt-4o-mini",
        tools=tools,
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant that can parse the email content, identify bank transactions and add the 'important' label to the email. Otherwise, don't do anything.",
            },
            {
                "role": "user",
                "content": f"Thread ID: {thread_id}\nMessage: {message}\nSender: {sender_mail}",
            },
        ],
    )
    result = toolset.handle_tool_calls(response)
    print(result)
5

Create a Trigger Listener

listener = toolset.create_trigger_listener()

@listener.callback(filters={"trigger_name": Trigger.GMAIL_NEW_GMAIL_MESSAGE})
def callback_function(event):
    payload = event.payload
    thread_id = payload.get("threadId")
    message = payload.get("messageText")
    sender_mail = payload.get("sender")
    agent_function(thread_id, message, sender_mail)


print("Starting listener")
listener.wait_forever()

Next Steps

Now that youโ€™ve seen how to use triggers, you can explore the following resources: