DEV Community

Cover image for Building an Event-Driven Invoice Follow-Up Engine in n8n (with Autonomous Reply Detection)
Ruesch Manny
Ruesch Manny

Posted on

Building an Event-Driven Invoice Follow-Up Engine in n8n (with Autonomous Reply Detection)

⚑ TL;DR β€” Ready-to-Deploy Automation Blueprints:


Chasing unpaid invoices and pending quotes is a manual, soul-crushing drain on operational resources. If you don't follow up, cash flow slows down. But if you automate it blindly, you inevitably end up sending an aggressive "Please pay immediately" email to a client who replied "Paid it yesterday!" three hours prior.

In this technical guide, I'll show you how I built a Smart Invoice & Quote Follow-Up Engine using n8n. This self-hosted, event-driven architecture automates multi-step follow-up sequences, but more importantly, it features an IMAP-driven interrupt mechanism that instantly halts reminders the second a client replies.

Here is a complete breakdown of the architecture, the code, and how to run it in production.


1. The Bottleneck: Why Commercial Solutions Fall Short

If you look at the market for accounts receivable automation, you're faced with two bad options:

  1. Overpriced SaaS: Platforms that charge $50 to $200/month just to run basic cron jobs and send emails.
  2. Fragile CRM Workflows: Built-in sequences in tools like HubSpot or Salesforce that struggle with asynchronous real-world events. They often require manual intervention to move a lead out of a "sequence" once a reply hits the inbox.

We need a system that is completely autonomous, highly customizable, and decoupled from vendor lock-in. By using n8n (node-based event-driven automation), we can combine Webhook triggers, Wait nodes, and IMAP listeners to create a self-healing state machine.


2. The Architecture

The engine is split into two asynchronous workflows that communicate with each other:

Workflow A: The Drip Sequence

  1. Webhook Trigger: Receives an incoming JSON payload (from Stripe, Xero, or your CRM) containing the invoice_id, client_email, amount, and due_date.
  2. Send Email Node (SMTP): Dispatches the initial friendly reminder.
  3. Wait Node: Configured to suspend workflow execution for 5 days OR until a specific Webhook URL is called.
  4. Condition / Switch Node: Evaluates why the Wait node resumed. If it resumed because of a timeout, escalate to Email 2. If it resumed because of a webhook (client replied or paid), gracefully terminate.

Workflow B: The IMAP Listener & Reply Detector

  1. Email Read Trigger (IMAP): Polls the billing inbox for new incoming emails.
  2. Code Node: Parses the subject line and email body to extract the invoice_id or quote_id.
  3. HTTP Request Node: If an ID is found, it sends a POST request to Workflow A's Wait Node webhook, instantly interrupting the sequence and preventing future emails.

3. The Code & Logic

The Webhook Payload (JSON Schema)

Workflow A expects a structured payload. Here is the JSON schema of the trigger:

{
  "type": "object",
  "properties": {
    "invoice_id": { "type": "string", "pattern": "^INV-\\d+$" },
    "client_email": { "type": "string", "format": "email" },
    "client_name": { "type": "string" },
    "amount": { "type": "number" },
    "pdf_link": { "type": "string", "format": "uri" }
  },
  "required": ["invoice_id", "client_email", "amount"]
}
Enter fullscreen mode Exit fullscreen mode

The Reply Parser (n8n Code Node)

The magic happens in Workflow B. When an email hits your inbox, we need a reliable way to map that email back to an active sequence. We do this by parsing the subject line for the Invoice ID using a JavaScript Code Node.

// n8n Code Node: Extract Invoice ID from IMAP Email
const items = $input.all();
const results = [];

for (const item of items) {
  const subject = item.json.subject || "";
  const body = item.json.text || "";
  const sender = item.json.from.address || "";

  // Regex to find patterns like INV-10024 or QUOTE-882
  const invoiceRegex = /(INV|QUOTE)-\d{4,6}/i;
  const match = subject.match(invoiceRegex) || body.match(invoiceRegex);

  if (match) {
    results.push({
      json: {
        hasMatch: true,
        referenceId: match[0].toUpperCase(),
        senderEmail: sender,
        // Sanitize the body to keep logs clean
        snippet: body.substring(0, 300).replace(/\n/g, ' ')
      }
    });
  } else {
    results.push({
      json: { hasMatch: false }
    });
  }
}

return results;
Enter fullscreen mode Exit fullscreen mode

Triggering the Interrupt (HTTP Request Node)

Once Workflow B extracts the INV-XXXX ID, it routes into an HTTP Request Node.
n8n's Wait node generates a unique webhook URL based on the execution ID. To decouple this without needing a database, you can route the HTTP Request to your CRM to update a "Status" field, or use n8n's local execution tags to halt the process.

If you prefer a stateless interrupt, Workflow B's HTTP node simply updates your CRM to status: replied. When Workflow A wakes up from its 5-day wait, its very next step is an HTTP Request to check the CRM status. If status === 'replied', it terminates.


4. Deployment & Performance

When deploying this in a production n8n environment, keep these constraints in mind:

  • Long-Running Executions: Because Workflow A uses a Wait Node that can span weeks, ensure your EXECUTIONS_DATA_PRUNE environment variable is set high enough (e.g., EXECUTIONS_DATA_MAX_AGE=720). If n8n prunes the execution before the Wait node finishes, the sequence dies.
  • IMAP Rate Limits: Configure the Email Read trigger to poll every 5 or 10 minutes. Polling every minute can trigger rate limits on Google Workspace or Office365.
  • Error Escalation: Add an Error Trigger workflow. If the SMTP node fails (e.g., bounced email), catch the error, parse the execution data, and send an alert to your Slack/Discord so you can fix the client's email address.

5. Conclusion & Turnkey Package

By leveraging n8n's native Wait nodes and IMAP integration, you can build an automated, state-aware follow-up engine that protects your cash flow without risking your professional reputation through mistimed emails.

You can easily recreate this architecture using the code snippets and logic provided above. However, if you want to skip the trial-and-error, error handling, and regex tuning, I've packaged the entire production-ready system.

The turnkey package includes the complete n8n Workflow JSON blueprints, pre-configured delay nodes, smart reply parsing logic, and a full node configuration guide.

Grab the system here:

  • Instant Access on Whop: Link
  • Direct Download on Gumroad: Link with promo code EARLYBIRD (-20%).

Stop chasing invoices manually and let your infrastructure do the heavy lifting.


πŸ› οΈ D'autres outils MR Studio qui pourraient vous intΓ©resser :

Top comments (0)