ChatGPTSalesCustomer supportAI score · PendingAI-assisted edit · no obvious prompt-injection riskn8n.io

Auto-Analyze, Classify, and Summarize Gmail with n8n, OpenAI RAG, and Google Sheets

Gmail new-mail trigger → extract & clean → RAG vector retrieval classification → Google Sheets storage → self-learning taxonomy update → Telegram audio summary notification

Some experienceStepsWorkflowPromptTip
Who
Sales, support, or ops teams who need to automate high-volume Gmail processing with a custom taxonomy
You get
New emails are automatically extracted, classified via RAG against historical examples, summarized, and logged to Google Sheets; an audio summary is pushed to Telegram; new categories auto-extend the taxonomy with admin alerts
You need
n8n · gmail · google-sheets · telegram

Constraints

Prerequisites: n8n instance (Cloud or self-hosted), Google account (Gmail + Sheets), OpenAI API account, Telegram Bot. Required credentials: Gmail OAuth2, Google Sheets OAuth2, OpenAI API, Telegram API. First run must be executed manually to populate the in-memory vector store. Costs depend on OpenAI API usage and n8n hosting plan.

What they did

Author amirhoseinzahedi published an n8n workflow template. The template listens for new emails via Gmail Trigger, extracts and cleans message content, then uses historical classification examples from Google Sheets to build an in-memory vector store serving as a RAG knowledge base. An AI Agent (OpenAI gpt-4.1-mini), constrained by a detailed system prompt, prioritizes retrieved taxonomy examples to classify emails, generate summaries, extract keywords, and assign confidence scores, outputting strict JSON. Parsed results are stored in Google Sheets. If a new category or subcategory is detected, the taxonomy dataset is automatically expanded and the admin is notified via Telegram. An OpenAI audio summary is also generated and pushed to Telegram.

How it went

Source report (author_report): the template delivers fully automated Gmail monitoring, RAG email classification, taxonomy consistency enforcement, automatic keyword extraction and confidence scoring, self-updating category knowledge base, Google Sheets email database, AI-generated voice summaries, Telegram admin notifications, and continuously improving classification accuracy. Published on n8n.io with status published, created 2026-02-21.

Worth knowing

1. This site has not run or verified the template (reproduction=not_tested); actual results depend on credential setup and API availability. 2. The vector store is in-memory; it may need re-initialization after n8n instance restarts. The source recommends a manual first run to populate it. 3. Google Sheets documentId and Telegram chatId in the source are template placeholders and must be replaced with real values. 4. Classification quality heavily depends on the quantity and representativeness of initial Tagging Samples; insufficient examples will degrade results. 5. OpenAI audio generation (TTS) is billed per character; high-frequency email scenarios require cost monitoring. 6. The template uses n8n's AI Agent node (LangChain integration), which requires an n8n version supporting LangChain nodes; specific version requirements are not stated in the source. 7. The system prompt demands strict JSON output, but format errors may still occur due to model behavior. Adding error handling or a JSON repair node before Parse AI analysis result is recommended by this site, though not present in the source.

n8n workflow template

Structure checked · Not run-tested

Use “Import from File” in n8n, or copy the JSON and paste it into the editor. Connect your own accounts, then try test data. The template is inactive by default.

Setup and test checklist

Credentials to connect

  • OpenAI Chat Model node: connect OpenAI API credentials.
  • Gmail Trigger node: connect Gmail OAuth2 credentials.
  • Get row(s) in sheet node: connect Google Sheets OAuth2 credentials.
  • Fetch full Gmail message node: connect Gmail OAuth2 credentials.
  • Store processed email node: connect Google Sheets OAuth2 credentials.
  • Load taxonomy dataset node: connect Google Sheets OAuth2 credentials.
  • Append new taxonomy entry node: connect Google Sheets OAuth2 credentials.
  • Notify admin about taxonomy update node: connect Telegram API credentials.
  • Generate audio summary node: connect OpenAI API credentials.
  • Send audio summary to Telegram node: connect Telegram API credentials.
  • Create embeddings (OpenAI) node: connect OpenAI API credentials.

Configuration to replace

  • Source template is n8n public workflow #13568 (~29 nodes). Keep inactive after import; verify triggers, expressions and external API endpoints.
  • Sticky-note guidance is informational; replace placeholders with your own accounts, sheet schemas or channel IDs.

Test input and expected output

  • Manually run the main path once in a test workspace and confirm credentialed nodes authenticate without errors.
  • Drive one synthetic/redacted sample through and check output fields and downstream writes before enabling in production.

Template changes

  • Author credential bindings, webhookId and execution data are removed; the workflow is inactive. Nodes, connections and original prompts are preserved. Not run-tested in n8n.
  • No business-logic edits; verify keys, quotas and privacy compliance before use.

Template retrieved: 2026-10-24

Steps

  1. Configure trigger and credentials

    Create the following credentials in n8n: Gmail OAuth2 (for trigger and message retrieval), Google Sheets OAuth2 (for storage and taxonomy dataset), OpenAI API (for chat, embeddings, and audio generation), Telegram API (for notifications). Add a Gmail Trigger node set to poll every minute. Add a Fetch full Gmail message node to retrieve the full message using messageId.

  2. Extract and normalize email fields

    Add a Normalize email fields (Edit Fields/Set) node to extract and map: id, date, sender (from.value[0].name), email (from.value[0].address), subject, content (using html.removeTags() to strip HTML). Ensure plain-text output for downstream AI processing.

  3. Prepare the RAG taxonomy knowledge base (manual first run)

    Create two sheets in Google Sheets: Sheet 1 'Email Log' with columns date, email, name, subject, summarized text, category, subcategory, keywords; Sheet 2 'Tagging Samples' with columns id, subject, email_text, category, subcategory, keywords. Add a Get row(s) in sheet node to read the full Tagging Samples table. Add a Prepare taxonomy documents node to concatenate subject and email_text as documents. Add a Create embeddings (OpenAI) node to generate vector embeddings. Add a Vector store — taxonomy index node in insert mode with memoryKey=email_tagging. Add a Vector store retriever (RAG tool) node in retrieve-as-tool mode (topK=1) for the Agent to call. Manually click 'Execute workflow' once to populate the vector store before activation.

  4. Configure the AI analysis Agent (RAG classification and summarization)

    Add an Analyze email with RAG agent (AI Agent) node, connect OpenAI Chat Model (gpt-4.1-mini) as the language model, and connect Vector store retriever as a tool. In the Agent's text field, input the email variables. In options.systemMessage, paste the system prompt. The prompt instructs the model to: use retrieved vector-store examples as the sole source of truth for taxonomy; prefer existing categories and only create new ones when no reasonable match exists; output strict JSON appending summary, short_message, category, subcategory, keywords, confidence, new_category, new_subcategory; and perform internal validation before responding.

    Execution prompt · Source text。AI Agent node text input field (User Message); preserve n8n expression syntax

    =sender: {{ $json.sender }}
    email: {{ $json.email }}
    date: {{ $json.date }}
    subject: {{ $json.subject }}
    content: {{ $json.content }}

    Execution prompt · Source text。AI Agent node options.systemMessage field (System Prompt)

    =You are an email analysis, classification, and summarization assistant operating inside an automated workflow.
    
    You will receive ONE incoming email object as input.
    
    Your task is to analyze the email and RETURN THE SAME OBJECT with additional structured fields appended.
    
    --------------------------------------------------
    PRIMARY OBJECTIVES
    --------------------------------------------------
    
    1. Summarize the email content in ONE short paragraph (maximum 3 sentences).
    
    2. Classify the email using semantic context retrieved from "Simple Vector Store1".
    
    3. The retrieved examples represent the OFFICIAL taxonomy and are the PRIMARY SOURCE OF TRUTH for categories and subcategories.
    
    4. Extract up to 5 meaningful keywords representing the main topics of the email.
    
    5. Provide a confidence score between 0 and 1 indicating classification certainty.
    
    --------------------------------------------------
    CLASSIFICATION RULES (STRICT)
    --------------------------------------------------
    
    - ALWAYS prefer categories and subcategories found in retrieved examples.
    - DO NOT invent new categories or subcategories unless no reasonable semantic match exists.
    - Retrieved examples have higher authority than general model knowledge.
    - If similarity is weak, still choose the closest existing category and LOWER the confidence score.
    - Only create a new category or subcategory when NO retrieved example reasonably matches the email topic.
    
    Decision priority order:
    1) Retrieved vector store examples (highest priority)
    2) Semantic meaning of the email
    3) General reasoning (last resort)
    
    --------------------------------------------------
    TAXONOMY CONSISTENCY CHECK (MANDATORY)
    --------------------------------------------------
    
    After selecting a category and subcategory:
    
    1. Compare the selected category against ALL categories present in the retrieved examples from "Simple Vector Store1".
    
    2. If the selected category DOES NOT appear in retrieved examples from knowledge_base and you generated new one:
       set new_category = true
       otherwise set new_category = false.
    
    3. If the category exists but the selected subcategory DOES NOT appear in retrieved examples from knowledge_base and you generated new one:
       set new_subcategory = true
       otherwise set new_subcategory = false.
    
    4. This decision MUST be based ONLY on retrieved examples, not on general knowledge.
    
    --------------------------------------------------
    CONFIDENCE SCORING
    --------------------------------------------------
    
    0.90–1.00 → strong semantic match with retrieved examples
    0.70–0.89 → clear topic with minor ambiguity
    0.50–0.69 → weak similarity but reasonable classification
    0.00–0.49 → uncertain classification
    
    Lower confidence when retrieved similarity is weak or ambiguous.
    
    --------------------------------------------------
    OUTPUT REQUIREMENTS (CRITICAL)
    --------------------------------------------------
    
    - Output MUST be valid JSON ONLY.
    - DO NOT include markdown, explanations, comments, or extra text.
    - DO NOT remove, rename, or modify any existing input fields.
    - Preserve all original fields exactly as received.
    - Append ONLY the following fields:
    
    {
      "summary": "short paragraph summary",
      "short_message": "1 long line summary",
      "category": "main category",
      "subcategory": "specific subcategory",
      "keywords": ["keyword1","keyword2","keyword3"],
      "confidence": 0.0,
      "new_category": false,
      "new_subcategory": false
    }
    
    --------------------------------------------------
    NEW CATEGORY FLAGS
    --------------------------------------------------
    
    - new_category = true ONLY if the selected category is NOT present in retrieved examples.
    - new_subcategory = true ONLY if the category exists but the subcategory is NOT present in retrieved examples.
    
    --------------------------------------------------
    FINAL VALIDATION STEP (MANDATORY)
    --------------------------------------------------
    
    Before responding, internally verify:
    
    ✓ Output is valid JSON
    ✓ No missing commas or trailing text
    ✓ All original input fields remain unchanged
    ✓ Exactly the required fields were appended
    ✓ No additional fields were added
    ✓ Boolean fields contain true or false values only
    ✓ confidence is a number between 0 and 1
    
    If validation fails, correct the output before responding.
  5. Parse results and store in Google Sheets

    Add a Parse AI analysis result (Edit Fields/Set) node to parse the Agent's JSON output with parseJson(), mapping to: sender, email, date, subject, content (summary), short message, category, subcategory, keyword (keywords.join()), confidence, new category, new subcategory. Then add a Store processed email (Google Sheets) node in append mode to write into the Email Log sheet, with field mappings matching the Sheet 1 column structure from Step 3.

  6. Self-learning taxonomy update and admin notification

    Add a Check for new taxonomy items (If) node to test whether new category or new subcategory equals "true". On the true branch: add Load taxonomy dataset to read existing Tagging Samples; add Get next taxonomy ID (Code node, Python) to compute max id; add Append new taxonomy entry to write the new category/subcategory into Tagging Samples; add Notify admin about taxonomy update (Telegram) to send a text alert.

    Execution prompt · Source text。Telegram node Notify admin about taxonomy update text field

    =New category/subcategory added:
    {{ $json.category }} / {{ $json.subcategory }}
  7. Generate audio summary and push to Telegram

    On the false branch of Check for new taxonomy items (or in parallel), add a Generate audio summary (OpenAI) node with resource set to audio and input from the Store processed email summarized text. Then add a Send audio summary to Telegram node with operation set to sendAudio, binaryData=true, caption containing sender, formatted date, and subject, and fileName set to "email bite". Replace chatId with your actual Telegram user or group ID.

Prompt you can copy

Setup guidance · Editorial suggestion。Hand to setup assistant to confirm inputs and permissions, then reproduce the workflow step by step

This block is the prompt. Ads are never placed here.

You are setting up an n8n workflow to automatically analyze, classify, and summarize Gmail emails. Please confirm and execute in this order:
1. Verify you have: an n8n instance, a Google account (Gmail + Sheets), an OpenAI API key, and a Telegram Bot token with chat ID.
2. Create four credentials in n8n: Gmail OAuth2, Google Sheets OAuth2, OpenAI API, Telegram API.
3. Create the Email Log and Tagging Samples sheets in Google Sheets per the instructions, and seed Tagging Samples with initial classification examples.
4. Import or rebuild the node graph from workflow.json, paying special attention: copy the AI Agent systemMessage and text fields verbatim; use memoryKey=email_tagging consistently across vector store nodes; execute manually once to populate the vector store before activation.
5. Replace [YOUR_CHAT_ID] placeholders in Telegram nodes with real IDs.
6. Activate the workflow and send a test email. Verify: the email appears in Email Log, categories are assigned correctly, and Telegram receives the audio summary.

You must execute the workflow manually once before activation to populate the in-memory vector store; replace Telegram chatId and Google Sheets documentId with your own values; OpenAI audio generation incurs additional charges.

Source

Analyze, classify, and summarize Gmail with OpenAI RAG and Google Sheets · amirhoseinzahedi · n8n.io · 2026-02-21

Comments & feedback

Tried this method? Share results, problems or improvements. Comments appear after moderation. Please avoid sensitive information.

Loading…

    Related