{
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "188b3582-4c1f-4db2-9015-6f0c74d061e8",
      "name": "Run Node With Credentials X",
      "type": "n8n-nodes-run-node-with-credentials-x.runNodeWithCredentialsX",
      "position": [
        1088,
        320
      ],
      "parameters": {
        "nodeJson": "={\n  \"nodes\": [\n    {\n      \"parameters\": {\n        \"operation\": \"getAll\",\n        \"returnAll\": true,\n        \"simple\": false,\n        \"filters\": {\n          \"q\": \"after:{{ $json.item.after}} before:{{ $json.item.before }} -from:(*@getkhatriautomations.com OR *@thekhatriautomations.com OR *@heykhatriautomations.com)\"\n        },\n        \"options\": {}\n      },\n      \"type\": \"n8n-nodes-base.gmail\",\n      \"typeVersion\": 2.1,\n      \"position\": [\n        256,\n        224\n      ],\n      \"id\": \"bdb5a5de-e1f1-4385-8090-5d7dda99b2fd\",\n      \"name\": \"Get many messages\",\n      \"webhookId\": \"ca9579ad-c210-486c-90ee-0655e002fb3e\",\n      \"credentials\": {\n        \"gmailOAuth2\": {\n          \"id\": \"07zKhV0K7a3wXEZp\",\n          \"name\": \"jatin@get\"\n        }\n      }\n    }\n  ],\n  \"connections\": {},\n  \"pinData\": {},\n  \"meta\": {\n    \"templateCredsSetupCompleted\": true,\n    \"instanceId\": \"f5d0c13b222abccfa4b21baa9b6cd543e62d86b4c7c9b6917990da9dc767ae69\"\n  }\n}",
        "runPerItem": true,
        "credentialsId": "={{ $json.item.cred_id }}"
      },
      "typeVersion": 1,
      "alwaysOutputData": true
    },
    {
      "id": "4c0e6519-d20b-450c-8d10-6769eb3f7b13",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        64,
        320
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours"
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "67ba019f-85d7-4e32-9d2d-75b325db3d47",
      "name": "Code in JavaScript",
      "type": "n8n-nodes-base.code",
      "position": [
        800,
        320
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "let last_polled = $json.last_polled;\n\nconst last_poll = Math.floor(new Date(last_polled).getTime() / 1000); // epoch seconds\nconst now = Math.floor(Date.now() / 1000); // epoch seconds\n\nlet item = $json\nitem.after = last_poll\nitem.before = now\n\nreturn {item}"
      },
      "typeVersion": 2
    },
    {
      "id": "f19e61bd-356a-436c-b2bc-17d1e9a1d3c3",
      "name": "upsert emails",
      "type": "n8n-nodes-base.dataTable",
      "position": [
        1968,
        304
      ],
      "parameters": {
        "columns": {
          "value": {
            "email_data": "={{ $('Email Normalization').item.json.email }}",
            "message_id": "={{ $('Run Node With Credentials X').item.json.id }}"
          },
          "schema": [
            {
              "id": "message_id",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "message_id",
              "defaultMatch": false
            },
            {
              "id": "email_data",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "email_data",
              "defaultMatch": false
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "email_data"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "filters": {
          "conditions": [
            {
              "keyName": "message_id",
              "keyValue": "={{ $('Run Node With Credentials X').item.json.id }}"
            }
          ]
        },
        "options": {},
        "operation": "upsert",
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "6JmuKkOPzk4ryea9",
          "cachedResultUrl": "/projects/gWyT6ct8nsEBW0XK/datatables/6JmuKkOPzk4ryea9",
          "cachedResultName": "All Emails"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "fc88372d-71a7-4a71-b772-91b526129f67",
      "name": "Update last_polled",
      "type": "n8n-nodes-base.dataTable",
      "position": [
        1760,
        304
      ],
      "parameters": {
        "columns": {
          "value": {
            "last_polled": "={{ $now }}",
            "warmup_enabled": false
          },
          "schema": [
            {
              "id": "cred_id",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "cred_id",
              "defaultMatch": false
            },
            {
              "id": "email",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "email",
              "defaultMatch": false
            },
            {
              "id": "credentials_name",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "credentials_name",
              "defaultMatch": false
            },
            {
              "id": "daily_limit",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "daily_limit",
              "defaultMatch": false
            },
            {
              "id": "sent_today",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "sent_today",
              "defaultMatch": false
            },
            {
              "id": "last_sent_at",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "last_sent_at",
              "defaultMatch": false
            },
            {
              "id": "last_history_id",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "last_history_id",
              "defaultMatch": false
            },
            {
              "id": "warmup_enabled",
              "type": "boolean",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "warmup_enabled",
              "defaultMatch": false
            },
            {
              "id": "warmup_sent_today",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "warmup_sent_today",
              "defaultMatch": false
            },
            {
              "id": "warmup_target_today",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "warmup_target_today",
              "defaultMatch": false
            },
            {
              "id": "last_polled",
              "type": "dateTime",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "last_polled",
              "defaultMatch": false
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "filters": {
          "conditions": [
            {
              "keyValue": "={{ $('Loop Over Items').item.json.id }}"
            }
          ]
        },
        "options": {},
        "operation": "update",
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "mqNBBTqxgRm7R9v0",
          "cachedResultUrl": "/projects/gWyT6ct8nsEBW0XK/datatables/mqNBBTqxgRm7R9v0",
          "cachedResultName": "cold_email_accounts"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "0031fcaa-5aea-4476-8572-dded88512cc3",
      "name": "Update last_polled1",
      "type": "n8n-nodes-base.dataTable",
      "position": [
        1760,
        464
      ],
      "parameters": {
        "columns": {
          "value": {
            "last_polled": "={{ $now }}",
            "warmup_enabled": false
          },
          "schema": [
            {
              "id": "cred_id",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "cred_id",
              "defaultMatch": false
            },
            {
              "id": "email",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "email",
              "defaultMatch": false
            },
            {
              "id": "credentials_name",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "credentials_name",
              "defaultMatch": false
            },
            {
              "id": "daily_limit",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "daily_limit",
              "defaultMatch": false
            },
            {
              "id": "sent_today",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "sent_today",
              "defaultMatch": false
            },
            {
              "id": "last_sent_at",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "last_sent_at",
              "defaultMatch": false
            },
            {
              "id": "last_history_id",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "last_history_id",
              "defaultMatch": false
            },
            {
              "id": "warmup_enabled",
              "type": "boolean",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "warmup_enabled",
              "defaultMatch": false
            },
            {
              "id": "warmup_sent_today",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "warmup_sent_today",
              "defaultMatch": false
            },
            {
              "id": "warmup_target_today",
              "type": "string",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "warmup_target_today",
              "defaultMatch": false
            },
            {
              "id": "last_polled",
              "type": "dateTime",
              "display": true,
              "removed": false,
              "readOnly": false,
              "required": false,
              "displayName": "last_polled",
              "defaultMatch": false
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "filters": {
          "conditions": [
            {
              "keyValue": "={{ $('Loop Over Items').item.json.id }}"
            }
          ]
        },
        "options": {},
        "operation": "update",
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "mqNBBTqxgRm7R9v0",
          "cachedResultUrl": "/projects/gWyT6ct8nsEBW0XK/datatables/mqNBBTqxgRm7R9v0",
          "cachedResultName": "cold_email_accounts"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "3b84eb3a-62f1-4310-924e-2e0388a908bb",
      "name": "Loop Over Items",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        512,
        320
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "0bbedf6e-af59-4995-95c1-7eaef3712f2e",
      "name": "Edit Fields",
      "type": "n8n-nodes-base.set",
      "position": [
        1232,
        -64
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "620286d3-a5d9-42a2-9481-8a049a3392de",
              "name": "emailCount",
              "type": "string",
              "value": "={{ $input.all().length }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "df4bff3c-cdaa-473c-b4c5-dd3bdac234c4",
      "name": "Send a message",
      "type": "n8n-nodes-base.discord",
      "position": [
        1664,
        -64
      ],
      "parameters": {
        "content": "={{ $json.emailCount }} new emails arrived",
        "guildId": {
          "__rl": true,
          "mode": "list",
          "value": "1218618818264436817",
          "cachedResultUrl": "https://discord.com/channels/1218618818264436817",
          "cachedResultName": "jatinkhatri0001's server"
        },
        "options": {},
        "resource": "message",
        "channelId": {
          "__rl": true,
          "mode": "list",
          "value": "1448406301389619340",
          "cachedResultUrl": "https://discord.com/channels/1218618818264436817/1448406301389619340",
          "cachedResultName": "n8n_workflows"
        }
      },
      "credentials": {
        "discordBotApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2
    },
    {
      "id": "fb78da17-8af9-41b2-8ead-e7c7df840d1c",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        32,
        -496
      ],
      "parameters": {
        "width": 592,
        "height": 640,
        "content": "### How It Works (node-by-node):\n\n1. Schedule Trigger fires every hour (or your preferred interval).\n\n2. Fetch all email account rows from the cold_email_accounts table.\n\n3. Split In Batches loops through each account one by one.\n\n4. Calculate poll window in a Code node (after = last_polled, before = now)\n\n5. Run Node With Credentials X:\nInjects that account\u2019s Gmail OAuth2 credential\nExecutes Gmail \u2192 Get Many Messages\nUses filtered query:\nafter:<timestamp> before:<timestamp>\n\n6. If messages exist: Format + clean them through a Code node\n\n7. Save to All Emails table\n\n8. Update last_polled\n\n8. If no messages: Skip saving\n\n9. Only update last_polled\n\n10. Once the loop finishes:\n\n11. Check how many rows were inserted into the All Emails table during this run\n\n12. Send a Discord message summarizing the count (ex: \u201c15 new emails arrived\u201d)."
      },
      "typeVersion": 1
    },
    {
      "id": "97c9e764-66c0-4936-8df8-f74ccdc99c26",
      "name": "Limit",
      "type": "n8n-nodes-base.limit",
      "position": [
        1440,
        -64
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "e7bf6c35-2b03-4742-b3d0-57f8c4265910",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        16,
        208
      ],
      "parameters": {
        "color": 7,
        "width": 656,
        "height": 256,
        "content": "## Get Email Accounts\nLoads all email accounts to be polled."
      },
      "typeVersion": 1
    },
    {
      "id": "55a2d33c-6457-4db2-8dbd-a84902faa9ca",
      "name": "Get All Email Accounts",
      "type": "n8n-nodes-base.dataTable",
      "position": [
        288,
        320
      ],
      "parameters": {
        "operation": "get",
        "returnAll": true,
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "mqNBBTqxgRm7R9v0",
          "cachedResultUrl": "/projects/gWyT6ct8nsEBW0XK/datatables/mqNBBTqxgRm7R9v0",
          "cachedResultName": "cold_email_accounts"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "53c05718-b21b-4f67-9b7e-9e371bfdf4bd",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        704,
        208
      ],
      "parameters": {
        "color": 7,
        "width": 288,
        "height": 256,
        "content": "## Polling Time Calculator\nCalculates the polling time range in Epoch."
      },
      "typeVersion": 1
    },
    {
      "id": "51e7a928-d244-458e-955a-291c9a25f05c",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1024,
        208
      ],
      "parameters": {
        "color": 7,
        "width": 640,
        "height": 256,
        "content": "## Get Gmail Messages Dynamically\nRuns Gmail nodes dynamically using OAuth credentials from the data table."
      },
      "typeVersion": 1
    },
    {
      "id": "da3085bb-3404-4e33-a266-e6f524399d50",
      "name": "Email Normalization",
      "type": "n8n-nodes-base.code",
      "position": [
        1504,
        304
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const itemData = $json;\nconst fromValue = itemData.from?.value?.[0] || {};\n\nconst attachments = [];\nconst parts = itemData.payload?.parts || [];\nfor (const part of parts) {\n  if (part.filename) {\n    attachments.push({\n      name: part.filename,\n      size: part.body?.size || null,\n      type: part.mimeType || \"unknown\"\n    });\n  }\n}\n\nlet email = {\n  id: itemData.id,\n  threadId: itemData.threadId,\n  account: itemData.account,\n\n  from: {\n    name: fromValue.name || \"Unknown\",\n    email: fromValue.address || \"unknown\",\n    avatar: null\n  },\n\n  to: itemData.to?.text || itemData.to?.value?.[0]?.address || \"\",\n\n  subject: itemData.subject || \"(no subject)\",\n  preview: (itemData.text || \"\").slice(0, 150),\n\n  body_html: itemData.html || itemData.textAsHtml || \"\",\n  body_text: itemData.text || \"\",\n\n  date: itemData.date,\n\n  labels: itemData.labelIds || [],\n\n  attachments,\n\n  isRead: !(itemData.labelIds || []).includes(\"UNREAD\"),\n  isStarred: false\n};\n\n  email = JSON.stringify(email)\n  return {email}\n\n// return $input.all();"
      },
      "typeVersion": 2
    },
    {
      "id": "f7e73855-d33a-4662-ba56-f8862aa747a1",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1696,
        144
      ],
      "parameters": {
        "color": 7,
        "width": 448,
        "height": 544,
        "content": "## Add to Data Tables\nUpserts new emails into the All Emails table and avoids duplicates.\nUpdates last_polled for the current email account after processing."
      },
      "typeVersion": 1
    },
    {
      "id": "b2b0cebb-89f3-4695-b85e-5d3d8f4ad80f",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        752,
        -160
      ],
      "parameters": {
        "color": 7,
        "width": 1104,
        "height": 256,
        "content": "## Send Notification on Discord Channel\nSends a summary message with the number of newly received emails."
      },
      "typeVersion": 1
    },
    {
      "id": "9e1681dd-0181-4e9a-86e7-e268a80116c7",
      "name": "Get new emails if any",
      "type": "n8n-nodes-base.dataTable",
      "position": [
        784,
        -48
      ],
      "parameters": {
        "filters": {
          "conditions": [
            {
              "keyName": "message_id",
              "keyValue": "={{ $json.message_id }}"
            }
          ]
        },
        "operation": "get",
        "returnAll": true,
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "6JmuKkOPzk4ryea9",
          "cachedResultUrl": "/projects/gWyT6ct8nsEBW0XK/datatables/6JmuKkOPzk4ryea9",
          "cachedResultName": "All Emails"
        }
      },
      "typeVersion": 1,
      "alwaysOutputData": true
    },
    {
      "id": "d4ed6f2f-555b-44a8-abaf-ef547848f944",
      "name": "If new email found",
      "type": "n8n-nodes-base.if",
      "position": [
        1280,
        320
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "05a13bd7-b7fe-4beb-8d44-9fdf7aa99214",
              "operator": {
                "type": "object",
                "operation": "notEmpty",
                "singleValue": true
              },
              "leftValue": "={{ $json }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "f8e45d30-c99d-4712-8233-627d8e9ca565",
      "name": "If new email found1",
      "type": "n8n-nodes-base.if",
      "position": [
        1008,
        -48
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "5b6725fa-a021-434d-90e8-6da448b8b844",
              "operator": {
                "type": "object",
                "operation": "notEmpty",
                "singleValue": true
              },
              "leftValue": "={{ $json }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    }
  ],
  "connections": {
    "Limit": {
      "main": [
        [
          {
            "node": "Send a message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Edit Fields": {
      "main": [
        [
          {
            "node": "Limit",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "upsert emails": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [
          {
            "node": "Get new emails if any",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Code in JavaScript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Get All Email Accounts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code in JavaScript": {
      "main": [
        [
          {
            "node": "Run Node With Credentials X",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If new email found": {
      "main": [
        [
          {
            "node": "Email Normalization",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Update last_polled1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update last_polled": {
      "main": [
        [
          {
            "node": "upsert emails",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email Normalization": {
      "main": [
        [
          {
            "node": "Update last_polled",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If new email found1": {
      "main": [
        [
          {
            "node": "Edit Fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update last_polled1": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get new emails if any": {
      "main": [
        [
          {
            "node": "If new email found1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get All Email Accounts": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run Node With Credentials X": {
      "main": [
        [
          {
            "node": "If new email found",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}