Back to Integrations
integrationGmail node
integrationPostgres node

Gmail and Postgres integration

Save yourself the work of writing custom integrations for Gmail and Postgres and use n8n instead. Build adaptable and scalable Communication, HITL, Development, and Data & Storage workflows that work with your technology stack. All within a building experience you will love.

How to connect Gmail and Postgres

  • Step 1: Create a new workflow
  • Step 2: Add and configure nodes
  • Step 3: Connect
  • Step 4: Customize and extend your integration
  • Step 5: Test and activate your workflow

Step 1: Create a new workflow and add the first step

In n8n, click the "Add workflow" button in the Workflows tab to create a new workflow. Add the starting point – a trigger on when your workflow should run: an app event, a schedule, a webhook call, another workflow, an AI chat, or a manual trigger. Sometimes, the HTTP Request node might already serve as your starting point.

Gmail and Postgres integration: Create a new workflow and add the first step

Step 2: Add and configure Gmail and Postgres nodes

You can find Gmail and Postgres in the nodes panel. Drag them onto your workflow canvas, selecting their actions. Click each node, choose a credential, and authenticate to grant n8n access. Configure Gmail and Postgres nodes one by one: input data on the left, parameters in the middle, and output data on the right.

Gmail and Postgres integration: Add and configure Gmail and Postgres nodes

Step 3: Connect Gmail and Postgres

A connection establishes a link between Gmail and Postgres (or vice versa) to route data through the workflow. Data flows from the output of one node to the input of another. You can have single or multiple connections for each node.

Gmail and Postgres integration: Connect Gmail and Postgres

Step 4: Customize and extend your Gmail and Postgres integration

Use n8n's core nodes such as If, Split Out, Merge, and others to transform and manipulate data. Write custom JavaScript or Python in the Code node and run it as a step in your workflow. Connect Gmail and Postgres with any of n8n’s 1000+ integrations, and incorporate advanced AI logic into your workflows.

Gmail and Postgres integration: Customize and extend your Gmail and Postgres integration

Step 5: Test and activate your Gmail and Postgres workflow

Save and run the workflow to see if everything works as expected. Based on your configuration, data should flow from Gmail to Postgres or vice versa. Easily debug your workflow: you can check past executions to isolate and fix the mistake. Once you've tested everything, make sure to save your workflow and activate it.

Gmail and Postgres integration: Test and activate your Gmail and Postgres workflow

Suspicious login detection

This n8n workflow is designed for security monitoring and incident response when suspicious login events are detected. It can be initiated either manually from within the n8n UI for testing or automatically triggered by a webhook when a new login event occurs.

The workflow first extracts relevant data from the incoming webhook payload, including the IP address, user agent, timestamp, URL, and user ID. It then splits into three parallel processing paths.

In the first path, it queries GreyNoise's Community API to retrieve information about the investigated IP address. Depending on the classification and trust level received from GreyNoise, the alert is given a High, Medium, or Low priority. This priority is assigned based on the best practices documentation from GreyNoise on how to apply their data to analysis. Once a priority is assigned, a message is sent to a Slack channel to notify users about the alert.

The second path involves fetching geolocation data about the IP address using IP-API's Geolocation API and merging it with data from the UserParser node. This data is then combined with the data obtained from GreyNoise.

In the third path, the UserParser node queries the Userparser IP address and user agent lookup API to obtain information about the user's IP and user agent. This data is merged with the IP-API data and GreyNoise data.

The workflow then checks if the IP address is considered an unknown threat by examining both the noise and riot fields from GreyNoise. If it is considered an unknown threat, the workflow proceeds to retrieve the last 10 login records for the same user from a Postgres database.

If there are any discrepancies in the login information, indicating a new location or device/browser, the user is informed via email.

Potential issues when setting up this workflow include ensuring that credentials are correctly entered for GreyNoise and UserParser nodes, and addressing any discrepancies in the data sources that could lead to false positives or negatives in threat detection. Additionally, the usage of hardcoded API keys should be replaced with credentials for security and flexibility. Thorough testing and validation with sample data are crucial to ensure the workflow performs as expected and aligns with security incident response procedures.

Nodes used in this workflow

Popular Gmail and Postgres workflows

+5

Automate B2B SaaS Renewal Risk Management with CRM, Support & Usage Data

Description This workflow is designed for B2B/SaaS teams who want to secure renewals before it’s too late. It runs every day, identifies all accounts whose licenses are up for renewal in J–30, enriches them with CRM, product usage and support data, computes an internal churn risk level, and then triggers the appropriate playbook: HIGH risk** → full escalation (tasks, alerts, emails) MEDIUM risk** → proactive follow-up by Customer Success LOW risk** → light renewal touchpoint / monitoring Everything is logged into a database table so that you can build dashboards, run analysis, or plug additional automations on top. How it works Daily detection (J–30 renewals) A scheduled trigger runs every morning and queries your database (Postgres / Supabase) to fetch all active subscriptions expiring in 30 days. Each row includes the account identifier, name, renewal date and basic commercial data. Data enrichment across tools For each account, the workflow calls several business systems to collect context: HubSpot → engagement history Salesforce → account profile and segment Pipedrive → deal activities and associated products Analytics API → product feature usage and activity trends Zendesk → recent support tickets and potential friction signals All of this is merged into a single, unified item. Churn scoring & routing An internal scoring step evaluates the risk for each account based on multiple signals (engagement, usage, support, timing). The workflow then categorizes each account into one of three risk levels: HIGH – strong churn signals → needs immediate attention MEDIUM – some warning signs → needs proactive follow-up LOW – looks healthy → light renewal reminder A Switch node routes each account to the relevant playbook. Automated playbooks 🔴 HIGH risk Create a Trello card on a dedicated “High-Risk Renewals” board/list Create a Jira ticket for the CS / AM team Send a Slack alert in a designated channel Send a detailed email to the CSM and/or account manager 🟠 MEDIUM risk Create a Trello card in a “Renewals – Follow-up” list Send a contextual email to the CSM to recommend a proactive check-in 🟢 LOW risk Send a soft renewal email / internal note to keep the account on the radar Logging & daily reporting For every processed account, the workflow prepares a structured log record (account, renewal date, risk level, basic context). A Postgres node is used to insert the data into a churn_logs table. At the end of each run, all processed accounts are aggregated and a daily summary email is sent (for example to the Customer Success leadership team), listing the renewals and their risk levels. Requirements Database A table named churn_logs (or equivalent) to store workflow decisions and history. Example fields: account_id, account_name, end_date, riskScore, riskLevel, playbook, trello_link, jira_link, timestamp. External APIs HubSpot (engagement data) Salesforce (account profile) Pipedrive (deals & products) Zendesk (support tickets) Optional: product analytics API for usage metrics Communication & task tools Gmail (emails to CSM / AM / summary recipients) Slack (alert channel for high-risk cases) Trello (task creation for CS follow-up) Jira (escalation tickets for high-risk renewals) Configuration variables Thresholds are configured in the Init config & thresholds node: days_before_renewal churn_threshold_high churn_threshold_medium These parameters let you adapt the detection window and risk sensitivity to your own business rules. Typical use cases Customer Success teams who want a daily churn watchlist without exporting spreadsheets. RevOps teams looking to standardize renewal playbooks across tools. SaaS companies who need to prioritize renewals based on real risk signals rather than gut feeling. Product-led organizations that want to combine usage data + CRM + support into one automated process. Tutorial video Watch the Youtube Tutorial video About me : I’m Yassin a Project & Product Manager Scaling tech products with data-driven project management. 📬 Feel free to connect with me on Linkedin
+6

Interactive Knowledge Base Chat with Supabase RAG using AI 📚💬

Google Drive File Ingestion to Supabase for Knowledge Base 📂💾 Overview 🌟 This n8n workflow automates the process of ingesting files from Google Drive into a Supabase database, preparing them for a knowledge base system. It supports text-based files (PDF, DOCX, TXT, etc.) and tabular data (XLSX, CSV, Google Sheets), extracting content, generating embeddings, and storing data in structured tables. This is a foundational workflow for building a company knowledge base that can be queried via a chat interface (e.g., using a RAG workflow). 🚀 Problem Solved 🎯 Manually managing a knowledge base with files from Google Drive is time-consuming and error-prone. This workflow solves that by: Automatically ingesting files from Google Drive as they are created or updated. Extracting content** from various file types (text and tabular). Generating embeddings for text-based files to enable vector search. Storing data in Supabase for efficient retrieval. Handling duplicates and errors to ensure data consistency. Target Audience: Knowledge Managers**: Build a centralized knowledge base from company files. Data Teams**: Automate the ingestion of spreadsheets and documents. Developers**: Integrate with other workflows (e.g., RAG for querying the knowledge base). Workflow Description 🔍 This workflow listens for new or updated files in Google Drive, processes them based on their type, and stores the extracted data in Supabase tables for later retrieval. Here’s how it works: File Detection: Triggers when a file is created or updated in Google Drive. File Processing: Loops through each file, extracts metadata, and validates the file type. Duplicate Check: Ensures the file hasn’t been processed before. Content Extraction: Text-based Files: Downloads the file, extracts text, splits it into chunks, generates embeddings, and stores the chunks in Supabase. Tabular Files: Extracts data from spreadsheets and stores it as rows in Supabase. Metadata Storage: Stores file metadata and basic info in Supabase tables. Error Handling: Logs errors for unsupported formats or duplicates. Nodes Breakdown 🛠️ Detect New File 🔔 Type**: Google Drive Trigger Purpose**: Triggers the workflow when a new file is created in Google Drive. Configuration**: Credential: Google Drive OAuth2 Event: File Created Customization**: Specify a folder to monitor specific directories. Detect Updated File 🔔 Type**: Google Drive Trigger Purpose**: Triggers the workflow when a file is updated in Google Drive. Configuration**: Credential: Google Drive OAuth2 Event: File Updated Customization**: Currently disconnected; reconnect if updates need to be processed. Process Each File 🔄 Type**: Loop Over Items Purpose**: Processes each file individually from the Google Drive trigger. Configuration**: Input: {{ $json.files }} Customization**: Adjust the batch size if processing multiple files at once. Extract File Metadata 🆔 Type**: Set Purpose**: Extracts metadata like file_id, file_name, mime_type, and web_view_link. Configuration**: Fields: file_id: {{ $json.id }} file_name: {{ $json.name }} mime_type: {{ $json.mimeType }} web_view_link: {{ $json.webViewLink }} Customization**: Add more metadata fields if needed (e.g., size, createdTime). Check File Type ✅ Type**: IF Purpose**: Validates the file type by checking the MIME type. Configuration**: Condition: mime_type contains supported types (e.g., application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet). Customization**: Add more supported MIME types as needed. Find Duplicates 🔍 Type**: Supabase Purpose**: Checks if the file has already been processed by querying knowledge_base. Configuration**: Operation: Select Table: knowledge_base Filter: file_id = {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add additional duplicate checks (e.g., by file name). Handle Duplicates 🔄 Type**: IF Purpose**: Routes the workflow based on whether a duplicate is found. Configuration**: Condition: {{ $node['Find Duplicates'].json.length > 0 }} Customization**: Add notifications for duplicates if desired. Remove Old Text Data 🗑️ Type**: Supabase Purpose**: Deletes old text data from documents if the file is a duplicate. Configuration**: Operation: Delete Table: documents Filter: metadata->>'file_id' = {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add logging before deletion. Remove Old Data 🗑️ Type**: Supabase Purpose**: Deletes old tabular data from document_rows if the file is a duplicate. Configuration**: Operation: Delete Table: document_rows Filter: dataset_id = {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add logging before deletion. Route by File Type 🔀 Type**: Switch Purpose**: Routes the workflow based on the file’s MIME type (text-based or tabular). Configuration**: Rules: Based on mime_type (e.g., application/pdf for text, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for tabular). Customization**: Add more routes for additional file types. Download File Content 📥 Type**: Google Drive Purpose**: Downloads the file content for text-based files. Configuration**: Credential: Google Drive OAuth2 File ID: {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add error handling for download failures. Extract PDF Text 📜 Type**: Extract from File (PDF) Purpose**: Extracts text from PDF files. Configuration**: File Content: {{ $node['Download File Content'].binary.data }} Customization**: Adjust extraction settings for better accuracy. Extract DOCX Text 📜 Type**: Extract from File (DOCX) Purpose**: Extracts text from DOCX files. Configuration**: File Content: {{ $node['Download File Content'].binary.data }} Customization**: Add support for other text formats (e.g., TXT, RTF). Extract XLSX Data 📊 Type**: Extract from File (XLSX) Purpose**: Extracts tabular data from XLSX files. Configuration**: File ID: {{ $node['Extract File Metadata'].json.file_id }} Customization**: Add support for CSV or Google Sheets. Split Text into Chunks ✂️ Type**: Text Splitter Purpose**: Splits extracted text into manageable chunks for embedding. Configuration**: Chunk Size: 1000 Chunk Overlap: 200 Customization**: Adjust chunk size and overlap based on document length. Generate Text Embeddings 🌐 Type**: OpenAI Purpose**: Generates embeddings for text chunks using OpenAI. Configuration**: Credential: OpenAI API key Operation: Embedding Model: text-embedding-ada-002 Customization**: Switch to a different embedding model if needed. Store Text in Supabase 💾 Type**: Supabase Vector Store Purpose**: Stores text chunks and embeddings in the documents table. Configuration**: Credential: Supabase credentials Operation: Insert Documents Table Name: documents Customization**: Add metadata fields to store additional context. Store Tabular Data 💾 Type**: Supabase Purpose**: Stores tabular data in the document_rows table. Configuration**: Operation: Insert Table: document_rows Columns: dataset_id, row_data Customization**: Add validation for tabular data structure. Store File Metadata 📋 Type**: Supabase Purpose**: Stores file metadata in the document_metadata table. Configuration**: Operation: Insert Table: document_metadata Columns: file_id, file_name, file_type, file_url Customization**: Add more metadata fields as needed. Record in Knowledge Base 📚 Type**: Supabase Purpose**: Stores basic file info in the knowledge_base table. Configuration**: Operation: Insert Table: knowledge_base Columns: file_id, file_name, file_type, file_url, upload_date Customization**: Add indexes for faster lookups. Log File Errors ⚠️ Type**: Supabase Purpose**: Logs errors for unsupported file types. Configuration**: Operation: Insert Table: error_log Columns: error_type, error_message Customization**: Add notifications for errors. Log Duplicate Errors ⚠️ Type**: Supabase Purpose**: Logs errors for duplicate files. Configuration**: Operation: Insert Table: error_log Columns: error_type, error_message Customization**: Add notifications for duplicates. Interactive Knowledge Base Chat with Supabase RAG using GPT-4o-mini 📚💬 Introduction 🌟 This n8n workflow creates an interactive chat interface that allows users to query a company knowledge base using Retrieval-Augmented Generation (RAG). It retrieves relevant information from text documents and tabular data stored in Supabase, then generates natural language responses using OpenAI’s GPT-4o-mini model. Designed for teams managing internal knowledge, this workflow enables users to ask questions like “What’s the remote work policy?” or “Show me the latest budget data” and receive accurate, context-aware responses in a conversational format. 🚀 Problem Statement 🎯 Managing a company knowledge base can be a daunting task—employees often struggle to find specific information buried in documents or spreadsheets, leading to wasted time and inefficiencies. Traditional search methods may not understand natural language queries or provide contextually relevant results. This workflow solves these issues by: Offering a chat-based interface for natural language queries, making it easy for users to ask questions in their own words. Leveraging RAG to retrieve relevant text and tabular data from Supabase, ensuring responses are accurate and context-aware. Supporting diverse file types, including text-based files (e.g., PDFs, DOCX) and tabular data (e.g., XLSX, CSV), for comprehensive knowledge access. Maintaining conversation history to provide context during interactions, improving the user experience. Target Audience 👥 This workflow is ideal for: HR Teams**: Quickly access company policies, employee handbooks, or benefits documents. Finance Teams**: Retrieve budget data, expense reports, or financial summaries from spreadsheets. Knowledge Managers**: Build a centralized assistant for internal documentation, streamlining information access. Developers**: Extend the workflow with additional tools or integrations for custom use cases. Workflow Description 🔍 This workflow consists of a chat interface powered by n8n’s Chat Trigger node, an AI Agent node for RAG, and several tools to retrieve data from Supabase. Here’s how it works step-by-step: User Initiates a Chat: The user interacts with a chat interface, sending queries like “Summarize our remote work policy” or “Show budget data for Q1 2025.” Query Processing with RAG: The AI Agent processes the query using RAG, retrieving relevant data from Supabase tables and generating a response with OpenAI’s GPT-4o-mini model. Data Retrieval and Response Generation: The workflow uses multiple tools to fetch data: Retrieves text chunks from the documents table using vector search. Fetches tabular data from the document_rows table based on file IDs. Extracts full document text or lists available files as needed. Generates a natural language response combining the retrieved data. Conversation History Management: Stores the conversation history in Supabase to maintain context for follow-up questions. Response Delivery: Formats and sends the response back to the chat interface for the user to view. Nodes Breakdown 🛠️ Start Chat Interface 💬 Type**: Chat Trigger Purpose**: Provides the interactive chat interface for users to input queries and receive responses. Configuration**: Chat Title: Company Knowledge Base Assistant Chat Subtitle: Ask me anything about company documents! Welcome Message: Hello! I’m your Company Knowledge Base Assistant. How can I help you today? Suggestions: What is the company policy on remote work?, Show me the latest budget data., List all policy documents. Output Chat Session ID: true Output User Message: true Customization**: Update the title and welcome message to align with your company branding (e.g., HR Knowledge Assistant). Add more suggestions relevant to your use case (e.g., What are the company benefits?). Process Query with RAG 🧠 Type**: AI Agent Purpose**: Orchestrates the RAG process by retrieving relevant data using tools and generating responses with OpenAI’s GPT-4o-mini. Configuration**: Credential: OpenAI API key Model: gpt-4o-mini System Prompt: You are a helpful assistant for a company knowledge base. Use the provided tools to retrieve relevant information from documents and tabular data. If the query involves tabular data, format it clearly in your response. If no relevant data is found, respond with "I couldn’t find any relevant information. Can you provide more details?" Input Field: {{ $node['Start Chat Interface'].json.message }} Customization**: Switch to a different model (e.g., gpt-3.5-turbo) to adjust cost or performance. Modify the system prompt to change the tone (e.g., more formal for HR use cases). Retrieve Text Chunks 📄 Type**: Supabase Vector Store (Tool) Purpose**: Retrieves relevant text chunks from the documents table using vector search. Configuration**: Credential: Supabase credentials Operation Mode: Retrieve Documents (As Tool for AI Agent) Table Name: documents Embedding Field: embedding Content Field: content_text Metadata Field: metadata Embedding Model: OpenAI text-embedding-ada-002 Top K: 10 Customization**: Adjust Top K to retrieve more or fewer results (e.g., 5 for faster responses). Ensure the match_documents function (see prerequisites) is defined in Supabase. Fetch Tabular Data 📊 Type**: Supabase (Tool, Execute Query) Purpose**: Retrieves tabular data from the document_rows table based on a file ID. Configuration**: Credential: Supabase credentials Operation: Execute Query Query: SELECT row_data FROM document_rows WHERE dataset_id = $1 LIMIT 10 Tool Description: Run a SQL query - use this to query from the document_rows table once you know the file ID you are querying. dataset_id is the file_id and you are always using the row_data for filtering, which is a jsonb field that has all the keys from the file schema given in the document_metadata table. Customization**: Modify the query to filter specific columns or add conditions (e.g., WHERE dataset_id = $1 AND row_data->>'year' = '2025'). Increase the LIMIT for larger datasets. Extract Full Document Text 📜 Type**: Supabase (Tool, Execute Query) Purpose**: Fetches the full text of a document by concatenating all text chunks for a given file_id. Configuration**: Credential: Supabase credentials Operation: Execute Query Query: SELECT string_agg(content_text, ' ') as document_text FROM documents WHERE metadata->>'file_id' = $1 GROUP BY metadata->>'file_id' Tool Description: Given file id fetch the text from the documents Customization**: Add filters to the query if needed (e.g., limit to specific metadata fields). List Available Files 📋 Type**: Supabase (Tool, Select) Purpose**: Lists all files in the knowledge base from the document_metadata table. Configuration**: Credential: Supabase credentials Operation: Select Schema: public Table: document_metadata Tool Description: Use this tool to fetch all documents including the table schema if the file is csv, excel or xlsx Customization**: Add filters to list specific file types (e.g., WHERE file_type = 'application/pdf'). Modify the columns selected to include additional metadata (e.g., file_size). Manage Chat History 💾 Type**: Postgres Chat Memory (Tool) Purpose**: Stores and retrieves conversation history to maintain context. Configuration**: Credential: Supabase credentials (Postgres-compatible) Table Name: n8n_chat_history Session ID Field: session_id Session ID Value: {{ $node['Start Chat Interface'].json.sessionId }} Message Field: message Sender Field: sender Timestamp Field: timestamp Context Window Length: 5 Customization**: Increase the context window length for longer conversations (e.g., 10 messages). Add indexes on session_id and timestamp in Supabase for better performance. Format and Send Response 📤 Type**: Set Purpose**: Formats the AI Agent’s response and sends it back to the chat interface. Configuration**: Fields: response: {{ $node['Process Query with RAG'].json.output }} Customization**: Add additional formatting to the response if needed (e.g., prepend with a timestamp or apply markdown formatting). Setup Instructions 🛠️ Prerequisites 📋 n8n Setup: Ensure you’re using n8n version 1.0 or higher. Enable the AI features in n8n settings. Supabase: Create a Supabase project and set up the following tables: documents: id (uuid), content_text (text), embedding (vector(1536)), metadata (jsonb) document_rows: id (uuid), dataset_id (varchar), row_data (jsonb) document_metadata: file_id (varchar), file_name (varchar), file_type (varchar), file_url (text) knowledge_base: id (serial), file_id (varchar), file_name (varchar), file_type (varchar), file_url (text), upload_date (timestamp) n8n_chat_history: id (serial), session_id (varchar), message (text), sender (varchar), timestamp (timestamp) Add the match_documents function to Supabase to enable vector search: CREATE OR REPLACE FUNCTION match_documents ( query_embedding vector(1536), match_count int DEFAULT 5, filter jsonb DEFAULT '{}' ) RETURNS TABLE ( id uuid, content_text text, metadata jsonb, similarity float ) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY SELECT documents.id, documents.content_text, documents.metadata, 1 - (documents.embedding <=> query_embedding) as similarity FROM documents WHERE documents.metadata @> filter ORDER BY similarity DESC LIMIT match_count; END; $$;

The title is very good, clearly conveying the template's purpose while mentioning key technologies

How it works Collects articles from your preferred RSS feeds. Rates and tags each article using an AI model (e.g., QWEN 14B-s4), filtering for relevance and quality. Summarizes high-rated articles with a language model (e.g., Gemma3 4B) for quick, digestible reading. Checks for duplicates to avoid sending the same article twice. Formats and sends the top articles as an HTML newsletter via Gmail, using OAuth2 authentication. Stores records in a Postgres database, tracking which articles have been sent and their ratings. Requirements Postgres Account AI Models (if you work localy use Ollama) In the cloud you have to change Ollama node to your prefered Model Node RSS Feed of your desire Google Auth2, if you want to use Gmail Recommendations Use n8n local version for this workflow Here are some more informations: https://github.com/falks-ai-workbench/n8n_newsletter
+2

Gmail to Vector Embeddings with PGVector and Ollama

Gmail to Vector Embeddings with PGVector and Ollama Who is this for? Everyone! Did you dream of asking an AI "what hotel did I stay in for holidays last summer?" or "what were my marks last semester like?". Dream no more, as vector similarity searches and this workflow are the foundations to make it possible (as long as the information appears in your e-mails 😅). 100% local This workflow is designed to use locally-hosted open source. Ollama as LLM provider, nomic-embed-text as the embeddings model, and pgvector as the vector database engine, on top of Postgres. But.. how?! Firstly, specify the date you created your Gmail account on, then manually run the workflow in order to bulk read all your e-mail in monthly batches. Your database is now populated! Now it's the task for other workflows to query the vector database. Activate the workflow so that new e-mail is continuously added by the Gmail Trigger upon receiving it. Structured AND Vectorized This workflow stores your e-mail activity in two ways: In a structured table In a vector embeddings table And the information in both of them can be correlated by Gmail's messages id, which is stored in the vectors table as metadata property emails_metadata.id. That way consumers can benefit from both worlds! ✨ Vector similarity searches enable semantic searches, while structured queries can retrieve more factual data like the message id, its date or who it came from. Other useful templates My template Chat with Your Email History using Telegram, Mistral and Pgvector for RAG is a ready-made solution to consume this workflow. You may also pair this workflow with my other template to Email Assistant: Convert Natural Language to SQL Queries with Phi4-mini and PostgreSQL and you'll enable RAG workflows that use both structured and vectorized databases. Customizations I suppose the e-mail provider could be changed, but then you'd have to identify an alternative id field. Message-ID would be a more standard option. There are a few opinionated choices as to what metadata to store, but those shouldn't need adjustments.
+12

AI-Powered MIS Agent

The AI-powered MIS Agent is an intelligent, automated system built using n8n that streamlines email-based data collection and document organization for businesses. It classifies incoming emails, extracts and processes attachments or Drive links, and routes them to the correct destination folders in Google Drive. Additionally, it provides advanced file operations like cleaning, merging, joining, and transforming data. Advantages 📥 Automated Email and File Management Detects and processes emails containing attachments or Drive links, ensuring seamless classification and routing of business-critical files. 🧠 AI-Based Classification Uses LLMs (like GPT-4o Mini) to classify emails into categories such as Daily Sales, Customer Info, and Address based on their content. 📂 Smart File Routing and Upload Recognizes whether a file is a direct attachment or a Google Drive link, extracts the file ID if necessary, and uploads it to predefined folders. 📊 Powerful Data Operations Supports operations like append, join, group by, aggregation, and standardization of data directly from spreadsheets using Python and Pandas within the workflow. 🔁 Scheduled and Triggered Automation Supports scheduled runs and real-time email triggers, making it highly reliable and timely. 🔧 Fully Modular and Scalable Easily expandable with more logic, new folders, or different workflows. Clean architecture and annotations make maintenance simple. How It Works Email Trigger The system uses a Gmail trigger to monitor incoming emails with specific labels or attachments. Classification An LLM-based text classifier identifies the purpose of the email (e.g., sales data, address list, customer details). Conditional Logic Regex-based conditions check if the email contains Google Drive links or attachments. File Handling If it's a Drive link, it extracts the file ID and copies it to the correct folder. If it's an attachment, it uploads directly. Scheduled Data Management Periodically moves or logs files from predefined folders using a schedule trigger. Data Cleaning and Processing Performs data cleaning and transformation tasks like replacing missing values, standardizing formats, and joining datasets based on criteria provided by the user. Final Output Cleaned and processed files are saved in designated folders with their public links shared back through the system. Set Up Steps Configure Nodes: Gmail Trigger: Detects relevant incoming emails. Text Classifier: Uses OpenAI model to categorize email content. Regex Conditions: Determine whether a link or attachment is present. Google Drive Operations: Upload or copy files to categorized folders. Python Nodes: Handle data manipulation using Pandas. Google Sheets Nodes: Extract, clean, and write structured data. LLM-based Chat Models: Extract and apply cleaning configurations. Connect Nodes: Seamlessly connect Gmail inputs, classification, file processing, and data logic. Output links or processed files are uploaded back to Drive and ready to share. Credentials: Ensure OAuth credentials for Gmail, Google Drive, and OpenAI are correctly set. Ideal For Sales & CRM teams managing large volumes of email-based reports. Data teams needing structured pipelines from unstructured email inputs. Businesses looking to automate classification, storage, and transformation of routine data. Testing and Additional customization If you want to test this bot capability before purchasing the workflow. ask me on my mail [email protected] I will share the chat url and the links of associated google drives to see the result once you are satisfied then we are good to go. I have just kept $1 for testing purposes because of paid open ai . -If there is any customization needed like charts and other request like adding databases feel free to let me know i can do it accordingly. This is the first version i will come with more advancements based on the request and responses. Use it and let me know on [email protected]
+10

Generate product-aware B2B leads and outreach emails with Gemini, Pinecone and Gmail

How can you find your target market if you don't know what your product is. This simple philosophy changes the way we think about automated sales agents. Context changes everything. In this 4-part workflow, we start by creating a knowledge base that will act as context across the workflow. This context will guide and provide our AI Agents across the workflow to locate better leads and perform market research based on what the product actually offers. Use Case: Lead generation for Product-based Sales Tech Required Neon DB**: For storing Research and Lead Data. You can use Google sheets but it has a rate limiting problem. Google Serper**: As a web search tool for our AI. Google Drive**: For storing our knowledge base documents. Pinecone**: Vector DB for converting our knowledge base into context for AI. Hunter.io**: For finding emails for outreach. Email Client**: An email client, maybe gmail or anything that can send an email on your behalf. Gemini**: Our trusty AI LLM. Good to know All of the tools that I use in this workflow are either free or have an extremely generous free-tier. How it works We start by converting our knowledge base into context for AI. Take in the documents from Google drive and convert it into embeddings and store them in a vector store like Pinecone. This needs to be only run once, or whenever you have a new document in your knowledge base. Then we pass this context to an AI agent and tell it to generate search queries for locating companies that actually need my services. Then for each company that we've located, we determine the company staff that we need to reach out to for selling our product. This will be done by a combination of Google Serper and Hunter.io Once we have the list of employees and their emails, we start creating personalized emails based on the data we've collected for each of the employee and send them outreach emails.

Build your own Gmail and Postgres integration

Create custom Gmail and Postgres workflows by choosing triggers and actions. Nodes come with global operations and settings, as well as app-specific parameters that can be configured. You can also use the HTTP Request node to query data from any app or service with a REST API.

Gmail supported actions

Add Label
Delete
Get
Get Many
Mark as Read
Mark as Unread
Remove Label
Reply
Send
Send and Wait for Response
Create
Delete
Get
Get Many
Create
Delete
Get
Get Many
Add Label
Delete
Get
Get Many
Remove Label
Reply
Trash
Untrash

Postgres supported actions

Delete
Delete an entire table or rows in a table
Execute Query
Execute an SQL query
Insert
Insert rows in a table
Insert or Update
Insert or update rows in a table
Select
Select rows from a table
Update
Update rows in a table

FAQs

  • Can Gmail connect with Postgres?

  • Can I use Gmail’s API with n8n?

  • Can I use Postgres’s API with n8n?

  • Is n8n secure for integrating Gmail and Postgres?

  • How to get started with Gmail and Postgres integration in n8n.io?

Need help setting up your Gmail and Postgres integration?

Discover our latest community's recommendations and join the discussions about Gmail and Postgres integration.
Mikhail Savenkov
jake chard
Honza Pav
Jan Koch
Vyacheslav Karbovnichy

Looking to integrate Gmail and Postgres in your company?

Over 3000 companies switch to n8n every single week

Why use n8n to integrate Gmail with Postgres

Build complex workflows, really fast

Build complex workflows, really fast

Handle branching, merging and iteration easily.
Pause your workflow to wait for external events.

Code when you need it, UI when you don't

Simple debugging

Your data is displayed alongside your settings, making edge cases easy to track down.

Use templates to get started fast

Use 1000+ workflow templates available from our core team and our community.

Reuse your work

Copy and paste, easily import and export workflows.

Implement complex processes faster with n8n

red iconyellow iconred iconyellow icon