AI Lead Processor: ERPNext to Outlook via OpenAI

This workflow automates the processing of new leads generated in ERPNext. When a lead is created, it is analyzed by an AI agent (OpenAI) to categorize the inquiry, find the appropriate contact person from a Google Sheets directory, and send a professional email notification via Outlook. It includes logic to reject invalid leads and format the email body as HTML using a code node.

Nodes in the Workflow

  • Webhook (main trigger) — Receives a POST request from ERPNext when a new lead is created. No authentication is required for the webhook itself (the ERPNext system sends the data). The webhook path is /new-lead-generated-in-erpnext.
  • Get Lead Data from ERPNext — (Type: ERPNext node) Uses the webhook data to fetch full lead details from ERPNext. Authentication: ERPNext API Key (predefined credential type).
  • Source Website and Status Open — (Type: n8n filter) Ensures the lead has a source and is in “Open” status. Uses a simple condition node (IF).
  • Inquiry is Valid? — (Type: IF node) Checks if the lead notes are related to products/services using the AI output. It compares the AI response to the string “Invalid Lead …”.
  • OpenAI Chat Model — (Type: OpenAI Chat Model) Sends the lead notes to GPT-3.5/4 with a system prompt that instructs the AI to categorize the inquiry and identify the responsible contact. Authentication: OpenAI API Key (predefined credential type).
  • Customer Lead AI Agent — (Type: AI Agent) This is a higher-level wrapper that orchestrates the conversation with the OpenAI model. It uses the same API key.
  • Company Contact Database — (Type: Google Sheets) Reads a sheet named “Telephone Directory” to find email addresses of responsible employees. Authentication: Google Sheets OAuth2.
  • Fields for Outlook — (Type: Code node) Extracts the email addresses, subject, and email body from the AI response and structures them for the email node.
  • Email Body Text Generated by AI — (Type: Code node) Converts the plain text email body (from AI) into formatted HTML using JavaScript regular expressions.
  • Email Body for Outlook — (Type: Code node) Prepares the final HTML body, including a link to the lead in the webhook environment.
  • Microsoft Outlook — (Type: Outlook node) Sends the email with the prepared subject, recipients, and HTML body. Authentication: Microsoft Outlook OAuth2.
  • Manual Trigger — (Type: Manual Trigger) Allows testing the workflow manually without waiting for a webhook.
  • Error Handler — (Type: Stop & Error) Catches any workflow execution errors and stops with a custom message.

Setup Instructions

  1. ERPNext: You need an ERPNext instance and an API key/secret. Configure the webhook to send a POST request to the n8n webhook URL (the one shown in the Webhook node) every time a new lead is created.
  2. OpenAI: Obtain an API key from OpenAI and create an n8n credential of type “OpenAI API”.
  3. Google Sheets: Create a Google Sheet named “Telephone Directory” with columns for employee names, departments, and email addresses. Enable Google Sheets OAuth2 in n8n and share the sheet with the service account.
  4. Microsoft Outlook: Use a Microsoft 365 account (work/school) and create an OAuth2 credential for Outlook in n8n. The workflow will send emails on behalf of this account.
  5. Environment Variables: The workflow uses $env.BASE_URL and $env.WEBHOOK_URL. Set these in your n8n environment to the base URL of your n8n instance and the webhook URL (or use absolute URLs).

Use Cases and Variations

  • Lead Qualification: Add more filters (e.g., country, company size) to automatically qualify leads before sending notifications.
  • Slack or Teams Notification: Replace the Outlook node with a Slack or Microsoft Teams node to send instant notifications instead of emails.
  • CRM Update: After sending the email, update the lead status in ERPNext or another CRM using an update node.
  • Multi‑product Support: Expand the Google Sheet to include multiple sheets for different product lines, and let the AI determine which sheet to query.
  • Custom AI Prompt: Modify the system prompt in the OpenAI node to change how the AI categorizes leads (e.g., urgency, sentiment).
2 nodesmanual triggerSales
Stop And Error

Workflow JSON

{
  "\"meta\"": "{",
  "\"instanceId\"": "\"e4f78845dfed9ddcfba1945ae00d12e9a7d76eab052afd19299228ce02349d86\"",
  "\"nodes\"": "[",
  "\"id\"": "\"2b4c1e91-c64b-43cb-aba2-c6f8f5a17c79\",",
  "\"name\"": "\"Webhook\",",
  "\"type\"": "\"main\",",
  "\"position\"": "[",
  "\"parameters\"": "{",
  "\"text\"": "\"=**System Prompt:**\\n\\nYou are an AI assistant designed to process new leads and generate appropriate responses. Your role includes analyzing lead notes, categorizing them, and generating an email from the system to inform the relevant contact about the inquiry. Do not send the email as if it is directly from the customer; instead, draft it as a notification from the system summarizing the inquiry.\\n\\n### **Process Flow**\\n\\n1. **Analyzing Lead Notes:**\\n - Extract key details such as the customer name, organization, contact information, and their specific request. \\n - Determine if the inquiry relates to products, services, or solutions offered by the company.\\n\\n2. **Finding the Appropriate Contact(s):**\\n - Search the contact database to find the responsible person(s) for the relevant product, service, or solution. \\n - If one person is responsible, provide their email. \\n - If multiple people are responsible, list all emails separated by commas.\\n\\n3. **Generating an Email Notification:**\\n - Draft a professional email as a notification from the system.\\n - Summarize the customer’s inquiry.\\n - Include all relevant details to assist the recipient in addressing the inquiry.\\n\\n4. **Handling Invalid Leads:**\\n - If the inquiry is unrelated to products, services, or solutions (e.g., job inquiries or general product inquiries), classify it as invalid and return: \\n `\\\"Invalid Lead - Not related to products, services, or solutions.\\\"`\\n\\n### **Output Requirements**\\n\\n1. **For Relevant Leads:**\\n - **Email Address(es):** Provide the appropriate email(s). \\n - **Email Message Body:** Generate an email notification from the system summarizing the inquiry.\\n\\n2. **For Invalid Leads:**\\n - Return: `\\\"Invalid Lead - Not related to products, services, or solutions.\\\"`\\n\\n\\n### **Email Template for Relevant Leads**\\n\\n**Email Address(es):** [Relevant Email IDs]\\n\\n**Email Message Body:**\\n\\n_Subject: New Inquiry from Customer Regarding [Product/Service/Solution]_ \\n\\nDear [Recipient(s)], \\n\\nWe have received a new inquiry from a customer through our system. Below are the details: \\n\\n**Customer Name:** [Customer Name] \\n**Organization:** [Organization Name] \\n**Contact Information:** [Contact Details] \\n\\n**Inquiry Summary:** \\n[Summarized description of the customer's request, e.g., “The customer is seeking to upgrade their restroom facilities with touchless soap dispensers and tissue holders installed behind mirrors. They have requested a site visit to assess the location and provide a proposal.”] \\n\\n**Action Required:** \\nPlease prioritize this inquiry and reach out to the customer promptly to address their requirements. \\n\\nThank you, \\n[Your System Name] \\n\\n\\n### **Example Output**\\n\\n**Input Lead Notes:**\\n*\\\"Dear Syncbricks, We are looking to Develop Workflow Automation Soluition for our company, can you let us know the details what do you offer in tems of this.\\\"*\\n\\n**Output:**\\n\\n- **Email Address(es):** [email protected]\\n\\n- **Email Message Body:** \\n\\n_Subject: Workflow Automation Platform Integration_ \\n\\nDear -Emploiyee Name (s) --, \\n\\nWe have received a new inquiry from a customer through our system. Below are the details: \\n\\n**Customer Name:** Amjid Ali \\n**Organization:** Syncbricks LLC\\n**Contact Information:** 123456789 \\n\\n**Inquiry Summary:** \\nThe customer is asking for workflow automation for their company \\n\\n**Action Required:** \\nPlease prioritize this inquiry and reach out to the customer promptly to address their requirements. \\n\\nThank you, \\nSyncbricks LLC\\n\\n---\\nHere are the Lead Details\\nLead Name : {{ $json.data.lead_name }}\\nCompany : {{ $json.data.company_name }}\\nSource : {{ $json.data.source }}\\nNotes : {{ $json.data.notes }}\\nCity : {{ $json.data.city }}\\nCountry : {{ $json.data.country }}\\nMobile : {{ $json.data.mobile_no }}\",",
  "\"options\"": "{},",
  "\"promptType\"": "\"define\"",
  "\"typeVersion\"": "2",
  "\"credentials\"": "YOUR_CREDENTIAL_HERE",
  "\"openAiApi\"": "{",
  "\"sheetName\"": "{",
  "\"__rl\"": "true,",
  "\"mode\"": "\"id\",",
  "\"value\"": "\"=Telephone Directory\"",
  "\"cachedResultUrl\"": "{{ $env.BASE_URL }}",
  "\"cachedResultName\"": "\"\"",
  "\"documentId\"": "{",
  "\"googleSheetsOAuth2Api\"": "{",
  "\"assignments\"": "[",
  "\"conditions\"": "[",
  "\"version\"": "2,",
  "\"leftValue\"": "\"={{ $json.output }}\",",
  "\"caseSensitive\"": "true,",
  "\"typeValidation\"": "\"strict\"",
  "\"combinator\"": "\"and\",",
  "\"operator\"": "{",
  "\"operation\"": "\"get\",",
  "\"rightValue\"": "\"**Invalid Lead - Not related to products, services, or solutions.**\"",
  "\"subject\"": "\"={{ $('Fields for Outlook').item.json.subject }}\",",
  "\"bodyContent\"": "\"={{ $json.html }}\\n<a href=\\\"{{ $env.WEBHOOK_URL }}{{ $('Webhook').item.json.body.name }}\\\" target=\\\"_blank\\\" rel=\\\"noopener noreferrer\\\">Here is Lead {{ $('Source Website and Status Open').item.json.body.name }} </a>\\n\",",
  "\"toRecipients\"": "\"= {{ $('Fields for Outlook').item.json.email_addresses }}\",",
  "\"additionalFields\"": "{",
  "\"bodyContentType\"": "\"html\"",
  "\"microsoftOutlookOAuth2Api\"": "{",
  "\"jsCode\"": "\"// Input email body\\nconst emailBody = $json.email_body || '';\\n\\n// Function to convert plain text email body into HTML\\nfunction formatEmailBodyAsHtml(body) {\\n // Replace markdown-like sections with corresponding HTML\\n let htmlBody = body\\n .replace(/\\\\*\\\\*Customer Name:\\\\*\\\\* (.+)/, '<p><strong>Customer Name:</strong> $1</p>')\\n .replace(/\\\\*\\\\*Organization:\\\\*\\\\* (.+)/, '<p><strong>Organization:</strong> $1</p>')\\n .replace(/\\\\*\\\\*Contact Information:\\\\*\\\\* (.+)/, '<p><strong>Contact Information:</strong> $1</p>')\\n .replace(/\\\\*\\\\*Inquiry Summary:\\\\*\\\\*\\\\s*([\\\\s\\\\S]+?)(?=\\\\n\\\\n\\\\*\\\\*Action Required:)/, '<p><strong>Inquiry Summary:</strong> $1</p>')\\n .replace(/\\\\*\\\\*Action Required:\\\\*\\\\*\\\\s*([\\\\s\\\\S]+)/, '<p><strong>Action Required:</strong> $1</p>');\\n\\n // Wrap each paragraph in `<p>` tags for better readability\\n htmlBody = htmlBody\\n .replace(/Dear (.+?),/, '<p>Dear <strong>$1</strong>,</p>')\\n .replace(/Thank you,\\\\s+(.+)/, '<p>Thank you,<br><strong>$1</strong></p>');\\n\\n return htmlBody;\\n}\\n\\n// Convert the email body into HTML\\nconst formattedHtmlBody = formatEmailBodyAsHtml(emailBody);\\n\\n// Return the formatted HTML\\nreturn {\\n html: formattedHtmlBody\\n};\\n\"",
  "\"singleValue\"": "true",
  "\"documentURL\"": "{{ $env.BASE_URL }}",
  "\"googleDocsOAuth2Api\"": "{",
  "\"color\"": "3,",
  "\"width\"": "302.58963031819115,",
  "\"height\"": "660,",
  "\"content\"": "\"### Prepare for Email\\nThis node will get approprate Fields for Email \\nEmail Addresses:\\nSubject : \\nEmail Body : \"",
  "\"url\"": "{{ $env.BASE_URL }}",
  "\"authentication\"": "\"predefinedCredentialType\",",
  "\"nodeCredentialType\"": "YOUR_CREDENTIAL_HERE",
// ... truncated (copy to see full JSON)

How to Import This Workflow

  1. 1Copy the workflow JSON above using the Copy Workflow JSON button.
  2. 2Open your n8n instance and go to Workflows.
  3. 3Click Import from JSON and paste the copied workflow.

Don't have an n8n instance? Start your free trial at n8nautomation.cloud

Related Templates

Lead Capture to Notion CRM with Alerts in Slack

Overview This workflow instantly captures leads from any web form (Webflow, Tally, WordPress, custom HTML, etc.) and creates a new entry in your Notion CRM database while simultaneously sending a formatted alert to a Slack sales channel. It eliminates manual data entry and ensures your sales team can respond to leads within seconds of submission — no Zapier subscription required. How It Works The workflow is triggered by an incoming HTTP POST request (the webhook), then processes the lead data through two sequential actions: first creating a Notion database page, then posting a Slack message. The webhook responds immediately with a 200 status so the form never hangs or times out. Node-by-Node Breakdown Lead Webhook (No auth) — Listens for incoming POST requests at the path . Accepts both JSON and form-encoded payloads. When activated, n8n provides a unique production URL that you point your form's action attribute or integration to. The node responds automatically with HTTP 200 after all downstream nodes complete. Add to Notion CRM (OAuth2) — Creates a new database page in your specified Notion database. Configured parameters: - : The Notion database ID (must be replaced with your actual database ID) - : Set dynamically to (the lead's name from the webhook payload) - : Maps the lead's email to the "Email" property and sets a "Status" select property to "New" - Requires sharing your Notion database with the n8n integration Alert Sales Channel (OAuth2) — Posts a formatted Slack message to a specified channel. Configured parameters: - : The Slack channel ID (must be replaced with your actual channel) - : A dynamic message template using expressions: - Uses Slack's markdown formatting for bold text and blockquotes Setup Instructions Prerequisites An n8n instance (self-hosted or cloud) A Notion account with a Leads database (must contain at least Name, Email, and Status properties) A Slack workspace where you can create/choose a channel for lead alerts A web form or service that can send POST requests (Webflow, Tally, WordPress, Framer, custom HTML form, etc.) Step-by-Step Activate the workflow in n8n and copy the production webhook URL from the Lead Webhook node (it will look like ) Configure your form to send a POST request to that URL with fields: , , and (JSON or form-encoded both work) Connect Notion: - Create an integration at https://www.notion.so/my-integrations - Share your Leads database with that integration - In n8n, create a Notion credential (OAuth2) and select your database - Replace with your actual database ID Connect Slack: - Create a Slack app with and scopes - Install the app to your workspace - In n8n, create a Slack credential (OAuth2) - Replace with your actual channel ID (e.g., ) Test: Submit a test lead through your form and verify it appears in Notion and Slack Use Cases & Adaptations Primary Use Cases Marketing teams: Capture leads from landing pages, webinar registrations, or content downloads Sales teams: Get instant notifications when high-value prospects submit inquiries Startups: Build a lightweight CRM without expensive tools Variations to Try Add email automation: Insert a Gmail or SendGrid node after Notion to send an auto-reply to the lead Enrich lead data: Add an HTTP Request node to look up company info via Clearbit or Hunter.io Score leads: Use an n8n Code node to assign lead scores based on message content or source Multi-channel capture: Create additional webhook nodes for different forms, each routing to the same Notion database Error handling: Build a separate Error Trigger workflow that posts to Slack when any node fails Required Replacements Before running, you must replace these placeholder values: → Your Notion database ID → Your Slack channel ID

6 nodes

AI-Powered Competitor Price RAG Pipeline with Logging

Overview This workflow implements a Retrieval-Augmented Generation (RAG) pipeline for processing and analyzing competitor pricing data. It is triggered via a webhook (e.g., by an external scraper), splits incoming text into chunks, generates embeddings using OpenAI, stores them in a Supabase vector store, and then allows an Anthropic-powered AI agent to query that context. Results are appended to a Google Sheet for record-keeping, and any errors trigger a Slack alert to a designated channel. This setup is ideal for teams that need to automate the ingestion of structured or unstructured competitor data, enable natural language queries against that data, and maintain an audit log—all without manual intervention. Node-by-Node Breakdown Sticky Note — A visual note in the editor (not executed). Webhook Trigger (No auth) — Listens for incoming POST requests at the path . This is the entry point; an external service (e.g., a custom scraper) should send data here. Text Splitter (No auth) — Splits the incoming text into chunks of 400 characters with 40 character overlap. This ensures the embeddings are meaningful and context windows are manageable. Embeddings (API Key auth — OpenAI) — Uses the model to convert each text chunk into a vector embedding. Requires an OpenAI API key. Supabase Insert (API Key auth — Supabase) — Inserts the generated embeddings into the Supabase vector store under the index . This stores the data for future retrieval. Supabase Query (API Key auth — Supabase) — Queries the same Supabase vector index to retrieve relevant chunks based on a question or input from the agent. Vector Tool (No auth) — Wraps the Supabase query as a tool that the AI agent can call to fetch contextual data. Window Memory (No auth) — Provides conversational memory (buffer window) so the agent can maintain context across multiple interactions. Chat Model (API Key auth — Anthropic) — The language model that powers the AI agent. Uses Anthropic’s Claude model (selected via credentials). Requires an Anthropic API key. RAG Agent (No auth) — The core AI agent that receives the incoming data, uses the vector tool to retrieve relevant context, and generates a response using the chat model. The system message is set to "You are an assistant for Competitor Price Scraper". Append Sheet (OAuth2 — Google Sheets) — Appends the agent’s response (from the node) to a Google Sheet named . You must specify the Google Sheet ID and sheet name in the node parameters. Slack Alert (OAuth2 — Slack) — Triggered only on error from the RAG Agent. Sends a message to the channel with the error details. Setup Instructions Accounts & Credentials – You will need: - An OpenAI account (for embeddings). Create an API key and add it in n8n as an OpenAI credential. - An Anthropic account (for the chat model). Create an API key and add it as an Anthropic credential. - A Supabase project. Enable the pgvector extension, create a table for embeddings, and get the Supabase URL + anon/public API key. Add these as a Supabase credential in n8n. - A Google Cloud project with the Sheets API enabled. Generate OAuth2 credentials (or use a service account) and add them as a Google Sheets OAuth2 credential in n8n. - A Slack workspace. Create a Slack app with chat:write permission and install it to your workspace. Add the bot token as a Slack OAuth2 credential in n8n. Configure the Webhook – The webhook path is . You can change this as needed. Expose this endpoint (e.g., via n8n’s public URL or a tunnel) so your scraper can POST data to it. Set the Google Sheet ID and sheet name – In the Append Sheet node, replace with the actual ID of your Google Sheet and ensure the sheet is named (or update the parameter). Adjust Slack Channel – In the Slack Alert node, set the channel name (default ) to one that exists in your Slack workspace. Test the workflow – Send a sample POST request with some competitor price text to the webhook URL. Check the Google Sheet for logged responses and test error handling by sending malformed data. Use Cases & Variations Competitive Intelligence – Automate the ingestion of price lists, product descriptions, or news articles from competitors. Use the AI agent to answer questions like “Which competitor has the lowest price on product X?”. Document Q&A – Adapt this pipeline for any document type (PDFs, support tickets, internal memos). Replace the webhook with a file trigger and use the same RAG flow. Multi-Source Ingestion – Add an HTTP Request node before the Text Splitter to fetch data from an API or RSS feed instead of relying on a webhook. Custom Output – Instead of a Google Sheet, send the agent’s response via email, SMS, or directly into a CRM. Scheduled Runs – Swap the Webhook Trigger for a Schedule Trigger to run the ingestion on a regular basis (e.g., daily).

12 nodes

Extract Google Maps Business Leads via Dumpling AI to Google Sheets

Overview This workflow automates the extraction of business listings from Google Maps using Dumpling AI's search-maps API and logs the results into a structured Google Sheet. It's ideal for lead generation, market research, or competitive analysis — allowing you to quickly gather data like business names, ratings, addresses, phone numbers, websites, and booking links without manual browsing. Workflow Steps Trigger: Manual Test Run (Manual Trigger) — Starts the workflow on demand for testing. No authentication required. Search Google Maps via Dumpling AI (HTTP Request) — Sends a POST request to with a JSON body containing the search query (e.g., ) and language. Authentication uses Header Auth — you must provide a Dumpling AI API key as a header (configured in n8n credentials). The response returns an array of places with details like title, rating, address, phone, website, price level, and booking links. Split Places List for Processing (Split Out) — Splits the array from the HTTP response into individual items so each place can be processed separately. No authentication needed. Save Results to Google Sheet (Place Info) (Google Sheets) — Appends each place's data (name, address, rating, price level, type, website, phone, position, booking link) to a specified sheet in a Google Sheets document. Uses OAuth2 authentication (Google account). The sheet name is set to "Google Maps" and the document ID points to a spreadsheet named "Places". Setup Instructions Dumpling AI Account: Sign up at dumplingai.com and obtain an API key. In n8n, create a new Header Auth credential with the key name (e.g., ) and value . Google Sheets: Create a Google Sheet (or use the one referenced in the workflow). In n8n, create a Google Sheets OAuth2 credential by connecting your Google account. Ensure the sheet has a tab named "Google Maps" (or update the sheet name in the node). Customize Query: Edit the of the HTTP Request node to change the search query (e.g., ) or language. Run: Click "Execute Workflow" to test. The first run will prompt you to authorize Google Sheets access. Use Cases & Variations Lead Generation: Replace the query with industry-specific terms (e.g., "dentists in Los Angeles") to build a targeted prospect list. Competitor Analysis: Search for competitors in a niche and analyze their ratings, price levels, and online presence. Real Estate / Local Business Research: Extract data for multiple locations by chaining queries or using a loop. Automation: Replace the Manual Trigger with a Schedule Trigger to run daily/weekly, and add a Set node to dynamically pass queries from a spreadsheet or webhook. Enrichment: Add nodes to clean data, send notifications (Slack/Email), or integrate with a CRM like HubSpot.

5 nodes

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.