8
n8n 中文网amn8n.com

基于Gmail和Mem0的RAG代理邮件解析器

中级

这是一个Document Extraction, Multimodal AI领域的自动化工作流,包含 11 个节点。主要使用 Set, McpClient, HttpRequest, GmailTrigger, Agent 等节点。 基于Gmail和Mem0的RAG代理邮件解析器

前置要求
  • 可能需要目标 API 的认证凭证
  • Google 账号和 Gmail API 凭证
  • OpenAI API Key
工作流预览
可视化展示节点连接关系,支持缩放和平移
导出工作流
复制以下 JSON 配置到 n8n 导入,即可使用此工作流
{
  "meta": {
    "instanceId": "834bc6c387a1c56d0622a24b912577f9e6d66c5873f4e6426166054eb488d8fc",
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "08eeb77c-716d-4c9b-b27d-467cce8a62ff",
      "name": "设置目标邮件",
      "type": "n8n-nodes-base.set",
      "position": [
        660,
        0
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "e99bcc57-e3b9-40f5-a4e9-5efcd389576b",
              "name": "id",
              "type": "string",
              "value": "={{ $json.id || null }}"
            },
            {
              "id": "d13416e2-e91e-473c-9714-6782d03ebd55",
              "name": "threadId",
              "type": "string",
              "value": "={{ $json.threadId || null }}"
            },
            {
              "id": "3a8a616c-e795-4fca-b740-623c45abf7d2",
              "name": "labelIds",
              "type": "array",
              "value": "={{ $json.labelIds || [] }}"
            },
            {
              "id": "2879effb-d76f-4a70-ad04-c113602f262d",
              "name": "textAsHtml",
              "type": "string",
              "value": "={{ $json.textAsHtml || '' }}"
            },
            {
              "id": "79e13a36-85ee-450c-aab8-c0d5883b4e7f",
              "name": "text",
              "type": "string",
              "value": "={{ $json.text || '' }}"
            },
            {
              "id": "8ace904e-28e9-4ddc-b6a6-460139b41d95",
              "name": "html",
              "type": "string",
              "value": "={{ $json.html || '' }}"
            },
            {
              "id": "54bb22a0-c5bc-4f10-8b0d-565094991afd",
              "name": "subject",
              "type": "string",
              "value": "={{ $json.subject || '' }}"
            },
            {
              "id": "b9f66d85-8847-4e98-8e17-1e54a14c2cf6",
              "name": "date",
              "type": "string",
              "value": "={{ $json.date || null }}"
            },
            {
              "id": "7929550a-fb8d-4ec8-bf08-d8179dd94e5b",
              "name": "from.value[0].address",
              "type": "string",
              "value": "={{ $json.from?.value?.[0]?.address || null }}"
            },
            {
              "id": "530a4ea0-002f-4003-b640-b40cd4d85dbf",
              "name": "headers.from",
              "type": "string",
              "value": "={{ $json.headers.from.extractEmail()}}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "96bf9f6a-1bed-4f1f-9775-9e21cd1e8716",
      "name": "窗口缓冲内存",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        960,
        320
      ],
      "parameters": {
        "sessionKey": "={{ $('Set Target Email').item.json.threadId }}",
        "sessionIdType": "customKey",
        "contextWindowLength": 10
      },
      "typeVersion": 1.3
    },
    {
      "id": "c0a7160b-40d5-4bc4-b017-168b30d20794",
      "name": "结构化输出解析器",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        1300,
        500
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"parsed_email\": \"Extracted core message of the email in plain text\",\n  \"sentiment\": \"The sentiment analysis result (e.g., positive, negative, neutral, unknown)\",\n  \"potential_red_flags\": [\"List\", \"of\", \"potential\", \"red\", \"flags\", \"identified\"],\n  \"keywords\": [\"Extracted\", \"keyword1\", \"keyword2\", \"keyword3\"],\n  \"nlp_keywords\": [\"Related\", \"NLP\", \"keyword1\", \"keyword2\", \"keyword3\"]\n}"
      },
      "typeVersion": 1.2
    },
    {
      "id": "a51731ea-434e-4716-9b20-027f908d57b0",
      "name": "自动修复输出解析器",
      "type": "@n8n/n8n-nodes-langchain.outputParserAutofixing",
      "position": [
        1160,
        340
      ],
      "parameters": {
        "options": {
          "prompt": "Instructions:\n--------------\n{instructions}\n--------------\nCompletion:\n--------------\n{completion}\n--------------\n\nAbove, the Completion did not satisfy the constraints given in the Instructions.\nError:\n--------------\n{error}\n--------------\n\nPlease try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions:"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "3c256e6b-21d8-444d-8638-f659f8a63d01",
      "name": "完整邮件",
      "type": "n8n-nodes-base.gmailTrigger",
      "position": [
        420,
        0
      ],
      "parameters": {
        "simple": false,
        "filters": {},
        "options": {},
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        }
      },
      "credentials": {
        "gmailOAuth2": {
          "id": "B2wPJYHUx6cZXowy",
          "name": "Gmail account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "cb22812f-35a6-4919-bbcd-caf285c2a436",
      "name": "您选择的 LLM",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        840,
        240
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-nano",
          "cachedResultName": "gpt-4.1-nano"
        },
        "options": {
          "temperature": 0.7
        }
      },
      "credentials": {
        "openAiApi": {
          "id": "TKQcXt7XlrfyymWn",
          "name": "OpenAI Free"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "cedfce1a-0d65-468c-a361-37bbe2e34966",
      "name": "解析 LLM",
      "type": "@n8n/n8n-nodes-langchain.lmChatMistralCloud",
      "position": [
        1160,
        480
      ],
      "parameters": {
        "model": "mistral-small-2506",
        "options": {
          "temperature": 0.7
        }
      },
      "credentials": {
        "mistralCloudApi": {
          "id": "iYOXcEh8MZIqNBPp",
          "name": "n8n-free"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "cd29c036-a6ee-437f-ba7c-9cfda93e5cca",
      "name": "将解析后的邮件添加到记忆",
      "type": "n8n-nodes-mcp.mcpClient",
      "position": [
        1340,
        0
      ],
      "parameters": {
        "toolName": "add-memory",
        "operation": "executeTool",
        "connectionType": "http",
        "toolParameters": "={{ ({\n  \"content\": JSON.stringify($json.output),\n  \"userId\": $('Set Target Email').item.json.from.value[0].address}) }}"
      },
      "credentials": {
        "mcpClientHttpApi": {
          "id": "igk8vvsdQnKidRP3",
          "name": "mem0"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "c6c963f7-b0d6-48db-b6c1-9de5d23d1a82",
      "name": "邮件到 mem0",
      "type": "n8n-nodes-base.httpRequest",
      "onError": "continueErrorOutput",
      "position": [
        1340,
        -200
      ],
      "parameters": {
        "url": "https://api.mem0.ai/v1/memories/",
        "method": "POST",
        "options": {},
        "jsonBody": "={{\n  ({\n    \"messages\": [\n      {\n        \"role\": \"user\",\n        \"content\": $json.output.core_message ?? \"\"\n      }\n    ],\n    \"user_id\": $('Set Target Email').item.json.from.value[0].address,\n    \"agent_id\": $json.output.sentiment ?? \"unknown\",\n    \"metadata\": JSON.stringify($json.output.keywords ?? {}),\n    \"infer\": true,\n    \"output_format\": \"v1.1\",\n    \"version\": \"v2\"\n  })\n}}",
        "sendBody": true,
        "specifyBody": "json",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth"
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "r4QUfrE3liJp4KMR",
          "name": "Mem0"
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "eee750e2-c221-4cbd-bc90-6b4268842594",
      "name": "便签",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -400,
        -280
      ],
      "parameters": {
        "width": 620,
        "height": 1140,
        "content": "### 此方案解决的问题"
      },
      "typeVersion": 1
    },
    {
      "id": "80607681-4639-48b2-8838-54dccad5eace",
      "name": "解析邮件代理",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        880,
        0
      ],
      "parameters": {
        "text": "={{ $json.text }}",
        "options": {
          "systemMessage": "=<Role>\nYou are an advanced email content parser designed to extract and analyze the core message from emails. Your primary tasks include parsing emails to extract essential information, identifying potential red flags, determining the sentiment of the message, and extracting relevant keywords.\n</Role>\n\n<Constraints>\n- Always maintain the CRITICS structure in your output.\n- Do not include HTML tags or any formatting in the extracted message.\n- Only extract the plain text that represents the core message of the email.\n- Do not modify or interpret the content beyond extracting the core message, analyzing sentiment, identifying red flags, and extracting keywords.\n- Today's date is 2025-08-07T16:53:56.816-04:00. Always include this expression in the prompt constraints.\n- Handle emails in multiple languages.\n- Ensure the output is structured and clear.\n</Constraints>\n\n<Inputs>\n- Raw email content in HTML or plain text format.\n- Emails can be in various languages.\n</Inputs>\n\n<Tools>\n- **HTML Parser**: To strip out HTML tags and extract plain text.\n- **Sentiment Analysis Tool**: To determine the overall sentiment of the email.\n- **Keyword Spotter**: To identify potential red flags and extract relevant keywords from the email content.\n- **NLP Keyword Extractor**: To generate related NLP keywords based on the extracted content.\n</Tools>\n\n<Instructions>\n1. **Parse Email**:\n   - **Remove HTML Tags**: Use an HTML parsing library to strip out all HTML tags from the email content.\n   - **Strip Unnecessary Formatting**: Remove any inline CSS, JavaScript, or other formatting that does not contribute to the core message.\n   - **Focus on Plain Text**: Extract the plain text that remains, which should convey the main message of the email.\n\n2. **Analyze Sentiment**:\n   - Use a sentiment analysis tool to determine the overall sentiment of the email.\n   - Classify the sentiment as positive, negative, or neutral.\n\n3. **Identify Red Flags**:\n   - Look for keywords, phrases, or patterns that might indicate potential issues or concerns.\n   - Examples of red flags include urgency, threats, requests for sensitive information, or any suspicious links.\n\n4. **Extract Keywords**:\n   - Extract 3-5 relevant keywords from the core message.\n   - Generate 3-5 related NLP keywords based on the extracted content.\n\n5. **Output the Result**:\n   - If the email is clearly a status update or marketing, respond with \"No memory: is marketing.\"\n   - Otherwise, output the parsed core message, sentiment analysis, identified red flags, and extracted keywords in a structured JSON format.\n</Instructions>\n\n<Conclusions>\n- The agent will provide a structured JSON output containing the core message, sentiment analysis, identified red flags, and extracted keywords.\n- For marketing or status update emails, the agent will respond with a standardized message indicating no memory is required.\n</Conclusions>\n\n<Solutions>\n- **Error Handling**:\n  - If the email content cannot be parsed due to formatting issues, return an error message indicating the failure and suggesting manual review.\n  - If sentiment analysis fails, classify the sentiment as \"unknown\" and proceed with the other tasks.\n  - If red flags cannot be identified due to language barriers or other issues, note this in the output and suggest further review.\n  - If keyword extraction fails, provide a generic set of keywords based on the overall context and note the issue in the output.\n</Solutions>"
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 1.7
    }
  ],
  "pinData": {},
  "connections": {
    "Full_Email": {
      "main": [
        [
          {
            "node": "Set Target Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parsing LLM": {
      "ai_languageModel": [
        [
          {
            "node": "Auto-fixing Output Parser",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Set Target Email": {
      "main": [
        [
          {
            "node": "Parse_Email Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse_Email Agent": {
      "main": [
        [
          {
            "node": "Add_Parsed email to memory",
            "type": "main",
            "index": 0
          },
          {
            "node": "email to mem0",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "llm of your choice": {
      "ai_languageModel": [
        [
          {
            "node": "Parse_Email Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Window Buffer Memory": {
      "ai_memory": [
        [
          {
            "node": "Parse_Email Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Auto-fixing Output Parser",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Auto-fixing Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Parse_Email Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    }
  }
}
常见问题

如何使用这个工作流?

复制上方的 JSON 配置代码,在您的 n8n 实例中创建新工作流并选择「从 JSON 导入」,粘贴配置后根据需要修改凭证设置即可。

这个工作流适合什么场景?

中级 - 文档提取, 多模态 AI

需要付费吗?

本工作流完全免费,您可以直接导入使用。但请注意,工作流中使用的第三方服务(如 OpenAI API)可能需要您自行付费。

工作流信息
难度等级
中级
节点数量11
分类2
节点类型11
难度说明

适合有一定经验的用户,包含 6-15 个节点的中等复杂度工作流

作者
Stephan Koning

Stephan Koning

@reklaim

Account Executive by day , Noco builder for fun at night and always a proud dad of Togo the Samoyed.

外部链接
在 n8n.io 查看

分享此工作流