Automate Lead Handling & Emailing with n8n AI Agent

This n8n workflow automates lead processing by analyzing customer inquiries, filtering valid leads, and generating targeted email notifications. Using AI to pinpoint correct contacts, it streamlines communication and reduces manual errors for businesses managing incoming website leads.
agent
lmChatOpenAi
googleSheetsTool
+8
Workflow Identifier: 1117
NODES in Use: agent, lmChatOpenAi, googleSheetsTool, set, if, microsoftOutlook, code, googleDocsTool, httpRequest, webhook, stickyNote

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 connects ERPNext leads to company contacts and sends notification emails automatically.
It stops the need to check every lead manually.
The workflow reads new leads, finds the right person, and writes an email to tell them about the customer inquiry.
You get faster replies and fewer lost chances to sell.

The workflow starts when a lead is made in ERPNext.
It gathers lead details, reads notes to understand what the customer wants, and looks up product and contact info in Google Docs and Sheets.
Then, an AI node creates a clear, polite email summary.
Finally, the workflow sends the email through Microsoft Outlook.


Tools and Services Used

  • ERPNext: Provides lead data and triggers for new leads.
  • n8n: Automates the entire process with nodes including webhook, HTTP Request, and AI Agent.
  • AI Agent node (LangChain with OpenAI): Reads notes, extracts details, classifies inquiry, drafts email.
  • Google Docs: Stores company profile and policy text for referencing.
  • Google Sheets: Holds contact database to map inquiries to the right team.
  • Microsoft Outlook: Sends the finalized email notifications.
  • OpenAI API: Enables AI processing inside n8n.

Inputs, Processing Steps, and Outputs

Inputs

  • New lead data from ERPNext webhook.
  • Company documents from Google Docs.
  • Contact database from Google Sheets.

Processing Steps

  1. Webhook catches new lead creation with HTTP POST.
  2. Checks lead source is “Website” and status is “Open” with the If node.
  3. Fetches full lead details via HTTP Request to ERPNext API.
  4. Verifies lead has notes to process.
  5. Loads company profile and policies from Google Docs, and contacts from Google Sheets.
  6. The AI Agent node reads lead notes and documents, then extracts needed data like customer name, inquiry type, and who to contact.
  7. Checks AI result to confirm the inquiry is valid.
  8. A Code node extracts email addresses, subject line, and email text from the AI output.
  9. Another Code node formats the email body text into clean HTML.
  10. Sends the email to chosen contacts using the Microsoft Outlook node.

Outputs

  • Professional, well-structured email notifications sent automatically.
  • Faster response to customer inquiries.
  • Reduced manual work and human errors in lead handling.

Beginner Step-by-Step: How to Use This Workflow in n8n

Step 1: Import the Workflow

  1. Download the workflow file from this page using the Download button.
  2. Open the n8n editor.
  3. Click “Import from File” and select the downloaded workflow file.

Step 2: Configure Credentials and Settings

  1. Add API credentials for ERPNext, Google Docs, Google Sheets, Microsoft Outlook, and OpenAI within n8n.
  2. Update any IDs such as Google Sheet IDs, Google Doc URLs, or email addresses if needed.
  3. Check the Webhook node URL and set it in ERPNext webhook settings.
  4. If prompts or code blocks require changes, copy and paste the exact code provided in the workflow description.

Step 3: Test the Workflow

  1. Trigger a test lead in ERPNext to send data to the webhook.
  2. Monitor n8n runs to confirm data flows correctly and emails are generated.

Step 4: Activate the Workflow

  1. Switch the workflow status to Active.
  2. Now all new leads from ERPNext will be processed automatically.

You can expand or customize later, but this gets the automation running fast and reduces manual work.
For advanced privacy or full control, consider self-host n8n.


Customization Ideas ✏️

  • Change the If node filters to include leads from email or phone.
  • Add a WhatsApp step after sending emails for quick alerts.
  • Edit the AI Agent prompt to email multiple contacts at once.
  • Include links or attachments fetched from ERPNext lead files.
  • Modify email wording or branding inside the AI prompt in the Customer Lead AI Agent node.

Troubleshooting 🔧

  • Invalid lead error: check lead notes and AI prompt completeness.
  • Emails not sending: renew Microsoft Outlook OAuth credentials.
  • Google Sheets contact list not loading: verify sheet ID and share settings.

Pre-Production Checklist ✅

  • Make sure ERPNext triggers webhook with new lead data.
  • Test AI Agent node with different lead notes.
  • Confirm Google Docs and Sheets nodes access and permissions.
  • Send test email through Microsoft Outlook node.
  • Confirm that invalid leads are blocked and no emails sent.

Summary of Benefits and Outcomes

✓ Saves over 10 hours weekly by automating lead reviews.
✓ Delivers fast, accurate customer inquiry emails.
✓ Cuts human error and lost sales chances.
✓ Uses AI plus real company data for precise routing.
✓ Easy to import and activate inside the n8n editor.
✓ Scales with company needs and communication channels.


Code Snippet: Extract Fields From AI Output

This JavaScript Code node parses the AI generated text to extract emails, subject, and email body.

const textOutput = $json?.output || '';
function extractFields(text) {
 const fields = {};
 const emailMatch = text.match(/\*\*Email Address\(es\):\*\*\s*([^\n]+)/);
 const subjectMatch = text.match(/_Subject:\s*([^_]+)/);
 const emailBodyMatch = text.match(/Dear[\s\S]+/);
 fields.email_addresses = emailMatch ? emailMatch[1].trim() : null;
 fields.subject = subjectMatch ? subjectMatch[1].trim() : null;
 fields.email_body = emailBodyMatch ? emailBodyMatch[0].trim() : null;
 return fields;
}
const extractedFields = extractFields(textOutput);
return { json: extractedFields };

Code Snippet: Format Email Body to HTML

This Code node converts plain text email content into a nice HTML structure for professional emails.

const emailBody = $json.email_body || '';
function formatEmailBodyAsHtml(body) {
 let htmlBody = body
 .replace(/\*\*Customer Name:\*\* (.+)/, '<p><strong>Customer Name:</strong> $1</p>')
 .replace(/\*\*Organization:\*\* (.+)/, '<p><strong>Organization:</strong> $1</p>')
 .replace(/\*\*Contact Information:\*\* (.+)/, '<p><strong>Contact Information:</strong> $1</p>')
 .replace(/\*\*Inquiry Summary:\*\*\s*([\s\S]+?)(?=\n\n\*\*Action Required:)/, '<p><strong>Inquiry Summary:</strong> $1</p>')
 .replace(/\*\*Action Required:\*\*\s*([\s\S]+)/, '<p><strong>Action Required:</strong> $1</p>');
 htmlBody = htmlBody
 .replace(/Dear (.+?),/, '<p>Dear <strong>$1</strong>,</p>')
 .replace(/Thank you,\s+(.+)/, '<p>Thank you,<br><strong>$1</strong></p>');
 return htmlBody;
}
const formattedHtmlBody = formatEmailBodyAsHtml(emailBody);
return { html: formattedHtmlBody };

Frequently Asked Questions

The workflow uses a webhook node that receives new lead data when ERPNext creates a lead. It then fetches full lead details using an HTTP Request node calling the ERPNext API.
The AI Agent node reads incoming lead notes and company documents, extracts key inquiry details, classifies the inquiry, finds responsible contacts, and drafts the notification email text.
After importing, the user configures credentials and IDs, triggers a test lead in ERPNext, then monitors n8n to confirm correct data processing and email sending before activating the workflow.
Check that Microsoft Outlook OAuth credentials in n8n are valid and not expired. Also verify correct field mappings for recipient emails and subject lines.

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