> For the complete documentation index, see [llms.txt](https://docs.agenticflow.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.agenticflow.ai/use-cases/workflow/personal-productivity/gmail-auto-labeling-agent.md).

# Gmail Auto-Labeling Workflow

### 1. Use Case Description

**Problem:** Email inbox chaos - hundreds of emails piling up without organization, making it difficult to find important messages and reducing productivity.

**Solution:** An AI-powered workflow that automatically categorizes emails by:

1. Reading email content
2. Analyzing with AI (GPT-4o-mini)
3. Automatically applying the appropriate Gmail label

**Source:** This workflow was ported from N8N to AgenticFlow.

* **N8N Template:** [Basic Automatic Gmail Email Labelling with OpenAI and Gmail API](https://n8n.io/workflows/2740-basic-automatic-gmail-email-labelling-with-openai-and-gmail-api/)

***

### 2. Goal

* ✅ Automatically categorize emails based on content
* ✅ Use AI to determine the most appropriate label
* ✅ Apply existing Gmail labels
* ✅ Keep inbox clean and organized

***

### 3. Use Cases & Triggers

#### When to Use?

| Use Case           | Description                                                           |
| ------------------ | --------------------------------------------------------------------- |
| **Manual**         | Run manually when you want to label a specific email                  |
| **Batch**          | Label multiple emails at once                                         |
| **Auto (Webhook)** | Automatically trigger when new email arrives (requires Pub/Sub setup) |

#### Trigger Options

**Option 1: Manual Run**

* Open workflow → Enter email subject → Click Run

**Option 2: Webhook + Gmail Push (Auto)**

* Gmail receives new email → Pub/Sub → Webhook → Workflow runs automatically
* See Webhook setup instructions below

***

### 4. Workflow Architecture

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                        Gmail Auto-Labeling Agent                            │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  Input: email_subject                                                       │
│           │                                                                 │
│           ▼                                                                 │
│  ┌─────────────────────────────────────┐                                   │
│  │ Step 1: Get All Gmail Labels        │                                   │
│  │ Action: gmail-list-labels           │                                   │
│  └─────────────────────────────────────┘                                   │
│           │                                                                 │
│           ▼                                                                 │
│  ┌─────────────────────────────────────┐                                   │
│  │ Step 2: Search & Get Email          │                                   │
│  │ Action: gmail-search-emails         │                                   │
│  └─────────────────────────────────────┘                                   │
│           │                                                                 │
│           ▼                                                                 │
│  ┌─────────────────────────────────────┐                                   │
│  │ Step 3: AI Decides Label            │                                   │
│  │ Model: GPT-4o-mini                  │                                   │
│  └─────────────────────────────────────┘                                   │
│           │                                                                 │
│           ▼                                                                 │
│  ┌─────────────────────────────────────┐                                   │
│  │ Step 4: Apply Label to Email        │                                   │
│  │ Action: gmail-add-label-to-email    │                                   │
│  └─────────────────────────────────────┘                                   │
│           │                                                                 │
│           ▼                                                                 │
│  Output: status, applied_label, result                                     │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

***

### 5. Workflow Link

**AgenticFlow Workflow:** 👉 <https://agenticflow.ai/app/workspaces/30f2b04d-294f-4110-bf7e-4d405f2bea0c/workflows/6e17510a-16e5-4d43-9595-7b703620d38b/run>

***

### 6. How to Use

#### Step 1: Open Workflow

Access the workflow link above

#### Step 2: Enter Email Subject

1. Open Gmail → Find the email you want to label
2. **Copy the subject** of that email
3. Paste into the **"Email Subject"** field in the workflow

**Example:**

```
[Agenticflow] Your CX Agent is Ready! Let's Bring It to Life 🚀
```

#### Step 3: Run Workflow

Click the **"Run"** button

#### Step 4: Check Results

* View workflow output
* Open Gmail → Verify the email has been labeled

***

### 7. N8N Workflow JSON (Source)

**Link:** <https://n8n.io/workflows/2740-basic-automatic-gmail-email-labelling-with-openai-and-gmail-api/>

```
{
  "nodes": [
    {
      "id": "2a41e2da-19f7-4c31-ab93-3a534db3179e",
      "name": "Gmail Trigger",
      "type": "n8n-nodes-base.gmailTrigger",
      "position": [-360, -260],
      "parameters": {
        "filters": {},
        "pollTimes": {
          "item": [
            {
              "mode": "everyX",
              "unit": "minutes",
              "value": 5
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "a25e0e42-8eab-49c5-a553-797da40eb623",
      "name": "OpenAI Chat Model1",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [-220, -60],
      "parameters": {
        "options": {
          "maxTokens": 4096
        }
      },
      "typeVersion": 1
    },
    {
      "id": "cf437748-a0df-42a2-b1ca-f93162d85bfe",
      "name": "Gmail - read labels",
      "type": "n8n-nodes-base.gmailTool",
      "position": [80, -40],
      "parameters": {
        "resource": "label",
        "returnAll": true,
        "descriptionType": "manual",
        "toolDescription": "Tool to read all existing gmail labels"
      },
      "typeVersion": 2.1
    },
    {
      "id": "152f1970-7a1f-4977-9c21-64b69242d3a9",
      "name": "Gmail - get message",
      "type": "n8n-nodes-base.gmailTool",
      "position": [260, -40],
      "parameters": {
        "messageId": "={{ $fromAI('gmail_message_id', 'id of the gmail message', 'string') }}",
        "operation": "get",
        "descriptionType": "manual",
        "toolDescription": "Tool to read a specific message based on the message ID"
      },
      "typeVersion": 2.1
    },
    {
      "id": "ae09cedc-9675-4080-bcdc-3d6c4e4bc490",
      "name": "Gmail - add label to message",
      "type": "n8n-nodes-base.gmailTool",
      "position": [460, -40],
      "parameters": {
        "labelIds": "={{ $fromAI('gmail_categories', 'array of label ids') }}",
        "messageId": "={{ $fromAI('gmail_message_id') }}",
        "operation": "addLabels",
        "descriptionType": "manual",
        "toolDescription": "Tool to add label to message"
      },
      "typeVersion": 2.1
    },
    {
      "id": "be4a92ab-d3ab-451b-8655-172851f68628",
      "name": "Gmail - create label",
      "type": "n8n-nodes-base.gmailTool",
      "position": [640, -40],
      "parameters": {
        "name": "={{ $fromAI('new_label_name', 'new label name', 'string') }}",
        "resource": "label",
        "operation": "create",
        "descriptionType": "manual",
        "toolDescription": "Tool to create a new label, only use if label does not already exist"
      },
      "typeVersion": 2.1
    },
    {
      "id": "a40466d2-2fe3-4a97-98fe-b14cc38cc141",
      "name": "Gmail labelling agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [-60, -260],
      "parameters": {
        "text": "=Label the email based on the details below:\n{{ JSON.stringify($json) }}",
        "options": {
          "maxIterations": 5,
          "systemMessage": "Objective: Automatically categorize incoming emails based on existing Gmail labels or create a new label if none match..."
        },
        "promptType": "define"
      },
      "typeVersion": 1.7
    }
  ],
  "connections": {
    "Gmail Trigger": {
      "main": [[{"node": "Wait", "type": "main", "index": 0}]]
    },
    "OpenAI Chat Model1": {
      "ai_languageModel": [[{"node": "Gmail labelling agent", "type": "ai_languageModel", "index": 0}]]
    },
    "Gmail - get message": {
      "ai_tool": [[{"node": "Gmail labelling agent", "type": "ai_tool", "index": 0}]]
    },
    "Gmail - read labels": {
      "ai_tool": [[{"node": "Gmail labelling agent", "type": "ai_tool", "index": 0}]]
    },
    "Gmail - create label": {
      "ai_tool": [[{"node": "Gmail labelling agent", "type": "ai_tool", "index": 0}]]
    },
    "Gmail - add label to message": {
      "ai_tool": [[{"node": "Gmail labelling agent", "type": "ai_tool", "index": 0}]]
    }
  }
}
```

***

### 8. Node Mapping: N8N → AgenticFlow

| N8N Node                     | AgenticFlow Equivalent                |
| ---------------------------- | ------------------------------------- |
| Gmail Trigger                | Webhook Trigger + Pub/Sub (or Manual) |
| Gmail - read labels          | MCP: `gmail-list-labels`              |
| Gmail - get message          | MCP: `gmail-search-emails`            |
| OpenAI Chat Model            | Ask AI (llm) node - GPT-4o-mini       |
| Gmail - add label to message | MCP: `gmail-add-label-to-email`       |
| Gmail - create label         | *(Not implemented)*                   |

***

### 9. Debugging Guide

#### Error 1: "Authentication failed: OAuth token expired"

**Cause:** Gmail MCP connection has expired

**Solution:**

1. Go to AgenticFlow → Connections
2. Find your Gmail connection
3. Click **"Reconnect"** or **"Re-authorize"**
4. Sign in again with your Google account

***

#### Error 2: "Invalid id value" or "Thread ID invalid"

**Cause:** Using wrong type of ID

**Solution:**

* Use **Email Subject** instead of Message ID
* Workflow has been updated to use `gmail-search-emails` with subject

***

#### Error 3: "Error parsing arguments: instruction required"

**Cause:** MCP action missing `instruction` field

**Solution:**

* Ensure each MCP action has `instruction` field in `input_params`
* Example:

```
{
  "action": "gmail-list-labels",
  "input_params": {
    "instruction": "List all my Gmail labels with their IDs"
  }
}
```

***

#### Error 4: Email not labeled

**Possible causes:**

* Subject doesn't match exactly
* Label ID doesn't exist

**Solution:**

1. Check Step 2 output - was the email found?
2. Check Step 3 output - what label\_id did AI return?
3. Verify label\_id exists in Step 1 output

***

#### Error 5: Workflow doesn't auto-trigger

**Cause:** Webhook + Gmail Push not configured

**Solution:** See "Auto Trigger Setup" section below

***

### 10. Auto Trigger Setup (Optional)

To make the workflow run automatically when new emails arrive:

#### Step 1: Create Google Cloud Project

1. Go to [console.cloud.google.com](https://console.cloud.google.com/)
2. Create a new project
3. Enable **Gmail API** and **Pub/Sub API**

#### Step 2: Create Pub/Sub Topic

1. Go to Pub/Sub → Create Topic: `gmail-notifications`
2. Add permission for `gmail-api-push@system.gserviceaccount.com` with role `Pub/Sub Publisher`

#### Step 3: Create Webhook Trigger in AgenticFlow

1. Open workflow → "Triggers" tab
2. Create Trigger → Webhook
3. Copy the Webhook URL

#### Step 4: Create Push Subscription

1. Go to Pub/Sub → Create Subscription
2. Select topic `gmail-notifications`
3. Delivery type: **Push**
4. Endpoint URL: Paste AgenticFlow Webhook URL

#### Step 5: Activate Gmail Watch

1. Go to [OAuth Playground](https://developers.google.com/oauthplayground/)
2. Authorize Gmail API scope: `https://mail.google.com/`
3. Send POST request:

```
URL: https://gmail.googleapis.com/gmail/v1/users/me/watch
Body:
{
  "topicName": "projects/YOUR_PROJECT_ID/topics/gmail-notifications",
  "labelIds": ["INBOX"]
}
```

⚠️ **Note:** Gmail Watch expires after 7 days and needs periodic renewal.

***

### 11. Output Schema

```
{
  "status": "completed",
  "applied_label": "CATEGORY_UPDATES",
  "email_found": "{ email content... }",
  "labels_available": "{ list of labels... }",
  "result": "{ apply label result... }"
}
```

***

### 12. Summary

| Item               | Value                                      |
| ------------------ | ------------------------------------------ |
| **Workflow Name**  | Gmail Auto-Labeling Agent                  |
| **Source**         | N8N Template #2740                         |
| **AI Model**       | GPT-4o-mini                                |
| **Input**          | Email Subject                              |
| **Output**         | Label applied to email                     |
| **MCP Connection** | Gmail ()                                   |
| **Setup Time**     | \~5 min (manual) / \~30 min (auto trigger) |

***

### 13. Links

| Resource                 | URL                                                                                                                                            |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| **AgenticFlow Workflow** | [Open Workflow](https://agenticflow.ai/app/workspaces/30f2b04d-294f-4110-bf7e-4d405f2bea0c/workflows/6e17510a-16e5-4d43-9595-7b703620d38b/run) |
| **N8N Template**         | [N8N #2740](https://n8n.io/workflows/2740-basic-automatic-gmail-email-labelling-with-openai-and-gmail-api/)                                    |
| **Gmail API Docs**       | [developers.google.com/gmail/api](https://developers.google.com/gmail/api)                                                                     |
| **AgenticFlow Docs**     | [docs.agenticflow.ai](https://docs.agenticflow.ai/)                                                                                            |
