Skip to main content

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:

Tools

Checkout our toolset of 250+ LLM ready tools to build powerful AI applications

Connections

Learn how to create and manage connections for your users

Compatible Agentic Frameworks

Integrate with popular agentic frameworks

Kits

Composio SWE Kit (#4 on SWE bench) - Your ultimate coding companion

Triggers

Subscribe to triggers to execute actions automatically

Other Concepts

Learn about workspace environments, using CLI & other concepts