{
  "id": "z6QF6JvVLiEdA4Ij",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Intelligent Gmail Email Auto Organizer with Google Sheets Rules",
  "tags": [],
  "nodes": [
    {
      "id": "a06719ac-b0f9-4f5d-927c-a7acfa2a1752",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -2416,
        520
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes"
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "fb2532f6-d850-4a11-b741-33b8d0a4503d",
      "name": "Get many messages",
      "type": "n8n-nodes-base.gmail",
      "position": [
        -2192,
        400
      ],
      "parameters": {
        "filters": {
          "labelIds": [
            "INBOX"
          ]
        },
        "operation": "getAll"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "f2773ff3-af21-4a57-bf87-c58a8fb9272a",
      "name": "Loop Over Items",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        -1744,
        400
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "e9f96ccc-a1cc-497f-aceb-b3867dd39dd3",
      "name": "Is marketing/automated email?",
      "type": "n8n-nodes-base.if",
      "position": [
        -1520,
        -16
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "or",
          "conditions": [
            {
              "id": "d31b4425-e112-4c3d-8ed4-cba2fa7bb6db",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{\n(() => {\n  const fromRaw = ($json[\"From\"] || \"\").toString().toLowerCase();\n  const fromEmail = (fromRaw.match(/<([^>]+)>/)?.[1] || fromRaw).trim();\n  const patterns = [\n    // delete immediately\n    \"ivan@mail.notion.so\", \"notifications@discord.com\",\n    // promotions\n    \"newsletter@\", \"mailer@\", \"bounce@\",\n    \"@linkedin.com\", \"@e.linkedin.com\", \"@facebookmail.com\",\n    \"@mail.instagram.com\", \"@slack.com\", \"@mailchimp.com\",\n    \"info@e.atlassian.com\",\n    \"x.com\",\n    \"navicosoft.com\"\n  ];\n  return patterns.some(p => fromEmail.includes(p));\n})()\n}}",
              "rightValue": ""
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "81a86b7e-0a23-45d4-9491-200fc7487156",
      "name": "Promotional",
      "type": "n8n-nodes-base.gmail",
      "position": [
        48,
        -32
      ],
      "parameters": {
        "labelIds": [
          "CATEGORY_PROMOTIONS"
        ],
        "messageId": "={{ $json.id }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "f6d6425d-0474-49c2-b54b-e7c848fbb200",
      "name": "Remove From Inbox",
      "type": "n8n-nodes-base.gmail",
      "position": [
        272,
        88
      ],
      "parameters": {
        "labelIds": [
          "INBOX"
        ],
        "messageId": "={{ $json.id }}",
        "operation": "removeLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "7694b09a-a5f6-479e-9008-5b97e6693d6e",
      "name": "Mark as read",
      "type": "n8n-nodes-base.gmail",
      "position": [
        496,
        160
      ],
      "parameters": {
        "messageId": "={{ $json.id }}",
        "operation": "markAsRead"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "a571c442-ae22-4f4d-b5d9-7b50b9b3a880",
      "name": "Add Label",
      "type": "n8n-nodes-base.gmail",
      "position": [
        48,
        184
      ],
      "parameters": {
        "labelIds": "={{ [$json.labelId].filter(Boolean) }}",
        "messageId": "={{ $json.id }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "a4d6f349-4fdf-4f00-b708-96b805f06f14",
      "name": "Gmail Labels",
      "type": "n8n-nodes-base.gmail",
      "position": [
        -848,
        512
      ],
      "parameters": {
        "resource": "label",
        "returnAll": true
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "33b24f3b-3e2a-4a37-8cf6-73d2bbf41f65",
      "name": "is Label Exist?",
      "type": "n8n-nodes-base.if",
      "position": [
        -176,
        184
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "or",
          "conditions": [
            {
              "id": "d31b4425-e112-4c3d-8ed4-cba2fa7bb6db",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              },
              "leftValue": "={{ $json.labelId }}",
              "rightValue": "extra"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "9848ff9b-22bc-4c6f-a023-3b379680f2f5",
      "name": "Merge",
      "type": "n8n-nodes-base.merge",
      "position": [
        -624,
        184
      ],
      "parameters": {},
      "typeVersion": 3.2
    },
    {
      "id": "0fa625ab-3ebf-4568-a508-324bf1371b72",
      "name": "Sheet Rules",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        -1360,
        160
      ],
      "parameters": {
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/11eTXs7UN8H0aqXxOvUvCEO_zDRyArBnibUYet0MhKrE/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "11eTXs7UN8H0aqXxOvUvCEO_zDRyArBnibUYet0MhKrE",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/11eTXs7UN8H0aqXxOvUvCEO_zDRyArBnibUYet0MhKrE/edit?usp=drivesdk",
          "cachedResultName": "Email Rules"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "2b4ef6c6-535e-47f1-8834-d5b9544ff690",
      "name": "Merge1",
      "type": "n8n-nodes-base.merge",
      "position": [
        -1072,
        184
      ],
      "parameters": {
        "mode": "chooseBranch"
      },
      "typeVersion": 3.2
    },
    {
      "id": "f500be31-f1b5-46a4-bb49-1db7910ef748",
      "name": "Parse Sender Email",
      "type": "n8n-nodes-base.code",
      "position": [
        -1968,
        400
      ],
      "parameters": {
        "jsCode": "return items.map(it => {\n  const raw = String(it.json.From || \"\");\n  const email = (raw.toLowerCase().match(/<([^>]+)>/)?.[1] || raw.toLowerCase()).trim();\n  it.json._fromEmail = email;\n  return it;\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "a12ff76d-5b4c-4f2e-8388-615a7ac24484",
      "name": "Apply Sheet Rules",
      "type": "n8n-nodes-base.code",
      "position": [
        -848,
        184
      ],
      "parameters": {
        "jsCode": "// Use pre-parsed email\nconst fromEmail = (s) => String(s || '').toLowerCase();\n\n// Build rules from Google Sheet\nconst rows = $items('Sheet Rules', 0).map(i => i.json);\nconst rules = rows\n  .filter(r => r.Pattern && r.Action)\n  .map(r => ({\n    pattern: String(r.Pattern).toLowerCase().trim(),\n    action: String(r.Action).toUpperCase().trim(),        // DELETE | PROMO | LABEL\n    labelName: String(r.LabelName || '').trim(),\n    labelId: r.LabelId ? String(r.LabelId).trim() : null,\n    removeInbox: String(r.RemoveFromInbox || '').toUpperCase() === 'TRUE',\n  }));\n\nreturn items.map(it => {\n  const sender = fromEmail(it.json._fromEmail || it.json.From);\n  const hit = rules.find(r => sender.includes(r.pattern));\n\n  it.json.__rule = hit || null;\n\n  // For downstream switches:\n  if (!hit) {\n    it.json.switchLable = 'extra';\n  } else if (hit.action === 'LABEL') {\n    it.json.switchLable = hit.labelName || 'extra';\n    it.json.labelId = hit.labelId || null; // if provided in sheet\n  } else if (hit.action === 'PROMO') {\n    it.json.switchLable = 'PROMO';\n  } else if (hit.action === 'DELETE') {\n    it.json.switchLable = 'DELETE';\n  }\n\n  return it;\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "09790520-8c41-49d9-a818-1cc3e658b30c",
      "name": "Map Label Name",
      "type": "n8n-nodes-base.code",
      "position": [
        -400,
        184
      ],
      "parameters": {
        "jsCode": "// Build name \u2192 id map from Gmail Labels node\nconst labels = $items('Gmail Labels', 0).map(i => i.json);\nconst map = Object.fromEntries(\n  labels.filter(l => l && l.name && l.id)\n        .map(l => [String(l.name).trim(), l.id])\n);\n\nreturn items.map(item => {\n  const key = String(item.json.switchLable || '').trim();\n\n  // Only look up when we don't already have an id and key is a real label name\n  if (!item.json.labelId && key && key !== 'PROMO' && key !== 'DELETE' && key !== 'extra') {\n    item.json.labelId = map[key] || null;\n  }\n  return item;\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "189627a3-e7c6-4835-ab1a-801a68fb74e1",
      "name": "Completed Notification",
      "type": "n8n-nodes-base.slack",
      "position": [
        -1376,
        416
      ],
      "parameters": {
        "text": "=\u2705 Email Organization completed",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "C099YS0V3M2"
        },
        "otherOptions": {}
      },
      "credentials": {
        "slackApi": {
          "name": "<your credential>"
        }
      },
      "executeOnce": true,
      "typeVersion": 2.2
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "fd2cbb63-08c6-4841-aa0d-ee5c085b40a6",
  "connections": {
    "Merge": {
      "main": [
        [
          {
            "node": "Map Label Name",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge1": {
      "main": [
        [
          {
            "node": "Apply Sheet Rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add Label": {
      "main": [
        [
          {
            "node": "Remove From Inbox",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Promotional": {
      "main": [
        [
          {
            "node": "Remove From Inbox",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sheet Rules": {
      "main": [
        [
          {
            "node": "Merge1",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Gmail Labels": {
      "main": [
        [
          {
            "node": "Merge",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Mark as read": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Map Label Name": {
      "main": [
        [
          {
            "node": "is Label Exist?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [
          {
            "node": "Completed Notification",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Is marketing/automated email?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "is Label Exist?": {
      "main": [
        [
          {
            "node": "Add Label",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Get many messages",
            "type": "main",
            "index": 0
          },
          {
            "node": "Gmail Labels",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply Sheet Rules": {
      "main": [
        [
          {
            "node": "Merge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get many messages": {
      "main": [
        [
          {
            "node": "Parse Sender Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Remove From Inbox": {
      "main": [
        [
          {
            "node": "Mark as read",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Sender Email": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is marketing/automated email?": {
      "main": [
        [
          {
            "node": "Promotional",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Sheet Rules",
            "type": "main",
            "index": 0
          },
          {
            "node": "Merge1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}