{
  "id": "5vu0NifxPdAhR0hK",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Email Agent with AI Analysis",
  "tags": [],
  "nodes": [
    {
      "id": "484fdb46-d4aa-474c-ada7-23325c27494a",
      "name": "Process Email Data",
      "type": "n8n-nodes-base.code",
      "position": [
        -672,
        -48
      ],
      "parameters": {
        "jsCode": "// Process email data from Gmail trigger\nconst items = [];\n\nfor (const item of $input.all()) {\n  const emailData = item.json;\n  \n  // --- Handle sender information ---\n  let senderEmail = '';\n  let senderName = '';\n\n  if (emailData.from?.value?.[0]) {\n    senderEmail = emailData.from.value[0].address || '';\n    senderName = emailData.from.value[0].name || senderEmail;\n  } else if (emailData.from?.text) {\n    const emailMatch = emailData.from.text.match(/<([^>]+)>/) || \n                      emailData.from.text.match(/([^\\s]+@[^\\s]+)/);\n    senderEmail = emailMatch ? emailMatch[1] : emailData.from.text;\n    \n    const nameMatch = emailData.from.text.match(/^([^<]+)/);\n    senderName = nameMatch ? nameMatch[1].trim().replace(/\\\"/g, '') : senderEmail;\n  }\n\n  // --- Format date ---\n  const receivedDate = new Date(emailData.date || emailData.receivedTime);\n  const formattedDate = receivedDate.toLocaleString('en-US', {\n    year: 'numeric',\n    month: '2-digit',\n    day: '2-digit',\n    hour: '2-digit',\n    minute: '2-digit',\n    hour12: true\n  });\n\n  // --- Extract content ---\n  let emailContent = '';\n  \n  // 1. Plain text version\n  if (emailData.text) {\n    emailContent = emailData.text;\n  } \n  // 2. HTML version\n  else if (emailData.html) {\n    emailContent = emailData.html\n      .replace(/<style[^>]*>.*?<\\/style>/gs, '')  // Remove CSS\n      .replace(/<[^>]*>/g, ' ')                   // Strip HTML tags\n      .replace(/\\s+/g, ' ')                       // Collapse whitespace\n      .trim();\n  }\n  // 3. Fallback\n  else if (emailData.body || emailData.textPlain || emailData.textHtml) {\n    emailContent = emailData.body || emailData.textPlain || emailData.textHtml;\n  }\n\n  // --- Truncate if too long ---\n  const maxContentLength = 5000;\n  if (emailContent.length > maxContentLength) {\n    emailContent = emailContent.substring(0, maxContentLength) + '... [truncated]';\n  }\n\n  // --- Create final data object ---\n  const rowData = {\n    messageId: emailData.id || emailData.messageId || '',\n    threadId: emailData.threadId || '',\n    Date: formattedDate,\n    'Sender Name': senderName,\n    'Sender Email': senderEmail,\n    Subject: emailData.subject || 'No Subject',\n    Content: emailContent,\n    'Has Attachments': emailData.attachments?.length > 0 ? 'Yes' : 'No'\n  };\n  \n  items.push({ json: rowData });\n}\n\nreturn items;\n"
      },
      "typeVersion": 2
    },
    {
      "id": "bc108b82-4b56-4f1b-a49d-47bfc08c1e58",
      "name": "AI Email Analyzer",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -288,
        -48
      ],
      "parameters": {
        "text": "=You are an intelligent email assistant. Analyze the following email and perform these tasks:\n\n1. Create a comprehensive summary of the email without removing any essential information\n2. Determine the most appropriate label category for this email from the following options:\n   - Work\n   - Personal\n   - Finance\n   - Marketing/Promotional\n   - Newsletter\n   - Important\n   - Follow-up Required\n   - Project Updates\n   - Meeting/Calendar\n   - Support/Customer Service\n   - Social\n   - Travel\n   - Bills/Invoices\n   - Spam\n\nIf none of these labels fit perfectly, suggest a new label that would be most appropriate.\n\nEmail Details:\nFrom: {{ $json['Sender Name'] }} ({{ $json['Sender Email'] }})\nSubject: {{ $json.Subject }}\nContent: {{ $json.Content }}\nHas Attachments: {{ $json['Has Attachments'] }}\n\nProvide your response in the following JSON format:\n{\n  \"summary\": \"detailed summary here\",\n  \"suggestedLabel\": \"label name\",\n  \"createNewLabel\": true/false,\n  \"priority\": \"high/medium/low\",\n  \"actionRequired\": true/false,\n  \"keyPoints\": [\"point1\", \"point2\"]\n}",
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "1c47f4e7-6d29-4842-8e59-c96bedeb12c9",
      "name": "Create Gmail Label",
      "type": "n8n-nodes-base.gmail",
      "onError": "continueRegularOutput",
      "position": [
        304,
        -48
      ],
      "parameters": {
        "name": "={{ $json.output.output.emailParserOutput.emailLabel }}",
        "options": {},
        "resource": "label",
        "operation": "create"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2,
      "continueOnFail": true
    },
    {
      "id": "70af1293-925b-4396-a36c-8236cbd7ddda",
      "name": "Add Label to Email",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1424,
        -48
      ],
      "parameters": {
        "labelIds": "={{ $json.output }}",
        "messageId": "={{ $('Process Email Data').item.json.messageId }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2
    },
    {
      "id": "1a9df30f-e473-4ebf-ade4-fda37891f79f",
      "name": "Structured Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        -208,
        224
      ],
      "parameters": {
        "jsonSchemaExample": "{\n  \"emailParserOutput\": {\n    \"messageId\": \"string - unique Gmail message ID\",\n    \"threadId\": \"string - Gmail thread ID this email belongs to\",\n    \"summary\": \"string - concise 1-2 sentence summary of the email content\",\n    \"emailLabel\": \"string - label or category to assign (e.g., 'Finance', 'Meetings', 'Support', 'Marketing', 'Personal', 'Recruitment', 'General')\"\n  }\n}\n"
      },
      "typeVersion": 1.3
    },
    {
      "id": "ce8d7ab7-32e5-4d96-839c-84ded9261110",
      "name": "Get Label",
      "type": "n8n-nodes-base.gmailTool",
      "position": [
        976,
        112
      ],
      "parameters": {
        "resource": "label",
        "returnAll": true
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "9ba1e386-a291-4672-9b55-4c6abe3ada00",
      "name": "Logs in Notion",
      "type": "n8n-nodes-base.notion",
      "position": [
        896,
        496
      ],
      "parameters": {
        "options": {},
        "resource": "databasePage",
        "databaseId": {
          "__rl": true,
          "mode": "list",
          "value": "4b672fe9-afc9-4da3-8a1b-1a35b1b61513",
          "cachedResultUrl": "https://www.notion.so/4b672fe9afc94da38a1b1a35b1b61513",
          "cachedResultName": "Email Summary Database"
        },
        "propertiesUi": {
          "propertyValues": [
            {
              "key": "Message ID|rich_text",
              "textContent": "={{ $('Process Email Data').item.json.messageId }}"
            },
            {
              "key": "Sender Name|rich_text",
              "textContent": "={{ $('Process Email Data').item.json['Sender Name'] }}"
            },
            {
              "key": "Sender Email|email",
              "emailValue": "={{ $('Process Email Data').item.json['Sender Email'] }}"
            },
            {
              "key": "Subject|title",
              "title": "={{ $('Process Email Data').item.json.Subject }}"
            },
            {
              "key": "Summary|rich_text",
              "textContent": "={{ $('AI Email Analyzer').item.json.output.output.emailParserOutput.summary }}"
            },
            {
              "key": "Date & Time|date",
              "date": "={{ $('Process Email Data').item.json.Date }}"
            },
            {
              "key": "Label|multi_select",
              "multiSelectValue": "={{ $('AI Email Analyzer').item.json.output.output.emailParserOutput.emailLabel }}"
            }
          ]
        }
      },
      "credentials": {
        "notionApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "2f65eb86-855b-468f-88dd-d91448fa50da",
      "name": "Logs in Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        720,
        496
      ],
      "parameters": {
        "columns": {
          "value": {
            "Date": "={{ $('Process Email Data').item.json.Date }}",
            "Label": "={{ $('AI Email Analyzer').item.json.output.output.emailParserOutput.emailLabel }}",
            "Subject": "={{ $('Process Email Data').item.json.Subject }}",
            "Summary": "={{ $('Process Email Data').item.json.Content }}",
            "Message ID": "={{ $('Process Email Data').item.json.messageId }}",
            "Sender Name": "={{ $('Process Email Data').item.json['Sender Name'] }}",
            "Sender Email": "={{ $('Process Email Data').item.json['Sender Email'] }}"
          },
          "schema": [
            {
              "id": "Message ID",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Message ID",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Sender Name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Sender Name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Sender Email",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Sender Email",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Subject",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Subject",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Summary",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Summary",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Label",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Label",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1Vf3_L3dDbwSwY9AAvnwBM08sBVxrYpgkFLPzamrqwRo/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1Vf3_L3dDbwSwY9AAvnwBM08sBVxrYpgkFLPzamrqwRo",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1Vf3_L3dDbwSwY9AAvnwBM08sBVxrYpgkFLPzamrqwRo/edit?usp=drivesdk",
          "cachedResultName": "Email Summary Sheet"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4
    },
    {
      "id": "3036c3ee-4d54-489b-b066-32d6ff0079d8",
      "name": "On new Email",
      "type": "n8n-nodes-base.gmailTrigger",
      "position": [
        -912,
        -48
      ],
      "parameters": {
        "simple": false,
        "filters": {
          "labelIds": [
            "INBOX"
          ]
        },
        "options": {
          "downloadAttachments": false
        },
        "pollTimes": {
          "item": [
            {
              "mode": "=everyHour",
              "minute": 59
            }
          ]
        }
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "01278d0b-76e7-42f1-b184-5ccfbd687856",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1008,
        -320
      ],
      "parameters": {
        "width": 560,
        "height": 432,
        "content": "# Gmail Trigger and Email Process\n\n## - Gmail Trigger Node \n- Triggers on every message (default).\n- You can change on how often it triggers (default 59 mins)\n\n## - Process Email Data\n- Takes out essential data from the email received"
      },
      "typeVersion": 1
    },
    {
      "id": "de26393b-c208-472f-920d-af5c60fc3932",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -128,
        432
      ],
      "parameters": {
        "color": 2,
        "width": 464,
        "height": 192,
        "content": "# AI Node\n## You can choose your\n## own favourite LLM"
      },
      "typeVersion": 1
    },
    {
      "id": "ce139c50-bc92-4636-9784-47a4cc57e4ee",
      "name": "Google Gemini Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        144,
        480
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "googlePalmApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "75410ce2-1276-4bfe-80c9-d093989a125d",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -384,
        -224
      ],
      "parameters": {
        "color": 5,
        "width": 448,
        "height": 336,
        "content": "# Email Ananlyzer\n\n### Analyzes the email received, summarizes the whole email and suggests the most specific label for the mail"
      },
      "typeVersion": 1
    },
    {
      "id": "9e64d00e-88da-4be1-9d06-614e12c70081",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        112,
        -320
      ],
      "parameters": {
        "color": 2,
        "width": 432,
        "height": 432,
        "content": "# Creates Label\n\n### Creates the label received by **AI Email Analyzer Node**\n\n### If label is already there, the workflow continues"
      },
      "typeVersion": 1
    },
    {
      "id": "21a103b8-b239-4000-bc12-a57df7b1a5ae",
      "name": "Label Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        784,
        -48
      ],
      "parameters": {
        "text": "=Your work is basicaly to give the \"Add Label - Gmail Node\" the correct label ID\n\nYour Work -:\n\n1. The Label which needs to attached will be given by {{ $('AI Email Analyzer').item.json.output.output.emailParserOutput.emailLabel }}\n2. After you get the label, you need to take out the correct label id from {{ $json.id }}\n3. You need to use the Get Label tool to get all the labels and use that tool to take the correct label and label id.\n4. After you get the label id, you just need to output that label id and NOTHING ELSE\n\n**OUTPUT** Only Label ID from {{ $json.id }}",
        "options": {},
        "promptType": "define"
      },
      "typeVersion": 2.2
    },
    {
      "id": "f52d7b64-1614-4653-ae46-5aef4a43aedf",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        672,
        -320
      ],
      "parameters": {
        "color": 6,
        "width": 464,
        "height": 576,
        "content": "# AI Label Assigner\n\n### Gets the label and forward the appropriate Label Code for the Email received"
      },
      "typeVersion": 1
    },
    {
      "id": "b3a4c0a0-26e8-419e-a1f9-4efcd650a54c",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1232,
        -192
      ],
      "parameters": {
        "color": 5,
        "width": 416,
        "height": 448,
        "content": "# Add the Label\n\n**NOTE:** Only add the **Label ID** or else the workflow will fail"
      },
      "typeVersion": 1
    },
    {
      "id": "1fc628e0-7447-4440-8d30-65633736705f",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        592,
        352
      ],
      "parameters": {
        "color": 4,
        "width": 576,
        "height": 304,
        "content": "# Logging the details in G-Sheet and Notion"
      },
      "typeVersion": 1
    }
  ],
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "a0199094-3c1f-4c24-be3e-fb812070041c",
  "connections": {
    "Get Label": {
      "ai_tool": [
        [
          {
            "node": "Label Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Label Agent": {
      "main": [
        [
          {
            "node": "Add Label to Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "On new Email": {
      "main": [
        [
          {
            "node": "Process Email Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Email Analyzer": {
      "main": [
        [
          {
            "node": "Create Gmail Label",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add Label to Email": {
      "main": [
        [
          {
            "node": "Logs in Google Sheets",
            "type": "main",
            "index": 0
          },
          {
            "node": "Logs in Notion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Gmail Label": {
      "main": [
        [
          {
            "node": "Label Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process Email Data": {
      "main": [
        [
          {
            "node": "AI Email Analyzer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Label Agent",
            "type": "ai_languageModel",
            "index": 0
          },
          {
            "node": "AI Email Analyzer",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "AI Email Analyzer",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    }
  }
}