{
  "name": "13 Email agent: sort and draft replies with approval",
  "nodes": [
    {
      "id": "f3954cdb-ac62-448d-a6eb-a00f6546f112",
      "name": "New email",
      "type": "n8n-nodes-base.emailReadImap",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "parameters": {
        "mailbox": "INBOX",
        "postProcessAction": "read",
        "format": "simple",
        "options": {}
      }
    },
    {
      "id": "c8a2a9f4-66ea-4fa3-a586-160bfc3f8949",
      "name": "Fixed rules",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        300
      ],
      "parameters": {
        "jsCode": "// Fixed rules on the sender: those are reliable, loose keywords are not.\n// Fill the lists with your own suppliers and regular senders.\nconst regels = [\n  { category: 'invoice',     sender: /^(accounts|accounting|billing|invoices?)@/i },\n  { category: 'supplier', sender: /@(supplier-one\\.example|supplier-two\\.example)$/i },\n];\nreturn $input.all().map(i => {\n  const from = ((i.json.from || '').match(/<([^>]+)>/) || [null, i.json.from || ''])[1].trim();\n  const hit = false ? null : regels.find(r => r.sender.test(from));\n  return { json: { ...i.json, category: hit ? hit.category : null, route: hit ? 'rule' : 'ai' } };\n});"
      }
    },
    {
      "id": "1149cc89-a99e-4e07-a603-1044388d6fbf",
      "name": "Rule matched?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        480,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "r",
              "leftValue": "={{ $json.route }}",
              "rightValue": "rule",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "36e32023-abdd-4a86-bd75-e649729ffaf8",
      "name": "AI picks category",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.5,
      "position": [
        760,
        60
      ],
      "parameters": {
        "promptType": "define",
        "text": "=Subject: {{ $json.subject }}\n\n{{ ($json.textPlain || '').slice(0, 2000) }}",
        "messages": {
          "messageValues": [
            {
              "message": "You sort the inbox of a small business. Pick exactly one category for the user's email. Answer with only the category word, no explanation.\n\nCategories:\n- quote_request: Someone asks for a price, quote or availability for new work\n- client_question: An existing client has a question, complaint or change about ongoing or delivered work, including about an invoice\n- appointment: Planning, moving or confirming an appointment, visit, measuring, installation or handover\n- supplier: A message from a supplier about an order, delivery, stock or prices\n- invoice: An invoice, payment or credit note without a question or complaint\n- unsubscribe: Someone no longer wants to receive mailings\n- job_application: A job application, vacancy or internship\n- newsletter: A newsletter, webinar or promotional offer\n- other: Fits nowhere else, such as personal messages, parcel notifications or announcements"
            }
          ]
        }
      },
      "notes": "AI only for what the rules do not recognize",
      "notesInFlow": true,
      "retryOnFail": true,
      "maxTries": 2,
      "onError": "continueRegularOutput"
    },
    {
      "id": "5f10401b-36c8-4a9b-93ba-8e2eeca549aa",
      "name": "Chat model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOllama",
      "typeVersion": 1,
      "position": [
        780,
        260
      ],
      "parameters": {
        "model": "qwen2.5:7b",
        "options": {
          "temperature": 0.2
        }
      }
    },
    {
      "id": "d146613c-892c-406b-bc9d-176bc0a2e60f",
      "name": "Check answer",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1060,
        60
      ],
      "parameters": {
        "jsCode": "// Any answer that is not a known category goes to a human.\nconst ok = [\"quote_request\", \"client_question\", \"appointment\", \"supplier\", \"invoice\", \"unsubscribe\", \"job_application\", \"newsletter\", \"other\"];\nreturn $input.all().map((i, n) => {\n  const mail = $('Rule matched?').all(1)[n]?.json || {};\n  const a = String(i.json.text || '').toLowerCase().replace(/[^a-z_]/g, '');\n  return { json: { ...mail, category: ok.includes(a) ? a : 'review', route: 'ai' } };\n});"
      }
    },
    {
      "id": "ff2255a9-9154-4dfc-9a73-31a92eab35a0",
      "name": "Add to inbox log",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1,
      "position": [
        1340,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultName": "inbox_log"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "sender": "={{ $json.from }}",
            "subject": "={{ $json.subject }}",
            "category": "={{ $json.category }}",
            "route": "={{ $json.route }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "sender",
              "displayName": "sender",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "subject",
              "displayName": "subject",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "category",
              "displayName": "category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "route",
              "displayName": "route",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "38c0cc59-1572-4875-af05-d9f12d045676",
      "name": "Reply needed?",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        1340,
        520
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "n",
              "leftValue": "={{ [\"quote_request\", \"client_question\", \"appointment\"].includes($json.category) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "98c24fcc-da85-41b8-9ebf-5d4a64afc8bc",
      "name": "One draft per email",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.2,
      "position": [
        1580,
        520
      ],
      "parameters": {
        "source": "database",
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultName": "14 Draft reply with approval (per email)"
        },
        "mode": "each",
        "options": {
          "waitForSubWorkflow": false
        }
      },
      "notes": "Each email gets its own execution that waits for approval",
      "notesInFlow": true
    },
    {
      "id": "5f786dec-5223-46c3-adc1-c163fbb8fc3b",
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -160
      ],
      "parameters": {
        "content": "## Email agent: sort and draft replies with approval\nTested on November 11, 2026, with n8n 2.47.3 and qwen2.5:7b (Ollama), 50 test emails: 46 sorted correctly.\n\n**Fill in:** an IMAP account, a chat model, the *inbox_log* table, your own suppliers in 'Fixed rules', and pick template 14 in 'One draft per email'.\n\nThis workflow sends nothing itself: template 14 only sends after your click.",
        "height": 220,
        "width": 520,
        "color": 7
      }
    }
  ],
  "connections": {
    "New email": {
      "main": [
        [
          {
            "node": "Fixed rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fixed rules": {
      "main": [
        [
          {
            "node": "Rule matched?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Rule matched?": {
      "main": [
        [
          {
            "node": "Add to inbox log",
            "type": "main",
            "index": 0
          },
          {
            "node": "Reply needed?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "AI picks category",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI picks category": {
      "main": [
        [
          {
            "node": "Check answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check answer": {
      "main": [
        [
          {
            "node": "Add to inbox log",
            "type": "main",
            "index": 0
          },
          {
            "node": "Reply needed?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Chat model": {
      "ai_languageModel": [
        [
          {
            "node": "AI picks category",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Reply needed?": {
      "main": [
        [
          {
            "node": "One draft per email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  }
}