{
  "name": "AI Email Triage \u2014 Gmail + Claude (by That Digital Strategist)",
  "nodes": [
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyX",
              "value": 5,
              "unit": "minutes"
            }
          ]
        },
        "simple": false,
        "filters": {
          "q": "is:unread in:inbox -label:ai-triaged"
        },
        "options": {}
      },
      "id": "2cd279a2-7cc6-43f7-b27e-08e6364f4e7f",
      "name": "Gmail: New Email",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        240,
        300
      ],
      "notes": "Polls every 5 minutes. Filter excludes already-triaged emails. Connect YOUR Gmail OAuth credential here with compose + label modify scopes."
    },
    {
      "parameters": {
        "jsCode": "// Pull the email fields and format them for Claude.\n// Stores the original IDs for downstream nodes (draft creation, labeling).\n\nconst email = $input.first().json;\n\n// Extract text body \u2014 fall back to snippet, then HTML stripped\nlet body = '';\nif (email.text) {\n  body = email.text;\n} else if (email.snippet) {\n  body = email.snippet;\n} else if (email.html) {\n  body = email.html.replace(/<[^>]*>/g, ' ').replace(/\\s+/g, ' ').trim();\n}\n\n// Truncate very long emails to protect API spend\nconst MAX_BODY = 6000;\nif (body.length > MAX_BODY) {\n  body = body.slice(0, MAX_BODY) + '\\n\\n[...truncated]';\n}\n\nconst formattedEmail = `From: ${email.from?.value?.[0]?.address || email.from || 'unknown'}\nSender Name: ${email.from?.value?.[0]?.name || 'unknown'}\nTo: ${email.to?.value?.[0]?.address || email.to || 'unknown'}\nSubject: ${email.subject || '(no subject)'}\nDate: ${email.date || new Date().toISOString()}\n\n---\n\n${body}`;\n\nreturn [{\n  json: {\n    emailForClaude: formattedEmail,\n    messageId: email.id,\n    threadId: email.threadId,\n    labelIds: email.labelIds || [],\n    senderEmail: email.from?.value?.[0]?.address || email.from || '',\n    senderName: email.from?.value?.[0]?.name || '',\n    originalSubject: email.subject || '',\n    replySubject: (email.subject || '').startsWith('Re:')\n      ? email.subject\n      : `Re: ${email.subject || '(no subject)'}`,\n    receivedAt: email.date || new Date().toISOString()\n  }\n}];\n"
      },
      "id": "d26fb997-f24e-453b-8a88-3da7198b2c28",
      "name": "Extract Email Data",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        300
      ],
      "notes": "Pulls subject, body, sender from the incoming email. No edits needed."
    },
    {
      "parameters": {
        "jsCode": "// =====================================================================\n// CUSTOMIZE YOUR VOICE HERE\n// =====================================================================\n// The TRIAGE_PROMPT below is what tells Claude how to classify your\n// emails AND how to write in your voice. Edit it to match yourself.\n//\n// Look for the sections marked [REPLACE THIS...] \u2014 fill them in with:\n//   1. Who you are (2-3 sentences)\n//   2. Your email voice (sign-off, length, formality, words you use/avoid)\n//\n// Save the node after editing. Save the workflow. New emails will\n// use your updated voice immediately.\n// =====================================================================\n\nconst TRIAGE_PROMPT = `# IDENTITY\n\nYou are an email triage assistant for [YOUR NAME / ROLE HERE].\n\n[REPLACE THIS PARAGRAPH WITH 2-3 SENTENCES ABOUT YOURSELF.\n Include: your name, what you do, who you work with, and anything that\n would help the model understand the context of the emails you receive.\n\n Example:\n \"I'm Jane Smith, a freelance marketing consultant. I work with B2B SaaS\n companies on lifecycle email and lead nurture. I get inquiries from\n prospects, vendor pitches, and active client work, plus newsletters\n I subscribe to.\"]\n\nYour single job: classify each incoming email and, when a reply is\nwarranted, draft a response in MY voice that I can review and send.\n\n# MY EMAIL VOICE\n\n[REPLACE THIS SECTION WITH YOUR OWN VOICE RULES.\n The model will draft replies in this style.\n\n Strong examples to include:\n - How you sign off (e.g., \"\u2014 Jane\", \"Best, J\", \"Talk soon,\")\n - Average reply length (e.g., \"2-3 sentences max\")\n - Formality level (casual / professional / mixed by recipient)\n - Specific phrases you USE often\n - Specific phrases you NEVER use\n - Whether you use contractions\n - Whether you use lowercase casual style for known contacts\n\n Example voice rules:\n - Warm but efficient. Get to the point in the first sentence.\n - Sign off \"\u2014 Jane\"\n - One paragraph for most replies. Two max.\n - I use contractions. No corporate stiffness.\n - I never say \"I hope this finds you well\" or \"circle back\" or \"leverage.\"\n - For people I know well, I write lowercase casual. For new contacts, normal caps.]\n\n# CLASSIFICATION CATEGORIES\n\nREPLY_NEEDED \u2014 Personal email, direct question from a known contact, a\nbusiness question warranting a response. Draft a reply.\n\nLEAD \u2014 Sales inquiry, prospect, partnership pitch, podcast or speaking\ninvitation, agency or freelance inquiry. Draft a qualifying reply that\neither moves the conversation forward or politely declines.\n\nFYI \u2014 A newsletter you actually read, a status update, a notification\nworth seeing but not actioning, a CC where you're not the primary\nrecipient. No draft.\n\nNEWSLETTER \u2014 Routine marketing emails, promotions, automated product\nupdates you don't typically engage with. No draft.\n\nSPAM \u2014 Cold outreach with no personalization, generic sales pitches,\nphishing attempts, low-effort automation. No draft.\n\nURGENT \u2014 Same as REPLY_NEEDED but flagged as time-sensitive. Examples:\nclient emergencies, interview scheduling, payment/invoice issues,\nanything with deadlines today or tomorrow. Draft a reply AND flag\npriority as high.\n\n# DRAFTING RULES\n\nWhen you draft a reply:\n1. Address the sender by first name if their name is in the email.\n2. Acknowledge their specific ask in the first sentence \u2014 never generic.\n3. Answer or move the conversation forward in the second sentence.\n4. If asked for time, propose 2-3 specific 30-min windows (use a\n   placeholder like \"[propose 2-3 windows next week]\" \u2014 you'll fill in\n   your actual calendar before sending).\n5. If declining, decline cleanly. No vague \"let me circle back.\"\n6. End with your sign-off (see MY EMAIL VOICE above).\n\n# DECISION HEURISTICS\n\n- If from a personal email address AND mentions you by name AND asks\n  a specific question \u2192 REPLY_NEEDED.\n- If from a company domain mentioning consulting, fractional, contract,\n  hire, or \"I saw your\" \u2192 LEAD.\n- If body contains \"unsubscribe\" link AND comes from a marketing\n  platform (Mailchimp, HubSpot, etc.) \u2192 NEWSLETTER.\n- If from a no-reply address with no personalization \u2192 SPAM unless it\n  contains account/security info \u2192 FYI.\n- If subject contains \"urgent\", \"asap\", \"today\", or a date within 48 hrs\n  AND is not marketing \u2192 URGENT.\n\n# OUTPUT FORMAT \u2014 STRICT\n\nOutput ONLY valid JSON. No preamble. No markdown fences. No commentary.\nUse this exact schema:\n\n{\n  \"classification\": \"REPLY_NEEDED\" | \"LEAD\" | \"FYI\" | \"NEWSLETTER\" | \"SPAM\" | \"URGENT\",\n  \"confidence\": \"high\" | \"medium\" | \"low\",\n  \"reasoning\": \"one sentence explaining the classification\",\n  \"priority\": \"high\" | \"normal\" | \"low\",\n  \"sender_name\": \"first name only, or null if unknown\",\n  \"summary\": \"what the email is actually asking (max 15 words, or null if no draft needed)\",\n  \"draft\": \"full email reply text in my voice, with my sign-off, or null\"\n}\n\nIf classification is FYI, NEWSLETTER, or SPAM, set draft to null.\nIf classification is REPLY_NEEDED, LEAD, or URGENT, draft must be a complete reply.\n`;\n\nconst data = $input.first().json;\n\nreturn [{\n  json: {\n    ...data,\n    systemPrompt: TRIAGE_PROMPT,\n    userMessage: `Triage this email and return ONLY the JSON object per the schema:\\n\\n${data.emailForClaude}`\n  }\n}];\n"
      },
      "id": "d2df4c38-dc90-4182-970b-9c665579785d",
      "name": "Build Claude Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        680,
        300
      ],
      "notes": "\u2b50 EDIT THIS NODE to customize your voice. Look for [REPLACE THIS...] sections in the TRIAGE_PROMPT."
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.anthropic.com/v1/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "anthropic-version",
              "value": "2023-06-01"
            },
            {
              "name": "content-type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({\n  model: 'claude-opus-4-5',\n  max_tokens: 2048,\n  system: $json.systemPrompt,\n  messages: [\n    {\n      role: 'user',\n      content: $json.userMessage\n    }\n  ]\n}) }}",
        "options": {
          "timeout": 60000
        }
      },
      "id": "f5311dd6-909c-4118-9229-a6cd0e06f322",
      "name": "Call Claude API",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        900,
        300
      ],
      "notes": "Connect Header Auth credential here. Header name: x-api-key, value: your Anthropic API key. Get a key at console.anthropic.com."
    },
    {
      "parameters": {
        "jsCode": "// Parse Claude's JSON response with defensive fallback handling.\n\nconst response = $input.first().json;\nconst meta = $('Extract Email Data').first().json;\n\nlet rawText = response.content?.[0]?.text || '';\n\n// Strip markdown fences if Claude added them\nrawText = rawText\n  .replace(/^```json\\s*/i, '')\n  .replace(/^```\\s*/i, '')\n  .replace(/\\s*```$/i, '')\n  .trim();\n\nlet parsed = {};\ntry {\n  parsed = JSON.parse(rawText);\n} catch (e) {\n  const match = rawText.match(/\\{[\\s\\S]*\\}/);\n  if (match) {\n    try {\n      parsed = JSON.parse(match[0]);\n    } catch (e2) {\n      parsed = {\n        classification: 'PARSE_ERROR',\n        confidence: 'low',\n        reasoning: 'Could not parse Claude response',\n        draft: null\n      };\n    }\n  } else {\n    parsed = {\n      classification: 'PARSE_ERROR',\n      confidence: 'low',\n      reasoning: 'No JSON found in response',\n      draft: null\n    };\n  }\n}\n\nconst draftCategories = ['REPLY_NEEDED', 'LEAD', 'URGENT'];\nconst shouldDraft = draftCategories.includes(parsed.classification) && parsed.draft;\n\nreturn [{\n  json: {\n    ...meta,\n    classification: parsed.classification,\n    confidence: parsed.confidence,\n    reasoning: parsed.reasoning,\n    priority: parsed.priority || 'normal',\n    senderFirstName: parsed.sender_name,\n    summary: parsed.summary,\n    draftBody: parsed.draft,\n    shouldDraft: shouldDraft,\n    triageTimestamp: new Date().toISOString()\n  }\n}];\n"
      },
      "id": "d5bd3738-5d72-42ff-8278-acfc1dbe0aa4",
      "name": "Parse Triage Result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1120,
        300
      ],
      "notes": "Parses Claude's structured JSON output. No edits needed."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "0fa1d9ff-38a6-4086-ad84-1aa4c1d8d57b",
              "leftValue": "={{ $json.shouldDraft }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "fb8f1711-3d8e-4365-8a14-520e9d169528",
      "name": "Should Draft?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1340,
        300
      ],
      "notes": "Routes TRUE branch (create draft) or FALSE branch (just label)."
    },
    {
      "parameters": {
        "resource": "draft",
        "subject": "={{ $json.replySubject }}",
        "emailType": "text",
        "message": "={{ $json.draftBody }}",
        "options": {
          "sendTo": "={{ $json.senderEmail }}",
          "threadId": "={{ $json.threadId }}"
        }
      },
      "id": "7462d857-5c97-49b9-a8ef-c0395ee35024",
      "name": "Create Gmail Draft",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1580,
        200
      ],
      "notes": "SAFETY: Creates a draft only. Never sends. Reuse the Gmail credential from the trigger node."
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "addLabels",
        "messageId": "={{ $('Parse Triage Result').first().json.messageId }}",
        "labelIds": [
          "ai-triaged"
        ]
      },
      "id": "7fe680b7-405f-403d-9554-32b2346d252a",
      "name": "Label as Triaged (Draft)",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1800,
        200
      ],
      "notes": "Applies 'ai-triaged' label after a draft is created. Make sure you've created this label in Gmail first."
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "addLabels",
        "messageId": "={{ $('Parse Triage Result').first().json.messageId }}",
        "labelIds": [
          "ai-triaged"
        ]
      },
      "id": "0bde1a90-b408-4858-9218-f7218e7ca4f7",
      "name": "Label as Triaged (Skipped)",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1580,
        400
      ],
      "notes": "Applies 'ai-triaged' label even when no draft is created \u2014 prevents reprocessing."
    }
  ],
  "connections": {
    "Gmail: New Email": {
      "main": [
        [
          {
            "node": "Extract Email Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Email Data": {
      "main": [
        [
          {
            "node": "Build Claude Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Claude Prompt": {
      "main": [
        [
          {
            "node": "Call Claude API",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Call Claude API": {
      "main": [
        [
          {
            "node": "Parse Triage Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Triage Result": {
      "main": [
        [
          {
            "node": "Should Draft?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Should Draft?": {
      "main": [
        [
          {
            "node": "Create Gmail Draft",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Label as Triaged (Skipped)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Gmail Draft": {
      "main": [
        [
          {
            "node": "Label as Triaged (Draft)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "8f05e15e-75bc-4b23-aa6f-58c6770453f4",
  "id": "bf234adb-97e3-4d75-9d28-0c8b95fa9c20",
  "meta": {
    "templateCredsSetupCompleted": false,
    "instanceId": ""
  },
  "tags": [
    {
      "name": "email-triage"
    },
    {
      "name": "claude"
    },
    {
      "name": "lead-magnet"
    }
  ]
}