{
  "name": "Mimecast",
  "nodes": [
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "b0ed986b-a3e4-45d1-bd41-b1115a39d5ee",
              "name": "CLIENT_ID",
              "value": "dJi50wqLNyuQATspgS1i2bauMGT8yNNsbgmEO9sFIeQPsYGS",
              "type": "string"
            },
            {
              "id": "b3aba2f2-25e7-475f-bbde-bc3bb09403b1",
              "name": "CLIENT_SECRET",
              "value": "8R1Kz6D7KzlVEkfLnKfmpW8A5OfFGPOmOOKey1MAWNyyGTuWYQBS4abA5UQkQi8M",
              "type": "string"
            },
            {
              "id": "0ebe27ad-92d1-4fa4-849e-d2be12d59aa3",
              "name": "SENDER_EMAIL",
              "value": "= {{ $json.FromEmail }}",
              "type": "string"
            },
            {
              "id": "2ba4ceba-a3a2-45a5-9654-1c9f432c1253",
              "name": "RECIPIENT_EMAIL",
              "value": "={{ $json.ToEmail }}",
              "type": "string"
            },
            {
              "id": "bc048c3b-3b4e-40d2-a762-1d8b68bf0437",
              "name": "MIMECAST_BASE_URL",
              "value": " https://api.services.mimecast.com",
              "type": "string"
            },
            {
              "id": "fef1b6f6-6017-4f05-b6a7-815be8d06fe0",
              "name": "CLIENT_ACCOUNT_CODE",
              "value": "={{ $json.MimecastID }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "6369f504-c5c5-4294-b208-aba953e5a824",
      "name": "Configuration",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.3,
      "position": [
        -2016,
        448
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "condition_1",
              "leftValue": "={{ $json.totalEmailsFound }}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "d440f18b-f90b-4cc4-a293-28a51e8c091a",
      "name": "Check if Messages Found",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        -1184,
        448
      ]
    },
    {
      "parameters": {
        "jsCode": "return {\n  message: \"No messages found matching the search criteria\",\n  searchCriteria: {\n    sender: $('When Executed by Another Workflow').first().json.FromEmail,\n    recipient: $('When Executed by Another Workflow').first().json.ToEmail,\n    dateRange: {\n      start: $('When Executed by Another Workflow').first().json.StartDate,\n      end: $('When Executed by Another Workflow').first().json.EndDate\n    }\n  },\n  rawResponse: $('Process Response').first().json.rawResponse\n};"
      },
      "id": "b0e1cfd7-f1d3-4495-9acf-78879ec39846",
      "name": "No Results Found",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -816,
        528
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.services.mimecast.com/api/message-finder/search",
        "authentication": "genericCredentialType",
        "genericAuthType": "oAuth2Api",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json"
            },
            {
              "name": "x-mc-account",
              "value": "={{ $('Configuration').item.json.CLIENT_ACCOUNT_CODE }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"data\": [\n    {\n      \"accountCode\": \"{{ $('Configuration').item.json.CLIENT_ACCOUNT_CODE }}\",\n      \"advancedTrackAndTraceOptions\": {\n        \"from\": \"{{ $('Configuration').item.json.SENDER_EMAIL }}\",\n        \"to\": \"{{ $('When Executed by Another Workflow').item.json.ToEmail }}\"\n      }\n    }\n  ]\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -1824,
        448
      ],
      "id": "92ce6c4f-252b-4721-876c-da1d26529910",
      "name": "Search Messages",
      "credentials": {
        "oAuth2Api": {
          "id": "YYGu7rvvywEabDQZ",
          "name": "Mimecast Partner"
        }
      }
    },
    {
      "parameters": {
        "workflowInputs": {
          "values": [
            {
              "name": "FromEmail"
            },
            {
              "name": "SentDate",
              "type": "any"
            },
            {
              "name": "ToEmail"
            },
            {
              "name": "MimecastID"
            },
            {
              "name": "StartDate",
              "type": "any"
            },
            {
              "name": "EndDate"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1.1,
      "position": [
        -2176,
        448
      ],
      "id": "16449462-1667-4876-9dae-671121a3b8ed",
      "name": "When Executed by Another Workflow"
    },
    {
      "parameters": {
        "jsCode": "// Fixed Mimecast results summary based on actual structure\nconst input = $input.all();\nlet allEmails = [];\n\nconsole.log('Processing input items:', input.length);\n\n// Process each input item\nfor (const item of input) {\n  console.log('Processing item:', JSON.stringify(item, null, 2));\n  \n  // Check if item has json property and process accordingly\n  if (item.json) {\n    // Handle direct structure: item.json = { meta: {...}, data: [...], fail: [...] }\n    if (item.json.data && Array.isArray(item.json.data)) {\n      console.log('Found data array in item.json');\n      for (const dataItem of item.json.data) {\n        if (dataItem.trackedEmails && Array.isArray(dataItem.trackedEmails)) {\n          console.log('Found trackedEmails:', dataItem.trackedEmails.length);\n          allEmails = allEmails.concat(dataItem.trackedEmails);\n        }\n      }\n    }\n    // Handle array structure: item.json = [{ meta: {...}, data: [...], fail: [...] }, ...]\n    else if (Array.isArray(item.json)) {\n      console.log('item.json is an array');\n      for (const result of item.json) {\n        if (result.data && Array.isArray(result.data)) {\n          console.log('Found data array in array item');\n          for (const dataItem of result.data) {\n            if (dataItem.trackedEmails && Array.isArray(dataItem.trackedEmails)) {\n              console.log('Found trackedEmails:', dataItem.trackedEmails.length);\n              allEmails = allEmails.concat(dataItem.trackedEmails);\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nconsole.log('Total emails found (before deduplication):', allEmails.length);\n\n// Deduplicate emails based on their ID (which should be unique)\nconst uniqueEmails = allEmails.filter((email, index, self) => \n  index === self.findIndex(e => e.id === email.id)\n);\n\nconsole.log('Total emails found (after deduplication):', uniqueEmails.length);\nconsole.log('Unique emails:', JSON.stringify(uniqueEmails, null, 2));\n\nconst totalEmailsFound = uniqueEmails.length;\nconst uniqueRecipients = [...new Set(uniqueEmails.flatMap(email => \n  email.to ? email.to.map(recipient => recipient.emailAddress) : []\n))].filter(Boolean);\n\nconsole.log('Unique recipients:', uniqueRecipients);\n\nreturn [{\n  json: {\n    totalEmailsFound: totalEmailsFound,\n    uniqueRecipientsCount: uniqueRecipients.length,\n    uniqueRecipients: uniqueRecipients,\n    summary: `Total emails found: ${totalEmailsFound}, Unique recipients: ${uniqueRecipients.length}`,\n    debug: {\n      inputStructure: input.map(item => ({\n        hasJson: !!item.json,\n        jsonType: typeof item.json,\n        isJsonArray: Array.isArray(item.json)\n      }))\n    }\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -1600,
        448
      ],
      "id": "c9734388-35fc-4b1f-8a00-2d3d7dfcc32d",
      "name": "Results Summary"
    },
    {
      "parameters": {
        "jsCode": "// Create formatted HTML summary for Mimecast results\nconst resultsData = $('Results Summary').first().json;\nconst configData = $('Configuration').first().json;\nconst workflowData = $('When Executed by Another Workflow').first().json;\n\n// Extract domain from ToEmail input (remove leading spaces)\nlet domain = workflowData.ToEmail ? workflowData.ToEmail.trim() : 'Unknown Domain';\n\n// Calculate lookback days from date range\nconst startDate = new Date(workflowData.StartDate);\nconst endDate = new Date(workflowData.EndDate);\nconst lookbackDays = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24));\n\nconst totalEmails = resultsData.totalEmailsFound;\nconst recipients = resultsData.uniqueRecipients;\n\n// Create the formatted text summary\nlet summary = `Your domain: ${domain}\\n`;\nsummary += `Received: ${totalEmails} message${totalEmails !== 1 ? 's' : ''} over the last ${lookbackDays} days\\n\\n`;\n\nif (recipients.length > 0) {\n  summary += `To the following recipients:\\n\\n`;\n  \n  // Create a nice table\n  summary += `┌─────┬──────────────────────────────────────────┐\\n`;\n  summary += `│ #   │ Recipient Email Address                  │\\n`;\n  summary += `├─────┼──────────────────────────────────────────┤\\n`;\n  \n  recipients.forEach((recipient, index) => {\n    const num = String(index + 1).padStart(3, ' ');\n    const email = recipient.padEnd(40, ' ').substring(0, 40);\n    summary += `│ ${num} │ ${email} │\\n`;\n  });\n  \n  summary += `└─────┴──────────────────────────────────────────┘\\n`;\n} else {\n  summary += `No recipients found.\\n`;\n}\n\n// Create HTML version for Autotask ticket notes\nlet htmlSummary = `<div style=\"font-family: Arial, sans-serif; margin: 10px 0;\">`;\nhtmlSummary += `<h3 style=\"color: #2c5aa0; margin-bottom: 10px;\">📧 Mimecast Historical Analysis</h3>`;\nhtmlSummary += `<p><strong>Domain:</strong> ${domain}</p>`;\nhtmlSummary += `<p><strong>Messages Found:</strong> ${totalEmails} message${totalEmails !== 1 ? 's' : ''} over the last ${lookbackDays} days</p>`;\n\nif (recipients.length > 0) {\n  htmlSummary += `<h4 style=\"color: #2c5aa0; margin: 15px 0 10px 0;\">Recipients:</h4>`;\n  htmlSummary += `<table style=\"border-collapse: collapse; width: 100%; max-width: 500px;\">`;\n  htmlSummary += `<thead>`;\n  htmlSummary += `<tr style=\"background-color: #f8f9fa;\">`;\n  htmlSummary += `<th style=\"border: 1px solid #dee2e6; padding: 8px; text-align: left; width: 50px;\">#</th>`;\n  htmlSummary += `<th style=\"border: 1px solid #dee2e6; padding: 8px; text-align: left;\">Email Address</th>`;\n  htmlSummary += `</tr>`;\n  htmlSummary += `</thead>`;\n  htmlSummary += `<tbody>`;\n  \n  recipients.forEach((recipient, index) => {\n    const bgColor = index % 2 === 0 ? '#ffffff' : '#f8f9fa';\n    htmlSummary += `<tr style=\"background-color: ${bgColor};\">`;\n    htmlSummary += `<td style=\"border: 1px solid #dee2e6; padding: 8px;\">${index + 1}</td>`;\n    htmlSummary += `<td style=\"border: 1px solid #dee2e6; padding: 8px; font-family: monospace;\">${recipient}</td>`;\n    htmlSummary += `</tr>`;\n  });\n  \n  htmlSummary += `</tbody>`;\n  htmlSummary += `</table>`;\n} else {\n  htmlSummary += `<p style=\"color: #6c757d; font-style: italic;\">No recipients found in the search period.</p>`;\n}\n\nhtmlSummary += `</div>`;\n\n// Also create a plain text version for Autotask (since API doesn't render HTML)\nlet autotaskSummary = `📧 MIMECAST HISTORICAL ANALYSIS\\n`;\nautotaskSummary += `${'='.repeat(50)}\\n\\n`;\nautotaskSummary += `Domain: ${domain}\\n`;\nautotaskSummary += `Messages Found: ${totalEmails} message${totalEmails !== 1 ? 's' : ''} over the last ${lookbackDays} days\\n\\n`;\n\nif (recipients.length > 0) {\n  autotaskSummary += `RECIPIENTS:\\n`;\n  autotaskSummary += `${'-'.repeat(40)}\\n`;\n  recipients.forEach((recipient, index) => {\n    autotaskSummary += `${(index + 1).toString().padStart(2, ' ')}. ${recipient}\\n`;\n  });\n} else {\n  autotaskSummary += `No recipients found in the search period.\\n`;\n}\n\nautotaskSummary += `\\n${'='.repeat(50)}\\n`;\n\n// Create a Telegram-friendly markdown version with icons\nlet telegramSummary = `🏢 *Domain:* ${domain}\\n`;\ntelegramSummary += `📊 *Messages Found:* ${totalEmails} message${totalEmails !== 1 ? 's' : ''} over the last ${lookbackDays} days\\n\\n`;\n\nif (recipients.length > 0) {\n  telegramSummary += `👥 *Recipients:*\\n`;\n  const displayRecipients = recipients.slice(0, 10);\n  displayRecipients.forEach((recipient) => {\n    telegramSummary += `- \\`${recipient}\\`\\n`;\n  });\n  if (recipients.length > 10) {\n    telegramSummary += `- ...${recipients.length - 10} more\\n`;\n  }\n} else {\n  telegramSummary += `ℹ️ *No recipients found* in the search period\\n`;\n}\n\nreturn [{\n  json: {\n    formattedSummary: summary,\n    htmlSummary: htmlSummary,\n    autotaskSummary: autotaskSummary,\n    telegramSummary: telegramSummary,\n    domain: domain,\n    totalEmails: totalEmails,\n    lookbackDays: lookbackDays,\n    recipients: recipients,\n    recipientCount: recipients.length,\n    searchCriteria: {\n      sender: configData.SENDER_EMAIL,\n      recipient: configData.RECIPIENT_EMAIL,\n      dateRange: {\n        start: workflowData.StartDate,\n        end: workflowData.EndDate\n      }\n    }\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -816,
        352
      ],
      "id": "153352c0-6718-4b6c-8146-ae3bef211d14",
      "name": "HTML Summary"
    }
  ],
  "pinData": {
    "When Executed by Another Workflow": [
      {
        "json": {
          "FromEmail": "do_not_reply@amazonrobotics.coupahost.com",
          "SentDate": "2025-06-20T16:09:07Z",
          "ToEmail": "hynesind.com",
          "MimecastID": "CUSA95A555",
          "StartDate": "2025-06-13T00:00Z",
          "EndDate": "2025-06-20T23:59:59Z"
        }
      }
    ]
  },
  "connections": {
    "Configuration": {
      "main": [
        [
          {
            "node": "Search Messages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check if Messages Found": {
      "main": [
        [
          {
            "node": "HTML Summary",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "No Results Found",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search Messages": {
      "main": [
        [
          {
            "node": "Results Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When Executed by Another Workflow": {
      "main": [
        [
          {
            "node": "Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Results Summary": {
      "main": [
        [
          {
            "node": "Check if Messages Found",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "ffbbf23a-d770-4574-81cf-b7c904916791",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "ad3e8921b8f3ec5eb0f5de9993c5671acfe1653760ce28a0ae49df7ec32eb653"
  },
  "id": "48xkYTiggtdMvPAN",
  "tags": []
}