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
Automate email queries with Telegram and n8n

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

Learn how to Build this Workflow with AI:

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.


Automate email queries with Telegram and n8n

Visit through Desktop to Interact with the Workflow.

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 Twist Channel Creation and Messaging with n8n

This workflow automates creating and updating a channel in Twist and sending a personalized message to specific users. It eliminates manual setup errors and saves time managing Twist communications.

Automate Ideogram Image Generation with Google Sheets & Gmail

This workflow automates graphic design image generation via Ideogram AI, storing image data in Google Sheets and Google Drive, with email alerts via Gmail. It saves designers hours by automating image creation, remixing, review, and record-keeping.

Automate IT Support with Slack and OpenAI in n8n

Streamline IT support by automating Slack message handling using n8n and OpenAI. This workflow handles Slack DMs, filters bots, queries a Confluence knowledge base, and delivers AI-generated responses, improving support efficiency and response time.

Automate Crypto Analysis with CoinMarketCap & n8n AI Agent

Discover how this unique n8n workflow leverages CoinMarketCap’s multi-agent AI to deliver precise, real-time cryptocurrency insights directly via Telegram. Manage crypto data analysis efficiently with automated multi-source API integration.

Automate Gumroad to Beehiiv Subscriber Sync with n8n

Learn how to automatically add new Gumroad sales customers as Beehiiv newsletter subscribers using n8n automation. This workflow saves time by syncing sales data to Google Sheets CRM and notifying your Telegram channel instantly.

Generate On-Brand Blog Articles Using n8n and OpenAI

This workflow automates the creation of on-brand blog articles by analyzing existing company content using n8n and OpenAI. It extracts article structures and brand voice to produce consistent draft articles, saving significant content creation time.
1:1 Free Strategy Session
Your competitors are already automating. Are you still paying for it manually?

Do you want to adopt AI Automation?

Every hour your team does repetitive work, you're burning real money.
While you wait, faster businesses are cutting costs and moving quicker.
AI and automations aren't the future anymore — they're the present.

Book a live 1-on-1 session where we show you exactly which of your daily tasks can be automated — and what it’s costing you not to.