{ "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 = `
Domain: ${domain}
`;\nhtmlSummary += `Messages Found: ${totalEmails} message${totalEmails !== 1 ? 's' : ''} over the last ${lookbackDays} days
`;\n\nif (recipients.length > 0) {\n htmlSummary += `| # | `;\n htmlSummary += `Email Address | `;\n htmlSummary += `
|---|---|
| ${index + 1} | `;\n htmlSummary += `${recipient} | `;\n htmlSummary += `
No recipients found in the search period.
`;\n}\n\nhtmlSummary += `