Automated Email Archiving to Notion Knowledge Base with PostgreSQL Deduplication - n8n Workflow

Use this powerful n8n workflow to capture new IMAP emails, automatically clean and standardize the content, prevent duplicates using PostgreSQL, and save everything neatly into Notion. Get immediate Telegram notifications upon success.

Workflow Preview

Ready to automate?

Download this n8n workflow template and start using it instantly.

Who is this best for?


  • Knowledge managers or research teams needing to centralize information received via email.

  • Advanced n8n users seeking robust and scalable deduplication logic.

  • System administrators who need reliable email archiving that uses standard protocols like IMAP and PostgreSQL.

  • Anyone looking for high-quality n8n templates to handle structured data ingestion.

Overview

This sophisticated n8n workflow solves the critical issue of data duplication and inconsistency when using email in conjunction with a knowledge management system like Notion. Utilizing the IMAP n8n trigger, the flow continuously monitors a designated inbox (ideal for newsletters, alerts, or forwarded content). Data standardization is performed by a custom Code n8n node, which cleans HTML, extracts crucial metadata, and generates unique identifiers. Before committing resources to Notion, the workflow employs PostgreSQL to quickly check if the item has been processed before, ensuring efficiency. This complete n8n automation provides a reliable, indexed knowledge base system.

How it Works

This n8n workflow operates on a scheduled polling basis using the IMAP n8n trigger to initiate the process.


  1. Email Ingestion (IMAP Trigger): The process begins with the Email Trigger (IMAP) n8n node, configured to fetch only 'UNSEEN' emails from the specified mailbox connection.

  2. Data Normalization and ID Generation (Code Node): The custom Code n8n node handles raw email data. It cleans the email body (stripping HTML to create plain text content), extracts the sender address, subject, and date, and formats them. Crucially, it ensures every item has a unique messageId for reliable deduplication, using a fallback hash mechanism if the original email headers are insufficient.

  3. Deduplication Check (Postgres Node): The flow then utilizes the PostgreSQL n8n node to execute a query against the predefined emailkbindex table, checking for the existence of the newly calculated messageId.

  4. Conditional Routing (If Node): The If n8n node evaluates the database response. The n8n workflow only proceeds if the exists flag returned from Postgres is false (meaning it is a truly new email).

  5. Notion Archive: For unique items, the Notion n8n node creates a new page in the configured database, mapping the cleaned fields (Title, Snippet, Date, From, Source URL, Slug) from the Code n8n node output.

  6. Indexing and Alerting (Telegram Node): Finally, a Telegram n8n node sends a real-time notification confirming the successful archiving. *(Note: While not directly connected in the main line, best practice, as noted in the workflow comments, is to include a second Postgres n8n node here to insert the successful messageId and Notion page ID into the emailkbindex table to finalize the deduplication record.)

Installation Guide

To deploy this advanced n8n workflow, follow these steps:


  1. Import: Copy the provided JSON into your n8n instance using the 'New' -> 'Import from JSON' function.

  2. IMAP Credentials: Configure the Email Trigger (IMAP) n8n trigger node with credentials for the mailbox you wish to monitor (e.g., Gmail IMAP server details).

  3. Postgres Setup: Set up a PostgreSQL connection credential. You must create the required index table manually before running the workflow:

CREATE TABLE IF NOT EXISTS emailkbindex (
messageid TEXT PRIMARY KEY,
slug TEXT,
created
at TIMESTAMPTZ NOT NULL DEFAULT now(),
notionpageid TEXT
);

  1. Notion Setup: Connect your Notion credential. Select the target database in the 'Create a database page' n8n node and ensure the n8n integration has access to this database.

  2. Telegram Setup: Configure the Telegram n8n node with your Chat ID and API credentials for notifications.

  3. Activate: Set the n8n workflow to 'Active' to start polling for new emails.

Node Details

Email Trigger (IMAP):
Function: Serves as the continuous n8n trigger, periodically fetching new email messages that meet the UNSEEN criteria.
Key Configuration: Operation: Read Emails. Options: customEmailConfig: ["UNSEEN"].
Code:
Function: A powerful custom n8n node that standardizes raw email inputs. It ensures robust multi-format parsing (HTML to text, various date/subject fields), generates URL-safe slugs, limits text lengths for Notion summaries, and creates a highly reliable messageId for global deduplication.
Key Configuration: Contains extensive JavaScript logic for data hygiene and hash generation.
Execute a SQL query (Postgres):
Function: Executes the core deduplication logic by querying the emailkbindex table to check if the extracted messageId has been indexed previously.
Key Configuration: Query: SELECT EXISTS(...) WHERE message_id = '{{ $json.messageId }}'.
If:
Function: Controls the subsequent flow execution. It acts as a gate, allowing only unique, unprocessed emails to proceed to the archiving stage.
Key Configuration: Condition checks the result of the prior n8n node: Left ={{ $json.exists }} equals false.
Create a database page (Notion):
Function: Archives the cleaned and verified email content as a new structured page within the Notion knowledge database.
Key Configuration: Maps fields like title, snippet, sentAt, fromAddress, and sourceUrl to specific Notion database properties.
Send a text message (Telegram):
* Function: Provides instant confirmation via Telegram whenever this n8n workflow successfully processes and archives a unique email.

Related n8n Workflows

Free

Nodes: 7 Nodes
Updated: December 26 2025
View all
Created by
Ariyanto Catur Pamungkas
Ariyanto Catur Pamungkas

Featured*