This workflow corresponds to n8n.io template #17710 — we link there as the canonical source.
This workflow follows the Agent → Gmail recipe pattern — see all workflows that pair these two integrations.
The workflow JSON
Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →
{
"id": "",
"name": "Scan email folder and send AI digest for legal news",
"tags": [],
"nodes": [
{
"id": "2ef0f895-a4f1-46d4-a02b-683114781833",
"name": "Overview",
"type": "n8n-nodes-base.stickyNote",
"position": [
0,
0
],
"parameters": {
"color": 1,
"width": 360,
"height": 1156,
"content": "### Scan email folder and send AI digest for legal news\n\nMonitors an IMAP mailbox, uses AI to keep only emails about AI in the legal industry, researches each relevant topic with web search, and emails a branded HTML digest.\n\n### How it works\n1. **Schedule \u2014 Every 5 Hours** polls the inbox on a timer.\n2. **IMAP \u2014 Fetch Unread Emails** retrieves unread messages; **Set \u2014 Extract Email Fields** pulls subject, sender, date, body, UID.\n3. **OpenAI Agent \u2014 Score Relevance** classifies each email as legal-AI relevant or not (JSON), and the source email is deleted from the inbox.\n4. **Filter \u2014 Keep Relevant Only** and **Aggregate \u2014 Collect Topics** gather the matches; **IF \u2014 Has Topics** continues only when at least one is found.\n5. **OpenAI Agent \u2014 Research Topics** expands each topic using **Tavily \u2014 Web Search** and returns a Markdown report.\n6. **Code \u2014 Build HTML Email** converts the report to branded HTML and **Gmail \u2014 Send Digest** delivers it.\n\n### Setup\n1. Install the community nodes `n8n-nodes-imap` and `@tavily/n8n-nodes-tavily` (Settings \u2192 Community Nodes). Self-hosted n8n only.\n2. Add credentials: IMAP, OpenAI, Tavily, Gmail OAuth2.\n3. Set the recipient in the **Gmail \u2014 Send Digest** node.\n\n### Customization\n- Change the polling interval in the Schedule node.\n- Edit the topic list in **OpenAI Agent \u2014 Score Relevance** to target a different domain.\n- Point the IMAP node at a specific subfolder.\n\nSupport: support@legalgpts.com\nhttps://automatedintelligentsolutions.com"
},
"typeVersion": 1
},
{
"id": "a041d99c-50a5-49ff-951a-e792dd0f8398",
"name": "Community Node Warning",
"type": "n8n-nodes-base.stickyNote",
"position": [
384,
656
],
"parameters": {
"color": 3,
"width": 290,
"height": 200,
"content": "## \u26a0\ufe0f Community Nodes Required\nInstall both (self-hosted n8n only):\n\n**n8n-nodes-imap**\n**@tavily/n8n-nodes-tavily**\n\nSettings \u2192 Community Nodes \u2192 Install"
},
"typeVersion": 1
},
{
"id": "051012ea-f098-4011-9d57-0508069b6c19",
"name": "Section: Trigger & Extract",
"type": "n8n-nodes-base.stickyNote",
"position": [
368,
0
],
"parameters": {
"color": 7,
"width": 494,
"height": 624,
"content": "## Trigger & Extract\nPoll inbox on a timer; extract subject, sender, date, body, and UID."
},
"typeVersion": 1
},
{
"id": "046b9c47-a8d1-4de2-acac-e17e45ac6272",
"name": "Section: AI Relevance Filter",
"type": "n8n-nodes-base.stickyNote",
"position": [
880,
0
],
"parameters": {
"color": 7,
"width": 672,
"height": 304,
"content": "## AI Relevance Filter\nScore each email for legal-AI relevance; drop non-matches and delete the source email."
},
"typeVersion": 1
},
{
"id": "4e87347a-e81d-4aed-8806-fee6690dee14",
"name": "Section: Research & Send",
"type": "n8n-nodes-base.stickyNote",
"position": [
1728,
0
],
"parameters": {
"color": 7,
"width": 772,
"height": 304,
"content": "## Research & Send\nResearch each topic via web search, build a branded HTML email, and send the digest."
},
"typeVersion": 1
},
{
"id": "2d79a8e5-7842-44c6-9e19-179c0ad3fb64",
"name": "Schedule \u2014 Every 5 Hours",
"type": "n8n-nodes-base.scheduleTrigger",
"position": [
400,
128
],
"parameters": {
"rule": {
"interval": [
{
"field": "hours",
"hoursInterval": 5
}
]
}
},
"typeVersion": 1.2
},
{
"id": "d3c2d4ac-3751-445f-a37f-bcd09db6b177",
"name": "IMAP \u2014 Fetch Unread Emails",
"type": "n8n-nodes-imap.imap",
"position": [
560,
128
],
"parameters": {
"limit": 10,
"resource": "email",
"emailFlags": {
"seen": false
},
"mailboxPath": {
"__rl": true,
"mode": "list",
"value": "INBOX"
},
"authentication": "coreImapAccount",
"emailDateRange": {},
"emailSearchFilters": {}
},
"credentials": {
"imap": {
"name": "<your credential>"
}
},
"typeVersion": 1
},
{
"id": "d184a5fb-2970-475c-8be2-27db1863f2a5",
"name": "Set \u2014 Extract Email Fields",
"type": "n8n-nodes-base.set",
"position": [
720,
128
],
"parameters": {
"options": {},
"assignments": {
"assignments": [
{
"id": "email-uid",
"name": "emailUid",
"type": "string",
"value": "={{ $json.uid || $json.id || $json.messageId }}"
},
{
"id": "email-subject",
"name": "emailSubject",
"type": "string",
"value": "={{ $json.envelope.subject }}"
},
{
"id": "email-from",
"name": "emailFrom",
"type": "string",
"value": "={{ $json.envelope.from[0].name }}"
},
{
"id": "email-body",
"name": "emailBody",
"type": "string",
"value": "={{ $json.htmlContent }}"
},
{
"id": "email-date",
"name": "emailDate",
"type": "string",
"value": "={{ $json.envelope.date }}"
}
]
}
},
"typeVersion": 3.4
},
{
"id": "2dabdbe1-a338-4d1c-a959-cf857b1d878c",
"name": "OpenAI Agent \u2014 Score Relevance",
"type": "@n8n/n8n-nodes-langchain.agent",
"position": [
928,
128
],
"parameters": {
"text": "=Analyze this email and determine if it relates to AI in the legal industry.\n\n**EMAIL DETAILS:**\n- Subject: {{ $json.emailSubject }}\n- From: {{ $json.emailFrom }}\n- Date: {{ $json.emailDate }}\n- Content:\n{{ $json.emailBody }}\n\n**ANALYSIS INSTRUCTIONS:**\nDetermine if this email contains information about ANY of these topics:\n1. AI technology in legal practice (legal tech, AI tools for lawyers)\n2. Law firm news about AI adoption or initiatives\n3. AI regulations, legislation, or compliance affecting legal industry\n4. AI developments that impact legal services (LLMs, document review, contract analysis, eDiscovery)\n5. Legal AI startups, products, or vendor news\n6. AI ethics, liability, or professional responsibility in legal context\n7. Court decisions or case law related to AI\n8. AI-assisted legal research or document automation\n\n**IMPORTANT:** Newsletter digests, aggregated news emails, and industry bulletins that contain legal AI topics ARE relevant.\n\n**RESPONSE FORMAT (JSON only):**\n```json\n{\n \"isRelevant\": true/false,\n \"confidence\": \"high\"/\"medium\"/\"low\",\n \"primaryTopic\": \"Brief description of the main legal AI topic\",\n \"keywords\": [\"keyword1\", \"keyword2\", \"keyword3\"],\n \"summary\": \"2-3 sentence summary of the relevant content\",\n \"reasoning\": \"Why this is or isn't relevant to legal AI\"\n}\n```\n\nRespond ONLY with valid JSON, no additional text.",
"options": {
"systemMessage": "You are an expert legal technology analyst specializing in AI applications in the legal industry. Your job is to analyze emails and identify content related to artificial intelligence in the legal sector. Be inclusive - if an email contains ANY relevant legal AI content, mark it as relevant. Focus on practical value for legal technology consultants."
},
"promptType": "define"
},
"typeVersion": 1.9
},
{
"id": "d0337973-7707-44b9-944d-4cf372a8bc83",
"name": "OpenAI \u2014 Relevance Model",
"type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
"position": [
896,
304
],
"parameters": {
"model": {
"__rl": true,
"mode": "list",
"value": "gpt-4o-mini",
"cachedResultName": "gpt-4o-mini"
},
"options": {}
},
"credentials": {
"openAiApi": {
"name": "<your credential>"
}
},
"typeVersion": 1.2
},
{
"id": "b9033788-577e-417c-9a07-e7df49fd654f",
"name": "Code \u2014 Parse AI Analysis",
"type": "n8n-nodes-base.code",
"position": [
1216,
128
],
"parameters": {
"jsCode": "// Parse the AI response and extract analysis\nconst items = $input.all();\nconst results = [];\n\nfor (const item of items) {\n const output = item.json.output || item.json.text || '';\n \n // Try to extract JSON from the response\n let analysis;\n try {\n // Try direct parse first\n analysis = JSON.parse(output);\n } catch (e) {\n // Try to find JSON in the response\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n analysis = JSON.parse(jsonMatch[0]);\n } catch (e2) {\n analysis = {\n isRelevant: false,\n confidence: 'low',\n primaryTopic: 'Unable to parse',\n keywords: [],\n summary: 'Analysis failed',\n reasoning: 'Could not parse AI response'\n };\n }\n } else {\n analysis = {\n isRelevant: output.toLowerCase().includes('relevant') && !output.toLowerCase().includes('not relevant'),\n confidence: 'low',\n primaryTopic: 'Manual review needed',\n keywords: [],\n summary: output.substring(0, 200),\n reasoning: 'Fallback analysis'\n };\n }\n }\n \n results.push({\n json: {\n ...item.json,\n analysis: analysis,\n isRelevant: analysis.isRelevant === true\n }\n });\n}\n\nreturn results;"
},
"typeVersion": 2
},
{
"id": "5dcaff74-d38e-4802-b716-c00aed1ab72d",
"name": "Filter \u2014 Keep Relevant Only",
"type": "n8n-nodes-base.filter",
"position": [
1408,
128
],
"parameters": {
"options": {},
"conditions": {
"options": {
"version": 2,
"leftValue": "",
"caseSensitive": true,
"typeValidation": "loose"
},
"combinator": "and",
"conditions": [
{
"id": "relevance-check",
"operator": {
"type": "boolean",
"operation": "equals"
},
"leftValue": "={{ $json.isRelevant }}",
"rightValue": true
}
]
}
},
"typeVersion": 2.2
},
{
"id": "e342c79d-3a2c-49b0-9011-16103742f313",
"name": "IMAP \u2014 Delete Processed Email",
"type": "n8n-nodes-imap.imap",
"position": [
1424,
368
],
"parameters": {
"emailUid": "={{ $('IMAP \u2014 Fetch Unread Emails').item.json.uid }}",
"resource": "email",
"operation": "deleteEmail",
"mailboxPath": {
"__rl": true,
"mode": "list",
"value": "INBOX"
},
"authentication": "coreImapAccount"
},
"credentials": {
"imap": {
"name": "<your credential>"
}
},
"typeVersion": 1
},
{
"id": "0efc8c29-2108-4121-b92e-526fa3e3705b",
"name": "Aggregate \u2014 Collect Topics",
"type": "n8n-nodes-base.aggregate",
"position": [
1600,
128
],
"parameters": {
"options": {},
"aggregate": "aggregateAllItemData"
},
"typeVersion": 1
},
{
"id": "3fbdc79b-6fbf-41d9-9fe7-9beb6d232380",
"name": "IF \u2014 Has Topics",
"type": "n8n-nodes-base.if",
"position": [
1776,
128
],
"parameters": {
"options": {},
"conditions": {
"options": {
"version": 1,
"leftValue": "",
"caseSensitive": true,
"typeValidation": "strict"
},
"combinator": "and",
"conditions": [
{
"id": "has-topics",
"operator": {
"type": "number",
"operation": "gt"
},
"leftValue": "={{ $json.data.length }}",
"rightValue": 0
}
]
}
},
"typeVersion": 2.2
},
{
"id": "89ea7900-e178-42da-9fca-32ced0edc10f",
"name": "OpenAI Agent \u2014 Research Topics",
"type": "@n8n/n8n-nodes-langchain.agent",
"position": [
1952,
128
],
"parameters": {
"text": "==You are an expert Legal Technology Research Assistant. \n\n**TODAY'S TOPICS:**\n{{ JSON.stringify($json.data.map(item => ({ topic: item.analysis?.primaryTopic, summary: item.analysis?.summary })), null, 2) }}\n\n**TASK:**\nCreate a research report. Use Markdown formatting:\n- ## for Section Headers\n- ### for Topic Titles\n- **Bold** for emphasis\n- Bullet points for lists\n\n**STRUCTURE:**\n1. ## EXECUTIVE SUMMARY\n2. ## DETAILED TOPIC ANALYSIS\n - ### [Topic Title]\n - **Key Facts**: ...\n - **Impact**: ...\n - **Action**: ...\n3. ## MARKET INTELLIGENCE\n4. ## ACTION ITEMS\n5. SOURCE_INDEX (at the very bottom)",
"options": {
"systemMessage": "You are a senior legal technology research analyst with deep expertise in AI applications for the legal industry. Your reports are read by legal technology consultants who advise law firms and corporate legal departments. You have access to web search to find current information. Always search for the latest news and include specific source URLs in your responses. Be thorough, accurate, and focus on practical business intelligence that helps consultants identify opportunities and advise clients effectively."
},
"promptType": "define"
},
"typeVersion": 1.9
},
{
"id": "5ef58b7e-f311-4b91-a61c-32f878a5d5e4",
"name": "OpenAI \u2014 Research Model",
"type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
"position": [
1936,
304
],
"parameters": {
"model": {
"__rl": true,
"mode": "list",
"value": "gpt-4o",
"cachedResultName": "gpt-4o"
},
"options": {}
},
"credentials": {
"openAiApi": {
"name": "<your credential>"
}
},
"typeVersion": 1.2
},
{
"id": "b157a31b-69fd-4489-bae0-ca2172d05a5e",
"name": "Tavily \u2014 Web Search",
"type": "@tavily/n8n-nodes-tavily.tavilyTool",
"position": [
2128,
304
],
"parameters": {
"query": "={{ $json.data[0].analysis.primaryTopic }}",
"options": {}
},
"credentials": {
"tavilyApi": {
"name": "<your credential>"
}
},
"typeVersion": 1
},
{
"id": "c06b14ed-f83a-4318-9442-b632fa6ee536",
"name": "Code \u2014 Build HTML Email",
"type": "n8n-nodes-base.code",
"position": [
2208,
128
],
"parameters": {
"jsCode": "const researchOutput = $input.first().json.output || $input.first().json.text || 'No results.';\nconst today = new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });\n\nfunction markdownToHtml(text) {\n if (!text) return '';\n return text\n .replace(/^## (.+)$/gm, '<h2 style=\"color: #002657; font-size: 20px; margin: 25px 0 10px 0; border-bottom: 2px solid #FA4616; padding-bottom: 5px; font-family: Arial, sans-serif; text-transform: uppercase; letter-spacing: 1px;\">$1</h2>')\n .replace(/^### (.+)$/gm, '<h3 style=\"color: #002657; font-size: 17px; margin: 15px 0 5px 0;\">$1</h3>')\n .replace(/\\*\\*(.+?)\\*\\*/g, '<strong style=\"color: #1a1a1a;\">$1</strong>')\n .replace(/^[\\-\\*] (.+)$/gm, '<li style=\"margin: 0; padding: 2px 0; line-height: 1.2;\">$1</li>')\n .replace(/\\n\\n/g, '</p><p style=\"margin: 12px 0; line-height: 1.5; color: #333;\">')\n .replace(/\\n/g, '<br>');\n}\n\nfunction wrapLists(html) {\n return html.replace(/(<li[^>]*>.*?<\\/li>(?:<br>)?)+/g, '<ul style=\"margin: 5px 0 10px 25px; padding: 0; list-style-type: disc; color: #444;\">$&</ul>');\n}\n\nconst formattedContent = wrapLists(markdownToHtml(researchOutput));\n\nconst htmlEmail = `\n<!DOCTYPE html>\n<html>\n<body style=\"margin: 0; padding: 0; background-color: #f0f2f5; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\">\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" style=\"background-color: #f0f2f5; padding: 30px 0;\">\n <tr>\n <td align=\"center\">\n <table role=\"presentation\" width=\"850\" style=\"background-color: #ffffff; border: 1px solid #d1d9e0; border-radius: 6px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);\">\n <tr>\n <td style=\"background-color: #002657; padding: 35px 40px; text-align: center;\">\n <h1 style=\"color: #ffffff; margin: 0; font-size: 26px; font-weight: 400; letter-spacing: 2px;\">AI LEGAL DIGEST - <span style=\"color: #FA4616;\">${today}</span></h1>\n </td>\n </tr>\n <tr>\n <td style=\"padding: 40px 50px; color: #2d3436; font-size: 16px;\">\n ${formattedContent}\n </td>\n </tr>\n <tr>\n <td style=\"background-color: #f8f9fa; padding: 30px; border-top: 1px solid #eeeeee; text-align: center;\">\n <span style=\"font-size: 12px; color: #636e72;\">Automated AI digest • Generated by n8n</span>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n</body>\n</html>\n`;\n\nreturn [{ json: { htmlEmail, subject: `AI Legal Digest | ${today}` } }];"
},
"typeVersion": 2
},
{
"id": "72e6d038-b69d-47cb-b0bb-18ce32fae68b",
"name": "Gmail \u2014 Send Digest",
"type": "n8n-nodes-base.gmail",
"position": [
2352,
128
],
"parameters": {
"sendTo": "user@example.com",
"message": "={{ $json.htmlEmail }}",
"options": {
"appendAttribution": false
},
"subject": "={{ $json.subject }}"
},
"credentials": {
"gmailOAuth2": {
"name": "<your credential>"
}
},
"typeVersion": 2.1
}
],
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "",
"connections": {
"IF \u2014 Has Topics": {
"main": [
[
{
"node": "OpenAI Agent \u2014 Research Topics",
"type": "main",
"index": 0
}
]
]
},
"Tavily \u2014 Web Search": {
"ai_tool": [
[
{
"node": "OpenAI Agent \u2014 Research Topics",
"type": "ai_tool",
"index": 0
}
]
]
},
"Code \u2014 Build HTML Email": {
"main": [
[
{
"node": "Gmail \u2014 Send Digest",
"type": "main",
"index": 0
}
]
]
},
"OpenAI \u2014 Research Model": {
"ai_languageModel": [
[
{
"node": "OpenAI Agent \u2014 Research Topics",
"type": "ai_languageModel",
"index": 0
}
]
]
},
"Code \u2014 Parse AI Analysis": {
"main": [
[
{
"node": "Filter \u2014 Keep Relevant Only",
"type": "main",
"index": 0
},
{
"node": "IMAP \u2014 Delete Processed Email",
"type": "main",
"index": 0
}
]
]
},
"OpenAI \u2014 Relevance Model": {
"ai_languageModel": [
[
{
"node": "OpenAI Agent \u2014 Score Relevance",
"type": "ai_languageModel",
"index": 0
}
]
]
},
"Schedule \u2014 Every 5 Hours": {
"main": [
[
{
"node": "IMAP \u2014 Fetch Unread Emails",
"type": "main",
"index": 0
}
]
]
},
"Aggregate \u2014 Collect Topics": {
"main": [
[
{
"node": "IF \u2014 Has Topics",
"type": "main",
"index": 0
}
]
]
},
"IMAP \u2014 Fetch Unread Emails": {
"main": [
[
{
"node": "Set \u2014 Extract Email Fields",
"type": "main",
"index": 0
}
]
]
},
"Set \u2014 Extract Email Fields": {
"main": [
[
{
"node": "OpenAI Agent \u2014 Score Relevance",
"type": "main",
"index": 0
}
]
]
},
"Filter \u2014 Keep Relevant Only": {
"main": [
[
{
"node": "Aggregate \u2014 Collect Topics",
"type": "main",
"index": 0
}
]
]
},
"OpenAI Agent \u2014 Research Topics": {
"main": [
[
{
"node": "Code \u2014 Build HTML Email",
"type": "main",
"index": 0
}
]
]
},
"OpenAI Agent \u2014 Score Relevance": {
"main": [
[
{
"node": "Code \u2014 Parse AI Analysis",
"type": "main",
"index": 0
}
]
]
}
}
}
Credentials you'll need
Each integration node will prompt for credentials when you import. We strip credential IDs before publishing — you'll add your own.
gmailOAuth2imapopenAiApitavilyApi
For the full experience including quality scoring and batch install features for each workflow upgrade to Pro
About this workflow
Monitor an inbox, keep only emails about AI in the legal industry (or any topic), research each topic with web search, and email a branded HTML digest. A schedule trigger polls an IMAP mailbox every few hours for unread emails. Each message is extracted and passed to an agent…
Source: https://n8n.io/workflows/17710/ — original creator credit. Request a take-down →
Related workflows
Workflows that share integrations, category, or trigger type with this one. All free to copy and import.
Automatically searches for recent job postings (example: “Software Engineering Intern”), extracts structured details from each posting using an AI agent + Tavily, bundles results, and emails a single
This n8n workflow template uses community nodes and is only compatible with the self-hosted version of n8n.
This n8n automation workflow automates the creation, scripting, production, and posting of YouTube videos. It leverages AI (OpenAI), image generation (PIAPI), video rendering (Shotstack), and platform
Created by: Peyton Leveillee Last updated: October 2025
The Multi-Model Agency Content Engine is a high-performance editorial system designed for agencies. It solves the "blank page" problem by alternating between real-world social proof and strategic expe