Automate Email Queries with Telegram & Pgvector in n8n

This automation uses Telegram and n8n to intelligently query your email database using semantic vector search and structured SQL, delivering precise answers quickly. Save hours by turning complex email searches into simple chat conversations with this guided workflow.
telegramTrigger
vectorStorePGVector
agent
+12
Workflow Identifier: 2214
NODES in Use: telegramTrigger, splitInBatches, if, chatTrigger, vectorStorePGVector, toolWorkflow, embeddingsOllama, set, code, telegram, noOp, stickyNote, memoryBufferWindow, agent, lmChatOpenAi

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

What this workflow does

This workflow builds an AI email assistant inside n8n that users chat with on Telegram.

It solves the problem of slow manual email searches by understanding natural language questions and finding exact emails quickly.

The workflow uses vector search to find related emails and runs SQL queries for exact data.

The user asks questions naturally on Telegram and gets clear answers fast.


Tools and services used

  • Telegram Bot API: Receives user messages.
  • PostgreSQL with Pgvector extension: Stores email text embeddings and supports semantic search.
  • n8n automation platform: Orchestrates the workflow and connects components.
  • Ollama API: Generates vector embeddings from email text.
  • OpenAI API or compatible LLM: Interprets user questions and builds SQL queries.
  • SQL composer workflow: Dynamically generates and runs SQL queries on email data.

Who should use this workflow

People managing many emails and needing fast answers.

Teams looking to avoid manual email searches.

Anyone wanting to ask natural language questions about email details via chat.

What is the input → processing → output flow?

Inputs

  1. User sends a question to the Telegram bot.
  2. Question text and chat context are captured by n8n.

Processing

  1. Generate a session ID to track chat context.
  2. Use embeddings from Ollama to convert question to vector.
  3. Run Pgvector semantic search in Postgres for similar emails.
  4. Pass user question to AI Agent that calls SQL composer for exact info.
  5. Manage conversation memory to keep context.
  6. Split and escape responses for Telegram markdown formatting.

Output

  1. Send formatted answer back to the user via Telegram messages.

Beginner step-by-step: How to build this in n8n

Download and import

  1. Download the workflow using the Download button on this page.
  2. Inside n8n editor, choose “Import from File” and select the downloaded workflow file.

Configure credentials

  1. Set the Telegram Bot API credentials in the Telegram Trigger and Telegram nodes.
  2. Enter PostgreSQL connection details with Pgvector enabled in the Postgres PGVector Store node.
  3. Fill in Ollama API keys in the Embeddings Ollama node.
  4. Input OpenAI or compatible LLM API info in the LangChain OpenAI Chat Model node.

Update workflow data

  1. Change allowed Telegram chat IDs to match your chat to keep it secure.
  2. Modify email database table or folder names in nodes if different.
  3. Configure system prompt text in the AI Agent node to reflect email database schema.
  4. Link the SQL composer workflow in the Tool Workflow node by pasting its workflow ID after import.

Test and activate

  1. Send a test message on Telegram to the bot to verify response.
  2. Check for correct session handling, message formatting, and email search results.
  3. Activate the workflow to run continuously in n8n for production use.

For privacy and reliability, consider self-host n8n.


Customization ideas

  • Switch Telegram nodes to Slack or WhatsApp to chat there instead.
  • Adjust “topK” in the Postgres PGVector Store node to get more or fewer search results.
  • Edit the system prompt in the AI Agent node to focus answers on certain email folders.
  • Change the Ollama embedding model for better results in specific email types.
  • Modify chunk sizes for splitting messages in the Code node to match platform limits.

Typical errors and fixes

Telegram workflow not triggered

Cause: Bot not in correct chat or chat ID in Telegram Trigger is wrong.

Fix: Check chat ID and add bot to chat with right permissions.

SQL composer returns no data

Cause: SQL workflow not imported or linked properly.

Fix: Import the SQL composer template and update the Tool Workflow node with its ID.

Broken markdown in Telegram messages

Cause: Special characters in reply not escaped.

Fix: Confirm the Escape Markdown code node runs after splitting before sending.


Pre-production checklist

  • Confirm Telegram Bot API keys are valid and bot is added to correct chat.
  • Check PostgreSQL database has Pgvector and email embeddings loaded.
  • Verify Ollama and OpenAI API keys are active and linked.
  • Test SQL composer separately to ensure it returns data.
  • Run a test question and validate Telegram replies are formatted well and complete.

Deployment notes

Turn on the workflow in n8n after confirming everything works well.

Watch workflow execution logs for errors in Telegram or database connections.

Keep fresh backups of the email data and embedding database.

Hosting the workflow on your own server or cloud VM gives better control and privacy.

Consider self-host n8n for best privacy.


Summary of benefits

✓ Save hours by searching emails fast using natural language.

✓ Get accurate answers combining semantic and structured search.

✓ Chat using Telegram with simple questions.

✓ Keep conversation history with memory nodes.

✓ Flexible and customizable for other platforms and databases.


Frequently Asked Questions

Yes, but the Postgres PGVector Store node must be replaced with a compatible vector database node, and the AI Agent prompt updated to match.
Embedding and language model API calls do consume credits. To reduce costs, limit vector search results and cache frequent queries.
Self-hosting n8n and the database keeps data private. Using managed n8n requires trusting their security. Protect API keys and restrict access.
Import the SQL composer template into n8n and run test inputs to check for expected SQL outputs and results before linking in the main workflow.

Promoted by BULDRR AI

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation Workflows in n8n

A complete beginner guide to building an AI SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free