AutomationFlowsAI & RAG › Classify Gmail Emails with Openai and Send Urgent Telegram Alerts

Classify Gmail Emails with Openai and Send Urgent Telegram Alerts

ByDr. Firas @drfiras on n8n.io

This workflow polls Gmail for unread messages, uses OpenAI to classify each email into one of six categories based on content and prior sender history, applies the matching Gmail label, and sends a Telegram alert when an email is classified as requiring a reply. Polls Gmail…

Event trigger★★★★☆ complexityAI-powered22 nodesGmail TriggerGmailAgentOpenAI ChatGmail ToolOutput Parser StructuredTelegram
AI & RAG Trigger: Event Nodes: 22 Complexity: ★★★★☆ AI nodes: yes Added:

This workflow corresponds to n8n.io template #17378 — we link there as the canonical source.

This workflow follows the Agent → Gmail recipe pattern — see all workflows that pair these two integrations.

The workflow JSON

Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →

Download .json
{
  "id": "r5xLLfFuVlxBShen",
  "meta": {
    "builderVariant": "mcp",
    "aiBuilderAssisted": true
  },
  "name": "Classify Gmail messages with AI and alert urgent emails via Telegram",
  "tags": [],
  "nodes": [
    {
      "id": "2da94c94-cb0e-43ec-8d0f-efb21fcc06e1",
      "name": "Gmail Trigger",
      "type": "n8n-nodes-base.gmailTrigger",
      "position": [
        0,
        208
      ],
      "parameters": {
        "simple": false,
        "filters": {
          "readStatus": "unread"
        },
        "options": {},
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        }
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.4
    },
    {
      "id": "6cd2fcbe-ff9a-4320-9ec3-e7be8f5aeca6",
      "name": "Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        224,
        208
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "cfg-owner-email",
              "name": "owner_email",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Your Gmail address, e.g. you@gmail.com__>"
            },
            {
              "id": "cfg-ai-model",
              "name": "ai_model",
              "type": "string",
              "value": "gpt-4o-mini"
            },
            {
              "id": "cfg-enable-alerts",
              "name": "enable_telegram_alerts",
              "type": "boolean",
              "value": true
            },
            {
              "id": "cfg-telegram-chat-id",
              "name": "telegram_chat_id",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Your Telegram chat ID, ask @get_id_bot__>"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "a8d57ee0-6ee5-40c9-b13e-aa0748bbbd0f",
      "name": "Get Gmail Labels",
      "type": "n8n-nodes-base.gmail",
      "position": [
        448,
        208
      ],
      "parameters": {
        "resource": "label",
        "returnAll": true
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "d888acfa-f1f9-4a3e-9018-fd9024f69e42",
      "name": "Aggregate Gmail Labels",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        672,
        208
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData",
        "destinationFieldName": "labels"
      },
      "typeVersion": 1
    },
    {
      "id": "e48b3990-23b0-4e14-994d-9844e163255b",
      "name": "Get Full Email",
      "type": "n8n-nodes-base.gmail",
      "position": [
        896,
        208
      ],
      "parameters": {
        "simple": false,
        "options": {},
        "messageId": "={{ $('Gmail Trigger').item.json.id }}",
        "operation": "get"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "f6a3a977-02aa-452e-b830-f96dbf6ec898",
      "name": "Classify Email",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        1248,
        208
      ],
      "parameters": {
        "text": "=Classify the following email.\n\nSender email: {{ $json.from.value[0].address }}\nSender name: {{ $json.from.value[0].name }}\nDirect recipients (To): {{ $json.to?.value?.map(r => r.address).join(\", \") }}\nSubject: {{ $json.subject }}\nBody (plain text): {{ $json.text }}\nExisting Gmail labels: {{ ($json.labelIds || []).join(\", \") }}\nList-Unsubscribe header: {{ $json.headers?.[\"list-unsubscribe\"] }}\nPrecedence header: {{ $json.headers?.precedence }}\nIn-Reply-To header: {{ $json.headers?.[\"in-reply-to\"] }}",
        "options": {
          "maxIterations": 6,
          "systemMessage": "=You are an email triage assistant for {{ $('Configuration').item.json.owner_email }}.\n\nObjective: read the email data provided and assign exactly ONE label from: To Respond, FYI, Notification, Marketing, Meeting Update, Comment.\n\nBefore deciding, use your tools to check whether there is prior email history with the sender (\"Search Emails From Sender\") and whether the owner has previously emailed this sender (\"Check Sent To Sender\"). No prior history in either direction is a strong signal of a cold, unsolicited email (likely Marketing unless it is an exceptionally personalized, high-value opportunity).\n\nLabel definitions:\n- To Respond: requires a direct, timely reply from the owner (direct question, assigned task, active conversation).\n- FYI: for awareness only, no reply needed (owner CC'd, informational update, known non-critical newsletter).\n- Notification: important non-promotional update from a known service/account (ToS/DPA changes, outages, security alerts, billing).\n- Marketing: unsolicited promotional or sales content, especially with no prior email history with the sender.\n- Meeting Update: calendar-related updates (accepted/declined/updated/cancelled invitations).\n- Comment: a comment or feedback notification on a document, task, or system.\n\nAn unsubscribe link or \"Precedence: bulk\" header alone does NOT mean Marketing \u2014 a legitimate service Notification or FYI newsletter can carry those too. Weigh prior history and actual content together.\n\nAlways return your best single label with a confidence score and a one-sentence reason."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "187e9378-a621-44a4-9472-314f56bdd081",
      "name": "OpenAI Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1008,
        416
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Configuration').item.json.ai_model }}"
        },
        "options": {
          "temperature": 0.1
        },
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "ffd3537e-819b-440c-8270-a38e688e4801",
      "name": "Search Emails From Sender",
      "type": "n8n-nodes-base.gmailTool",
      "position": [
        1200,
        432
      ],
      "parameters": {
        "limit": 5,
        "filters": {
          "q": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('query', 'Gmail search query to find prior emails FROM this sender, formatted like \"from:sender@example.com\"') }}",
          "readStatus": "both"
        },
        "operation": "getAll"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "54fe9411-1d66-483a-988f-4d1b307845c9",
      "name": "Check Sent To Sender",
      "type": "n8n-nodes-base.gmailTool",
      "position": [
        1376,
        432
      ],
      "parameters": {
        "limit": 5,
        "filters": {
          "q": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('query', 'Gmail search query to find emails previously SENT to this sender, formatted like \"to:sender@example.com\"') }}",
          "labelIds": [
            "SENT"
          ]
        },
        "operation": "getAll"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "0a46c6fd-734a-4640-884c-f593f377b4d5",
      "name": "Classification Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        1504,
        432
      ],
      "parameters": {
        "autoFix": true,
        "schemaType": "manual",
        "inputSchema": "{\"type\":\"object\",\"properties\":{\"category\":{\"type\":\"string\",\"enum\":[\"To Respond\",\"FYI\",\"Notification\",\"Marketing\",\"Meeting Update\",\"Comment\"],\"description\":\"The single best-fitting label for this email\"},\"confidence\":{\"type\":\"number\",\"minimum\":0,\"maximum\":1,\"description\":\"Confidence score for the classification\"},\"reasoning\":{\"type\":\"string\",\"description\":\"One short sentence explaining why this category was chosen\"}},\"required\":[\"category\",\"confidence\",\"reasoning\"]}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "9246a70d-ff6d-483f-82eb-7c37faa8156b",
      "name": "OpenAI Fixer Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1504,
        640
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Configuration').item.json.ai_model }}"
        },
        "options": {
          "temperature": 0
        },
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "9394f851-e349-4e81-bd82-51a0db24f62b",
      "name": "Map Category to Label",
      "type": "n8n-nodes-base.set",
      "position": [
        1712,
        208
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "map-category",
              "name": "category",
              "type": "string",
              "value": "={{ $json.output.category }}"
            },
            {
              "id": "map-confidence",
              "name": "confidence",
              "type": "number",
              "value": "={{ $json.output.confidence }}"
            },
            {
              "id": "map-reasoning",
              "name": "reasoning",
              "type": "string",
              "value": "={{ $json.output.reasoning }}"
            },
            {
              "id": "map-label-id",
              "name": "label_id",
              "type": "string",
              "value": "={{ $('Aggregate Gmail Labels').item.json.labels.find(l => l.name === $json.output.category)?.id ?? '' }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "af39179e-537e-48dd-bd45-5a959e0815c1",
      "name": "Has Valid Label?",
      "type": "n8n-nodes-base.if",
      "position": [
        1936,
        208
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 1,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "operator": {
                "type": "string",
                "operation": "notEmpty"
              },
              "leftValue": "={{ $json.label_id }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "d8c88875-2d8d-46fa-a066-64dbf2f34e9c",
      "name": "Apply Gmail Label",
      "type": "n8n-nodes-base.gmail",
      "position": [
        2160,
        144
      ],
      "parameters": {
        "labelIds": [
          "={{ $json.label_id }}"
        ],
        "messageId": "={{ $('Get Full Email').item.json.id }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "86f15143-94de-4561-a407-b0525b2b2fca",
      "name": "Is Urgent & Alerts On?",
      "type": "n8n-nodes-base.if",
      "position": [
        2384,
        144
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 1,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $('Map Category to Label').item.json.category }}",
              "rightValue": "To Respond"
            },
            {
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $('Configuration').item.json.enable_telegram_alerts }}",
              "rightValue": true
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "19df75b0-31c0-4d8e-8fba-6cb1e2ea37b5",
      "name": "Send Telegram Alert",
      "type": "n8n-nodes-base.telegram",
      "position": [
        2608,
        208
      ],
      "parameters": {
        "text": "={{ $('Map Category to Label').item.json.category === \"To Respond\" ? \"\ud83d\udd34 <b>Action needed - email to respond to</b>\\n\\nFrom: \" + $('Get Full Email').item.json.from.text + \"\\nSubject: \" + $('Get Full Email').item.json.subject + \"\\n\\n\" + $('Get Full Email').item.json.text.slice(0, 300) : \"\u26a0\ufe0f <b>Unclassified email - manual review needed</b>\\n\\nFrom: \" + $('Get Full Email').item.json.from.text + \"\\nSubject: \" + $('Get Full Email').item.json.subject }}",
        "chatId": "={{ $('Configuration').item.json.telegram_chat_id }}",
        "additionalFields": {
          "parse_mode": "HTML",
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "0176a501-454e-441c-b1fe-bb54761ce47d",
      "name": "Sticky Note 766a844c",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -592,
        -336
      ],
      "parameters": {
        "color": 4,
        "width": 480,
        "height": 1636,
        "content": "# Classify Gmail messages with AI and alert urgent emails via Telegram\n# \ud83d\udce5  [Open full documentation on Notion](https://automatisation.notion.site/Course-Classify-Gmail-messages-with-AI-and-alert-urgent-emails-via-Telegram-39e3d6550fd9814ea2c3cb1642e4b15f)\n\n## How it works\nMonitors your Gmail inbox, checks prior email history with the sender, then uses an OpenAI-powered agent to classify each new message into one of 6 categories (To Respond, FYI, Notification, Marketing, Meeting Update, Comment). The matching Gmail label is applied automatically, and a Telegram alert fires instantly for emails that need a direct reply.\n\n## Setup\n1. Connect your Gmail credential on every Gmail node.\n2. Connect your OpenAI credential on the two model nodes.\n3. In Gmail, create 6 labels with these EXACT names: To Respond, FYI, Notification, Marketing, Meeting Update, Comment.\n4. Open **Configuration** and set your owner_email, ai_model, and (optionally) your Telegram chat ID for urgent alerts.\n5. Connect your Telegram credential on the Send Telegram Alert node and activate the workflow.\n\n## Requirements\n- A Gmail account (OAuth2 credential in n8n)\n- An OpenAI API key with access to gpt-4o-mini (or your preferred model)\n- A Telegram bot token + chat ID (only needed if Telegram alerts are enabled)\n\n## Customization\n- Change `ai_model` in Configuration to use a different OpenAI model.\n- Toggle `enable_telegram_alerts` off if you only want automatic labeling.\n- Add or rename categories by editing the classifier schema and creating matching Gmail labels.\n\nNeed help customizing?\nContact me for consulting and support : [Linkedin](https://www.linkedin.com/in/doctor-firass/)\n\n# MY NEW YOUTUBE CHANNEL\n\ud83d\udc49 [Subscribe to my new YouTube channel](https://www.youtube.com/@DrFiras_AI). Here I'll share videos and Shorts with practical tutorials and FREE templates for n8n.\n\n[![The AI Doctor](https://www.dr-firas.com/the-ai-doctor.png)](https://www.youtube.com/@DrFiras_AI)"
      },
      "typeVersion": 1
    },
    {
      "id": "bd1d408e-fb81-4581-a3a9-f635d3121612",
      "name": "Sticky Note 9878a774",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        80,
        -192
      ],
      "parameters": {
        "color": 7,
        "width": 300,
        "height": 200,
        "content": "## Trigger & Configuration\nPolls Gmail every minute for new messages and centralizes every setting you might change in one place."
      },
      "typeVersion": 1
    },
    {
      "id": "4ed1fe6e-4d42-42e0-966a-02b0b57f79e8",
      "name": "Sticky Note d451b828",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        608,
        -208
      ],
      "parameters": {
        "color": 7,
        "width": 300,
        "height": 232,
        "content": "## Resolve Gmail label IDs\nFetches your Gmail labels and aggregates them into a single lookup list, so categories are matched by NAME, never by hardcoded ID."
      },
      "typeVersion": 1
    },
    {
      "id": "19b910ea-29b2-4d3e-9534-b586cf052717",
      "name": "Sticky Note 224af9b1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1056,
        -176
      ],
      "parameters": {
        "color": 7,
        "width": 300,
        "height": 200,
        "content": "## Retrieve full email\nFetches the complete email body, headers, and sender/recipient details for the triggered message."
      },
      "typeVersion": 1
    },
    {
      "id": "f3f35b4a-6c52-445c-9836-0a29203cd0b4",
      "name": "Sticky Note b6699edf",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1536,
        -176
      ],
      "parameters": {
        "color": 7,
        "width": 300,
        "height": 216,
        "content": "## AI classification\nAn agent checks prior email history with the sender via two Gmail tools, then returns a structured category, confidence score, and reasoning."
      },
      "typeVersion": 1
    },
    {
      "id": "2486a841-968d-47f7-adac-2e549b4747b0",
      "name": "Sticky Note 83b0b97f",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2032,
        -208
      ],
      "parameters": {
        "color": 7,
        "width": 300,
        "height": 248,
        "content": "## Apply label & alert\nMaps the AI category to the matching Gmail label ID, applies it, and sends a Telegram alert for emails that need a reply (or that could not be classified)."
      },
      "typeVersion": 1
    }
  ],
  "active": true,
  "settings": {
    "binaryMode": "separate",
    "availableInMCP": true,
    "executionOrder": "v1"
  },
  "versionId": "40ed5348-dcb7-4075-ab63-e3a44e47b6f5",
  "nodeGroups": [],
  "connections": {
    "OpenAI Model": {
      "ai_languageModel": [
        [
          {
            "node": "Classify Email",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Configuration": {
      "main": [
        [
          {
            "node": "Get Gmail Labels",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail Trigger": {
      "main": [
        [
          {
            "node": "Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Classify Email": {
      "main": [
        [
          {
            "node": "Map Category to Label",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Full Email": {
      "main": [
        [
          {
            "node": "Classify Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Gmail Labels": {
      "main": [
        [
          {
            "node": "Aggregate Gmail Labels",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has Valid Label?": {
      "main": [
        [
          {
            "node": "Apply Gmail Label",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send Telegram Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply Gmail Label": {
      "main": [
        [
          {
            "node": "Is Urgent & Alerts On?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Fixer Model": {
      "ai_languageModel": [
        [
          {
            "node": "Classification Output Parser",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Check Sent To Sender": {
      "ai_tool": [
        [
          {
            "node": "Classify Email",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Map Category to Label": {
      "main": [
        [
          {
            "node": "Has Valid Label?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate Gmail Labels": {
      "main": [
        [
          {
            "node": "Get Full Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is Urgent & Alerts On?": {
      "main": [
        [
          {
            "node": "Send Telegram Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search Emails From Sender": {
      "ai_tool": [
        [
          {
            "node": "Classify Email",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Classification Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Classify Email",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    }
  }
}

Credentials you'll need

Each integration node will prompt for credentials when you import. We strip credential IDs before publishing — you'll add your own.

Pro

For the full experience including quality scoring and batch install features for each workflow upgrade to Pro

About this workflow

This workflow polls Gmail for unread messages, uses OpenAI to classify each email into one of six categories based on content and prior sender history, applies the matching Gmail label, and sends a Telegram alert when an email is classified as requiring a reply. Polls Gmail…

Source: https://n8n.io/workflows/17378/ — original creator credit. Request a take-down →

More AI & RAG workflows → · Browse all categories →

Related workflows

Workflows that share integrations, category, or trigger type with this one. All free to copy and import.

AI & RAG

Inbox Guardian. Uses gmailTrigger, lmChatOpenAi, agent, textClassifier. Event-driven trigger; 66 nodes.

Gmail Trigger, OpenAI Chat, Agent +12
AI & RAG

Automate your personal productivity with this intelligent n8n workflow that integrates Telegram, Google Sheets, and OpenAI (GPT-4o). This system uses multiple AI agents to manage work hours, tasks, fi

Agent, OpenAI Chat, Telegram +9
AI & RAG

This n8n workflow automates sales processes using AI agents integrated with Airtable as a CRM and Gmail for email handling. It consists of two main workflows: one for handling Airtable status changes

Airtable Trigger, Agent, OpenAI Chat +9
AI & RAG

An AI-powered Gmail assistant built with n8n that automatically labels emails, learns from your decisions, and safely improves over time using human-in-the-loop training.

Agent, Output Parser Structured, OpenAI Chat +6
AI & RAG

This n8n workflow automates email management by classifying incoming messages, drafting replies, and sending alerts—all powered by AI.

Sentiment Analysis, Lm Chat Azure Open Ai, Gmail +6