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 of your choice",
      "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": "Parsing 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": "email to 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": "### The Problem This Solves\n\nYour inbox is a goldmine of client data, but it's unstructured, and manually monitoring it is a full-time job. This constant, reactive work prevents you from scaling. This workflow solves that \"system problem\" by creating an \"always-on\" engine that automatically processes, analyzes, and structures every incoming email, turning raw communication into a single source of truth for growth.\n\n### How It Works\n\nThis is an autonomous, multi-stage intelligence engine. It runs in the background, turning every new email into a valuable data asset.\n\n1.  **Real-Time Ingest & Prep:** The system is kicked off by the **Gmail Trigger**, which constantly watches your inbox. The moment a new email arrives, the workflow fires. That email is immediately passed to the **Set Target Email** node, which strips it down to the essentials: the sender's address, the subject, and the core text of the message (I prefer using the plain text or HTML-as-text for reliability). While this step is optional, it's a good practice for keeping the data clean and orderly for the AI.\n\n2.  **AI Analysis (The Brain):** The prepared text is fed to the core of the system: the **AI Agent**. This agent, powered by the **LLM of your choice** (e.g., GPT-4), reads and understands the email's content. It's not just reading; it's performing analysis to:\n    * Extract the core message.\n    * Determine the sentiment (Positive, Negative, Neutral).\n    * Identify potential red flags.\n    * Pull out key topics and keywords.\n    * The agent uses **Window Buffer Memory** to recall the last 10 messages within the same conversation thread, giving it the context to provide a much smarter analysis.\n\n3.  **Quality Control (The Parser):** We don't trust the AI's first draft blindly. The analysis is sent to an **Auto-fixing Output Parser**. If the initial output isn't in a perfect JSON format, a second **Parsing LLM** (e.g., Mistral) automatically corrects it. This is our \"twist\" that guarantees your data is always perfectly structured and reliable.\n\n4.  **Create a Permanent Client Record:** This is the most critical step. The clean, structured data is sent to **mem0**. The analysis is now logged against the **sender's email address**. This moves beyond just tracking conversations; it builds a complete, historical intelligence file on every person you communicate with, creating an invaluable, long-term asset.\n\n> **Optional Use:** For back-filling historical data, you can disable the Gmail Trigger and temporarily connect a **Gmail \"Get Many\"** node to the `Set Target Email` node to process your backlog in batches.\n\n\n### Setup Requirements\n\nTo deploy this system, you'll need the following:\n* An active **n8n** instance.\n* **Gmail** API credentials.\n* An API key for your primary LLM (e.g., **OpenAI**).\n* An account with **mem0.ai** for the memory layer.\n* Community node for MCP mode or use the HTTP + curl instead"
      },
      "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": {
    "3c256e6b-21d8-444d-8638-f659f8a63d01": {
      "main": [
        [
          {
            "node": "08eeb77c-716d-4c9b-b27d-467cce8a62ff",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "cedfce1a-0d65-468c-a361-37bbe2e34966": {
      "ai_languageModel": [
        [
          {
            "node": "a51731ea-434e-4716-9b20-027f908d57b0",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "08eeb77c-716d-4c9b-b27d-467cce8a62ff": {
      "main": [
        [
          {
            "node": "80607681-4639-48b2-8838-54dccad5eace",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "80607681-4639-48b2-8838-54dccad5eace": {
      "main": [
        [
          {
            "node": "cd29c036-a6ee-437f-ba7c-9cfda93e5cca",
            "type": "main",
            "index": 0
          },
          {
            "node": "c6c963f7-b0d6-48db-b6c1-9de5d23d1a82",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "cb22812f-35a6-4919-bbcd-caf285c2a436": {
      "ai_languageModel": [
        [
          {
            "node": "80607681-4639-48b2-8838-54dccad5eace",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "96bf9f6a-1bed-4f1f-9775-9e21cd1e8716": {
      "ai_memory": [
        [
          {
            "node": "80607681-4639-48b2-8838-54dccad5eace",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "c0a7160b-40d5-4bc4-b017-168b30d20794": {
      "ai_outputParser": [
        [
          {
            "node": "a51731ea-434e-4716-9b20-027f908d57b0",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "a51731ea-434e-4716-9b20-027f908d57b0": {
      "ai_outputParser": [
        [
          {
            "node": "80607681-4639-48b2-8838-54dccad5eace",
            "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で表示

このワークフローを共有

カテゴリー

カテゴリー: 34