8
n8n 中文网amn8n.com

邮件转Notion知识库(含IMAP、Postgres去重和Telegram提醒)

高级

这是一个Internal Wiki, Multimodal AI领域的自动化工作流,包含 28 个节点。主要使用 If, Code, Notion, Postgres, Telegram 等节点。 将邮件转换为Notion知识库,包含IMAP、Postgres去重和Telegram提醒功能

前置要求
  • Notion API Key
  • PostgreSQL 数据库连接信息
  • Telegram Bot Token
工作流预览
可视化展示节点连接关系,支持缩放和平移
导出工作流
复制以下 JSON 配置到 n8n 导入,即可使用此工作流
{
  "meta": {
    "instanceId": "",
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "f69ede00-31fd-4c5f-b4ac-1dc3ed08d9c0",
      "name": "电子邮件触发器 (IMAP)",
      "type": "n8n-nodes-base.emailReadImap",
      "position": [
        -928,
        656
      ],
      "parameters": {
        "options": {
          "forceReconnect": 60,
          "customEmailConfig": "[\"UNSEEN\"]"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "2ebe795e-796c-4996-a6d2-29c463bbfe06",
      "name": "代码",
      "type": "n8n-nodes-base.code",
      "position": [
        -704,
        656
      ],
      "parameters": {
        "jsCode": "/**\n * Function Node — Normalize & Dedupe (multi-item, no require)\n * Memproses SEMUA items dari IMAP/HTML node dan mengeluarkan jumlah item yang sama.\n * Output per item:\n * { title, snippet, bodyText, slug, messageId, sentAt, fromAddress, sourceUrl, debugFields }\n */\n\n/* ---------- Helpers (dipakai di tiap item) ---------- */\nfunction toISO(d) {\n  const dt = d ? new Date(d) : new Date();\n  return isNaN(dt) ? new Date().toISOString() : dt.toISOString();\n}\nfunction slugify(s) {\n  return String(s || '')\n    .trim().toLowerCase()\n    .replace(/\\s+/g, '-')        // spasi -> -\n    .replace(/[^a-z0-9-]/g, '')  // buang non URL-safe\n    .replace(/-+/g, '-')         // rapikan multiple -\n    .replace(/^-+|-+$/g, '');    // trim - di awal/akhir\n}\nfunction limit(str, max) {\n  const s = String(str || '').replace(/\\s+/g, ' ').trim();\n  return s.length <= max ? s : s.slice(0, max - 1).trim() + '…';\n}\nfunction firstUrlFrom(text) {\n  const s = String(text || '');\n  const m = s.match(/https?:\\/\\/[^\\s<>\"'`]+/i);\n  return m ? m[0] : '';\n}\nfunction extractFromAddress(from) {\n  if (!from) return '';\n  if (typeof from === 'string') {\n    const m = from.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i);\n    return m ? m[0] : from.trim();\n  }\n  if (from.value && Array.isArray(from.value) && from.value[0]?.address) {\n    return from.value[0].address;\n  }\n  if (from.text) {\n    const m = String(from.text).match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i);\n    return m ? m[0] : String(from.text).trim();\n  }\n  if (from.address) return String(from.address);\n  return '';\n}\nfunction stripHtmlToText(html, fallbackText = '') {\n  let h = String(html || '');\n  if (!h) return String(fallbackText || '');\n  h = h.replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n       .replace(/<style[\\s\\S]*?<\\/style>/gi, '');\n  let t = h.replace(/<\\/?[^>]+>/g, ' ');\n  return t.replace(/\\s+/g, ' ').trim();\n}\nfunction simpleHash(str) {\n  let hash = 0;\n  const s = String(str || '');\n  for (let i = 0; i < s.length; i++) {\n    hash = (hash << 5) - hash + s.charCodeAt(i);\n    hash |= 0; // 32-bit\n  }\n  return Math.abs(hash).toString(16);\n}\n\n/* ---------- PROSES SEMUA ITEM ---------- */\nconst titleMax = 140;\nconst snippetMax = 260;\n\nreturn items.map((item) => {\n  const j = item.json || {};\n\n  // 1) SUBJECT (multi-jalur)\n  const subject =\n    j.subject ??\n    j.headers?.subject ??\n    j.message?.subject ??\n    '(no subject)';\n\n  // 2) BODY (multi-jalur) — dukung hasil HTML node juga (mis. bodyText)\n  const htmlCandidates = [\n    j.bodyTextHtml,   // beberapa node\n    j.textHtml,\n    j.html,\n    j.body?.html,\n    j.message?.html,\n  ];\n  const textCandidates = [\n    j.bodyText,       // kalau HTML node menaruh hasil disini\n    j.textPlain,\n    j.text,\n    j.body?.text,\n    j.message?.text,\n  ];\n\n  const htmlSrc = htmlCandidates.find(v => v && String(v).trim().length > 0);\n  let text = textCandidates.find(v => v && String(v).trim().length > 0) || '';\n\n  if (htmlSrc) {\n    text = stripHtmlToText(htmlSrc, text);\n  } else {\n    text = String(text).replace(/\\s+/g, ' ').trim();\n  }\n\n  // 3) DATE (multi-jalur)\n  const rawDate =\n    j.date ??\n    j.internalDate ??\n    j.headers?.date ??\n    j.message?.date ??\n    new Date().toISOString();\n  const sentAt = toISO(rawDate);\n\n  // 4) FROM (multi-jalur)\n  const fromCandidate =\n    j.from ??\n    j.headers?.from ??\n    j.message?.from ??\n    '';\n  const fromAddress = extractFromAddress(fromCandidate);\n\n  // 5) Title/Slug/Snippet\n  const title = limit(String(subject || '(no subject)').trim(), titleMax);\n  const slug = slugify(title);\n  const snippet = limit(text, snippetMax);\n\n  // 6) URL pertama (opsional)\n  const sourceUrl = firstUrlFrom(text) || '';\n\n  // 7) messageId (fallback hash)\n  let messageId =\n    (j.messageId ?? j.headers?.['message-id'] ?? j.message?.messageId ?? '').toString().trim();\n  if (!messageId) {\n    messageId = simpleHash(`${title}__${sentAt}`);\n  }\n\n  // 8) Debug asal field (opsional, boleh dihapus nanti)\n  const debugFields = {\n    subjectPickedFrom: subject === j.subject ? 'subject'\n      : subject === j.headers?.subject ? 'headers.subject'\n      : subject === j.message?.subject ? 'message.subject'\n      : '(default)',\n    bodyPickedFrom: htmlSrc ? 'HTML→text'\n      : (textCandidates.find(v => v && String(v).trim().length > 0) ? 'plain text' : '(none)'),\n    datePickedFrom: rawDate === j.date ? 'date'\n      : rawDate === j.internalDate ? 'internalDate'\n      : rawDate === j.headers?.date ? 'headers.date'\n      : rawDate === j.message?.date ? 'message.date'\n      : '(default now)',\n    fromPickedFrom: typeof fromCandidate === 'string' ? '(string)'\n      : fromCandidate?.value ? 'from.value[0]'\n      : fromCandidate?.text ? 'from.text'\n      : '(unknown)',\n  };\n\n  return {\n    json: {\n      title,\n      snippet,\n      bodyText: text,\n      slug,\n      messageId,\n      sentAt,\n      fromAddress,\n      sourceUrl,\n      debugFields, // hapus kalau sudah yakin\n    }\n  };\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "7b18f198-1e29-4cf7-b5c4-ca483e4f4486",
      "name": "执行 SQL 查询",
      "type": "n8n-nodes-base.postgres",
      "position": [
        -480,
        656
      ],
      "parameters": {
        "query": "SELECT EXISTS(\n  SELECT 1\n  FROM email_kb_index\n  WHERE message_id = '{{ $json.messageId }}'\n) AS exists;\n",
        "options": {},
        "operation": "executeQuery"
      },
      "typeVersion": 2.6
    },
    {
      "id": "39cbc53e-23e4-426f-b879-e1a2fc81c4b8",
      "name": "如果",
      "type": "n8n-nodes-base.if",
      "position": [
        -256,
        656
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "086a03b2-23c7-4a90-904e-420bbd480a0a",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              },
              "leftValue": "={{ $json.exists }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "ee6394e8-31f1-4962-9c56-c7fa924e162c",
      "name": "创建数据库页面",
      "type": "n8n-nodes-base.notion",
      "position": [
        -32,
        656
      ],
      "parameters": {
        "title": "={{ $('Code').item.json.title }}",
        "options": {},
        "resource": "databasePage",
        "databaseId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultUrl": "",
          "cachedResultName": "Email Knowledge Base"
        },
        "propertiesUi": {
          "propertyValues": [
            {
              "key": "date|date",
              "date": "={{ $('Code').item.json.sentAt }}"
            },
            {
              "key": "summary|rich_text",
              "textContent": "={{ $('Code').item.json.snippet }}"
            },
            {
              "key": "sourceUrl|url",
              "urlValue": "={{ $('Code').item.json.sourceUrl }}",
              "ignoreIfEmpty": true
            },
            {
              "key": "From|rich_text",
              "textContent": "={{ $('Code').item.json.fromAddress }}"
            },
            {
              "key": "Slug|rich_text",
              "textContent": "={{ $('Code').item.json.slug }}"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "7d3d8ece-4dc4-484c-a6ba-11a706933de5",
      "name": "发送短信",
      "type": "n8n-nodes-base.telegram",
      "position": [
        192,
        656
      ],
      "webhookId": "e529cba8-37ec-4427-8404-b1d20e4924c7",
      "parameters": {
        "additionalFields": {}
      },
      "typeVersion": 1.2
    },
    {
      "id": "a2c4f333-cb90-44a5-9469-bc89d33e7824",
      "name": "便签",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1008,
        -160
      ],
      "parameters": {
        "width": 640,
        "height": 672,
        "content": "0) 创建 Postgres 表 (运行一次)"
      },
      "typeVersion": 1
    },
    {
      "id": "d3cd1192-79e8-4d02-b157-5611f53f9141",
      "name": "便签1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -352,
        -96
      ],
      "parameters": {
        "color": 3,
        "width": 672,
        "height": 528,
        "content": "6. Notion — 创建页面 (父级: 数据库)"
      },
      "typeVersion": 1
    },
    {
      "id": "eb42b744-cf6a-49d5-9c5f-5109d823e2af",
      "name": "电子邮件触发器 (IMAP)1",
      "type": "n8n-nodes-base.emailReadImap",
      "disabled": true,
      "position": [
        -544,
        -96
      ],
      "parameters": {
        "options": {
          "forceReconnect": 60,
          "customEmailConfig": "[\"UNSEEN\"]"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "1dd93fa5-e5c8-4dd2-963e-1130ff968a73",
      "name": "代码1",
      "type": "n8n-nodes-base.code",
      "disabled": true,
      "position": [
        -544,
        48
      ],
      "parameters": {
        "jsCode": "/**\n * Function Node — Normalize & Dedupe (multi-item, no require)\n * Memproses SEMUA items dari IMAP/HTML node dan mengeluarkan jumlah item yang sama.\n * Output per item:\n * { title, snippet, bodyText, slug, messageId, sentAt, fromAddress, sourceUrl, debugFields }\n */\n\n/* ---------- Helpers (dipakai di tiap item) ---------- */\nfunction toISO(d) {\n  const dt = d ? new Date(d) : new Date();\n  return isNaN(dt) ? new Date().toISOString() : dt.toISOString();\n}\nfunction slugify(s) {\n  return String(s || '')\n    .trim().toLowerCase()\n    .replace(/\\s+/g, '-')        // spasi -> -\n    .replace(/[^a-z0-9-]/g, '')  // buang non URL-safe\n    .replace(/-+/g, '-')         // rapikan multiple -\n    .replace(/^-+|-+$/g, '');    // trim - di awal/akhir\n}\nfunction limit(str, max) {\n  const s = String(str || '').replace(/\\s+/g, ' ').trim();\n  return s.length <= max ? s : s.slice(0, max - 1).trim() + '…';\n}\nfunction firstUrlFrom(text) {\n  const s = String(text || '');\n  const m = s.match(/https?:\\/\\/[^\\s<>\"'`]+/i);\n  return m ? m[0] : '';\n}\nfunction extractFromAddress(from) {\n  if (!from) return '';\n  if (typeof from === 'string') {\n    const m = from.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i);\n    return m ? m[0] : from.trim();\n  }\n  if (from.value && Array.isArray(from.value) && from.value[0]?.address) {\n    return from.value[0].address;\n  }\n  if (from.text) {\n    const m = String(from.text).match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i);\n    return m ? m[0] : String(from.text).trim();\n  }\n  if (from.address) return String(from.address);\n  return '';\n}\nfunction stripHtmlToText(html, fallbackText = '') {\n  let h = String(html || '');\n  if (!h) return String(fallbackText || '');\n  h = h.replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n       .replace(/<style[\\s\\S]*?<\\/style>/gi, '');\n  let t = h.replace(/<\\/?[^>]+>/g, ' ');\n  return t.replace(/\\s+/g, ' ').trim();\n}\nfunction simpleHash(str) {\n  let hash = 0;\n  const s = String(str || '');\n  for (let i = 0; i < s.length; i++) {\n    hash = (hash << 5) - hash + s.charCodeAt(i);\n    hash |= 0; // 32-bit\n  }\n  return Math.abs(hash).toString(16);\n}\n\n/* ---------- PROSES SEMUA ITEM ---------- */\nconst titleMax = 140;\nconst snippetMax = 260;\n\nreturn items.map((item) => {\n  const j = item.json || {};\n\n  // 1) SUBJECT (multi-jalur)\n  const subject =\n    j.subject ??\n    j.headers?.subject ??\n    j.message?.subject ??\n    '(no subject)';\n\n  // 2) BODY (multi-jalur) — dukung hasil HTML node juga (mis. bodyText)\n  const htmlCandidates = [\n    j.bodyTextHtml,   // beberapa node\n    j.textHtml,\n    j.html,\n    j.body?.html,\n    j.message?.html,\n  ];\n  const textCandidates = [\n    j.bodyText,       // kalau HTML node menaruh hasil disini\n    j.textPlain,\n    j.text,\n    j.body?.text,\n    j.message?.text,\n  ];\n\n  const htmlSrc = htmlCandidates.find(v => v && String(v).trim().length > 0);\n  let text = textCandidates.find(v => v && String(v).trim().length > 0) || '';\n\n  if (htmlSrc) {\n    text = stripHtmlToText(htmlSrc, text);\n  } else {\n    text = String(text).replace(/\\s+/g, ' ').trim();\n  }\n\n  // 3) DATE (multi-jalur)\n  const rawDate =\n    j.date ??\n    j.internalDate ??\n    j.headers?.date ??\n    j.message?.date ??\n    new Date().toISOString();\n  const sentAt = toISO(rawDate);\n\n  // 4) FROM (multi-jalur)\n  const fromCandidate =\n    j.from ??\n    j.headers?.from ??\n    j.message?.from ??\n    '';\n  const fromAddress = extractFromAddress(fromCandidate);\n\n  // 5) Title/Slug/Snippet\n  const title = limit(String(subject || '(no subject)').trim(), titleMax);\n  const slug = slugify(title);\n  const snippet = limit(text, snippetMax);\n\n  // 6) URL pertama (opsional)\n  const sourceUrl = firstUrlFrom(text) || '';\n\n  // 7) messageId (fallback hash)\n  let messageId =\n    (j.messageId ?? j.headers?.['message-id'] ?? j.message?.messageId ?? '').toString().trim();\n  if (!messageId) {\n    messageId = simpleHash(`${title}__${sentAt}`);\n  }\n\n  // 8) Debug asal field (opsional, boleh dihapus nanti)\n  const debugFields = {\n    subjectPickedFrom: subject === j.subject ? 'subject'\n      : subject === j.headers?.subject ? 'headers.subject'\n      : subject === j.message?.subject ? 'message.subject'\n      : '(default)',\n    bodyPickedFrom: htmlSrc ? 'HTML→text'\n      : (textCandidates.find(v => v && String(v).trim().length > 0) ? 'plain text' : '(none)'),\n    datePickedFrom: rawDate === j.date ? 'date'\n      : rawDate === j.internalDate ? 'internalDate'\n      : rawDate === j.headers?.date ? 'headers.date'\n      : rawDate === j.message?.date ? 'message.date'\n      : '(default now)',\n    fromPickedFrom: typeof fromCandidate === 'string' ? '(string)'\n      : fromCandidate?.value ? 'from.value[0]'\n      : fromCandidate?.text ? 'from.text'\n      : '(unknown)',\n  };\n\n  return {\n    json: {\n      title,\n      snippet,\n      bodyText: text,\n      slug,\n      messageId,\n      sentAt,\n      fromAddress,\n      sourceUrl,\n      debugFields, // hapus kalau sudah yakin\n    }\n  };\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "de0849c9-a638-42ce-b436-9f50000f5b0c",
      "name": "执行 SQL 查询1",
      "type": "n8n-nodes-base.postgres",
      "disabled": true,
      "position": [
        -544,
        208
      ],
      "parameters": {
        "query": "SELECT EXISTS(\n  SELECT 1\n  FROM email_kb_index\n  WHERE message_id = '{{ $json.messageId }}'\n) AS exists;\n",
        "options": {},
        "operation": "executeQuery"
      },
      "typeVersion": 2.6
    },
    {
      "id": "c092af6c-aa61-432f-9212-7723fdecef1c",
      "name": "如果1",
      "type": "n8n-nodes-base.if",
      "disabled": true,
      "position": [
        -544,
        368
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "086a03b2-23c7-4a90-904e-420bbd480a0a",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              },
              "leftValue": "={{ $json.exists }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "3de38f0e-371a-4e52-b6e4-2fa4aafa0306",
      "name": "创建数据库页面1",
      "type": "n8n-nodes-base.notion",
      "disabled": true,
      "position": [
        144,
        -16
      ],
      "parameters": {
        "title": "={{ $('Code').item.json.title }}",
        "options": {},
        "resource": "databasePage",
        "databaseId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultUrl": "",
          "cachedResultName": "Email Knowledge Base"
        },
        "propertiesUi": {
          "propertyValues": [
            {
              "key": "date|date",
              "date": "={{ $('Code').item.json.sentAt }}"
            },
            {
              "key": "summary|rich_text",
              "textContent": "={{ $('Code').item.json.snippet }}"
            },
            {
              "key": "sourceUrl|url",
              "urlValue": "={{ $('Code').item.json.sourceUrl }}",
              "ignoreIfEmpty": true
            },
            {
              "key": "From|rich_text",
              "textContent": "={{ $('Code').item.json.fromAddress }}"
            },
            {
              "key": "Slug|rich_text",
              "textContent": "={{ $('Code').item.json.slug }}"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "055677f0-bea4-4a65-b603-b918068e3fb2",
      "name": "发送短信1",
      "type": "n8n-nodes-base.telegram",
      "disabled": true,
      "position": [
        128,
        224
      ],
      "webhookId": "e529cba8-37ec-4427-8404-b1d20e4924c7",
      "parameters": {
        "additionalFields": {}
      },
      "typeVersion": 1.2
    },
    {
      "id": "8071d1b9-8da3-4720-b1ee-0537f2c05262",
      "name": "电子邮件触发器 (IMAP)2",
      "type": "n8n-nodes-base.emailReadImap",
      "position": [
        -6096,
        2512
      ],
      "parameters": {
        "options": {
          "forceReconnect": 60,
          "customEmailConfig": "[\"UNSEEN\"]"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "5339fdb6-b7aa-4da0-82f5-1f6e07d96246",
      "name": "代码2",
      "type": "n8n-nodes-base.code",
      "position": [
        -5872,
        2512
      ],
      "parameters": {
        "jsCode": "/**\n * Function Node — Normalize & Dedupe (multi-item, no require)\n * Memproses SEMUA items dari IMAP/HTML node dan mengeluarkan jumlah item yang sama.\n * Output per item:\n * { title, snippet, bodyText, slug, messageId, sentAt, fromAddress, sourceUrl, debugFields }\n */\n\n/* ---------- Helpers (dipakai di tiap item) ---------- */\nfunction toISO(d) {\n  const dt = d ? new Date(d) : new Date();\n  return isNaN(dt) ? new Date().toISOString() : dt.toISOString();\n}\nfunction slugify(s) {\n  return String(s || '')\n    .trim().toLowerCase()\n    .replace(/\\s+/g, '-')        // spasi -> -\n    .replace(/[^a-z0-9-]/g, '')  // buang non URL-safe\n    .replace(/-+/g, '-')         // rapikan multiple -\n    .replace(/^-+|-+$/g, '');    // trim - di awal/akhir\n}\nfunction limit(str, max) {\n  const s = String(str || '').replace(/\\s+/g, ' ').trim();\n  return s.length <= max ? s : s.slice(0, max - 1).trim() + '…';\n}\nfunction firstUrlFrom(text) {\n  const s = String(text || '');\n  const m = s.match(/https?:\\/\\/[^\\s<>\"'`]+/i);\n  return m ? m[0] : '';\n}\nfunction extractFromAddress(from) {\n  if (!from) return '';\n  if (typeof from === 'string') {\n    const m = from.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i);\n    return m ? m[0] : from.trim();\n  }\n  if (from.value && Array.isArray(from.value) && from.value[0]?.address) {\n    return from.value[0].address;\n  }\n  if (from.text) {\n    const m = String(from.text).match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i);\n    return m ? m[0] : String(from.text).trim();\n  }\n  if (from.address) return String(from.address);\n  return '';\n}\nfunction stripHtmlToText(html, fallbackText = '') {\n  let h = String(html || '');\n  if (!h) return String(fallbackText || '');\n  h = h.replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n       .replace(/<style[\\s\\S]*?<\\/style>/gi, '');\n  let t = h.replace(/<\\/?[^>]+>/g, ' ');\n  return t.replace(/\\s+/g, ' ').trim();\n}\nfunction simpleHash(str) {\n  let hash = 0;\n  const s = String(str || '');\n  for (let i = 0; i < s.length; i++) {\n    hash = (hash << 5) - hash + s.charCodeAt(i);\n    hash |= 0; // 32-bit\n  }\n  return Math.abs(hash).toString(16);\n}\n\n/* ---------- PROSES SEMUA ITEM ---------- */\nconst titleMax = 140;\nconst snippetMax = 260;\n\nreturn items.map((item) => {\n  const j = item.json || {};\n\n  // 1) SUBJECT (multi-jalur)\n  const subject =\n    j.subject ??\n    j.headers?.subject ??\n    j.message?.subject ??\n    '(no subject)';\n\n  // 2) BODY (multi-jalur) — dukung hasil HTML node juga (mis. bodyText)\n  const htmlCandidates = [\n    j.bodyTextHtml,   // beberapa node\n    j.textHtml,\n    j.html,\n    j.body?.html,\n    j.message?.html,\n  ];\n  const textCandidates = [\n    j.bodyText,       // kalau HTML node menaruh hasil disini\n    j.textPlain,\n    j.text,\n    j.body?.text,\n    j.message?.text,\n  ];\n\n  const htmlSrc = htmlCandidates.find(v => v && String(v).trim().length > 0);\n  let text = textCandidates.find(v => v && String(v).trim().length > 0) || '';\n\n  if (htmlSrc) {\n    text = stripHtmlToText(htmlSrc, text);\n  } else {\n    text = String(text).replace(/\\s+/g, ' ').trim();\n  }\n\n  // 3) DATE (multi-jalur)\n  const rawDate =\n    j.date ??\n    j.internalDate ??\n    j.headers?.date ??\n    j.message?.date ??\n    new Date().toISOString();\n  const sentAt = toISO(rawDate);\n\n  // 4) FROM (multi-jalur)\n  const fromCandidate =\n    j.from ??\n    j.headers?.from ??\n    j.message?.from ??\n    '';\n  const fromAddress = extractFromAddress(fromCandidate);\n\n  // 5) Title/Slug/Snippet\n  const title = limit(String(subject || '(no subject)').trim(), titleMax);\n  const slug = slugify(title);\n  const snippet = limit(text, snippetMax);\n\n  // 6) URL pertama (opsional)\n  const sourceUrl = firstUrlFrom(text) || '';\n\n  // 7) messageId (fallback hash)\n  let messageId =\n    (j.messageId ?? j.headers?.['message-id'] ?? j.message?.messageId ?? '').toString().trim();\n  if (!messageId) {\n    messageId = simpleHash(`${title}__${sentAt}`);\n  }\n\n  // 8) Debug asal field (opsional, boleh dihapus nanti)\n  const debugFields = {\n    subjectPickedFrom: subject === j.subject ? 'subject'\n      : subject === j.headers?.subject ? 'headers.subject'\n      : subject === j.message?.subject ? 'message.subject'\n      : '(default)',\n    bodyPickedFrom: htmlSrc ? 'HTML→text'\n      : (textCandidates.find(v => v && String(v).trim().length > 0) ? 'plain text' : '(none)'),\n    datePickedFrom: rawDate === j.date ? 'date'\n      : rawDate === j.internalDate ? 'internalDate'\n      : rawDate === j.headers?.date ? 'headers.date'\n      : rawDate === j.message?.date ? 'message.date'\n      : '(default now)',\n    fromPickedFrom: typeof fromCandidate === 'string' ? '(string)'\n      : fromCandidate?.value ? 'from.value[0]'\n      : fromCandidate?.text ? 'from.text'\n      : '(unknown)',\n  };\n\n  return {\n    json: {\n      title,\n      snippet,\n      bodyText: text,\n      slug,\n      messageId,\n      sentAt,\n      fromAddress,\n      sourceUrl,\n      debugFields, // hapus kalau sudah yakin\n    }\n  };\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "6aaf8200-35c7-419a-9480-a54f49b43493",
      "name": "执行 SQL 查询2",
      "type": "n8n-nodes-base.postgres",
      "position": [
        -5648,
        2512
      ],
      "parameters": {
        "query": "SELECT EXISTS(\n  SELECT 1\n  FROM email_kb_index\n  WHERE message_id = '{{ $json.messageId }}'\n) AS exists;\n",
        "options": {},
        "operation": "executeQuery"
      },
      "typeVersion": 2.6
    },
    {
      "id": "481d4a86-c36a-4ced-abfa-b9aa1313f2a7",
      "name": "如果2",
      "type": "n8n-nodes-base.if",
      "position": [
        -5424,
        2512
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "086a03b2-23c7-4a90-904e-420bbd480a0a",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              },
              "leftValue": "={{ $json.exists }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "0db94227-30d5-4cd5-8e00-1c538ebee9d7",
      "name": "创建数据库页面2",
      "type": "n8n-nodes-base.notion",
      "position": [
        -5200,
        2512
      ],
      "parameters": {
        "title": "={{ $('Code2').item.json.title }}",
        "options": {},
        "resource": "databasePage",
        "databaseId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultUrl": "",
          "cachedResultName": "Email Knowledge Base"
        },
        "propertiesUi": {
          "propertyValues": [
            {
              "key": "date|date",
              "date": "={{ $('Code2').item.json.sentAt }}"
            },
            {
              "key": "summary|rich_text",
              "textContent": "={{ $('Code2').item.json.snippet }}"
            },
            {
              "key": "sourceUrl|url",
              "urlValue": "={{ $('Code2').item.json.sourceUrl }}",
              "ignoreIfEmpty": true
            },
            {
              "key": "From|rich_text",
              "textContent": "={{ $('Code2').item.json.fromAddress }}"
            },
            {
              "key": "Slug|rich_text",
              "textContent": "={{ $('Code2').item.json.slug }}"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "069bafd2-b669-4890-9dd5-417310aecfa5",
      "name": "发送短信2",
      "type": "n8n-nodes-base.telegram",
      "position": [
        -4976,
        2512
      ],
      "webhookId": "118a1948-3e67-4a62-85b4-c876ff8d69f2",
      "parameters": {
        "additionalFields": {}
      },
      "typeVersion": 1.2
    },
    {
      "id": "0f04de27-a5cf-4a83-ba16-e9530ccbb091",
      "name": "便签2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -6160,
        1712
      ],
      "parameters": {
        "width": 640,
        "height": 688,
        "content": "0) 创建 Postgres 表 (运行一次)"
      },
      "typeVersion": 1
    },
    {
      "id": "40bf69bc-7e99-44a4-ba3d-cb58274b0be1",
      "name": "便签3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -5520,
        1760
      ],
      "parameters": {
        "color": 3,
        "width": 672,
        "height": 528,
        "content": "6. Notion — 创建页面 (父级: 数据库)"
      },
      "typeVersion": 1
    },
    {
      "id": "ba8081b0-40af-45cd-b748-1fbc2fb69f66",
      "name": "电子邮件触发器 (IMAP)3",
      "type": "n8n-nodes-base.emailReadImap",
      "disabled": true,
      "position": [
        -5712,
        1760
      ],
      "parameters": {
        "options": {
          "forceReconnect": 60,
          "customEmailConfig": "[\"UNSEEN\"]"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "6a16fe30-03a2-4ad9-a918-07f10cfe7086",
      "name": "代码3",
      "type": "n8n-nodes-base.code",
      "disabled": true,
      "position": [
        -5712,
        1904
      ],
      "parameters": {
        "jsCode": "/**\n * Function Node — Normalize & Dedupe (multi-item, no require)\n * Memproses SEMUA items dari IMAP/HTML node dan mengeluarkan jumlah item yang sama.\n * Output per item:\n * { title, snippet, bodyText, slug, messageId, sentAt, fromAddress, sourceUrl, debugFields }\n */\n\n/* ---------- Helpers (dipakai di tiap item) ---------- */\nfunction toISO(d) {\n  const dt = d ? new Date(d) : new Date();\n  return isNaN(dt) ? new Date().toISOString() : dt.toISOString();\n}\nfunction slugify(s) {\n  return String(s || '')\n    .trim().toLowerCase()\n    .replace(/\\s+/g, '-')        // spasi -> -\n    .replace(/[^a-z0-9-]/g, '')  // buang non URL-safe\n    .replace(/-+/g, '-')         // rapikan multiple -\n    .replace(/^-+|-+$/g, '');    // trim - di awal/akhir\n}\nfunction limit(str, max) {\n  const s = String(str || '').replace(/\\s+/g, ' ').trim();\n  return s.length <= max ? s : s.slice(0, max - 1).trim() + '…';\n}\nfunction firstUrlFrom(text) {\n  const s = String(text || '');\n  const m = s.match(/https?:\\/\\/[^\\s<>\"'`]+/i);\n  return m ? m[0] : '';\n}\nfunction extractFromAddress(from) {\n  if (!from) return '';\n  if (typeof from === 'string') {\n    const m = from.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i);\n    return m ? m[0] : from.trim();\n  }\n  if (from.value && Array.isArray(from.value) && from.value[0]?.address) {\n    return from.value[0].address;\n  }\n  if (from.text) {\n    const m = String(from.text).match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/i);\n    return m ? m[0] : String(from.text).trim();\n  }\n  if (from.address) return String(from.address);\n  return '';\n}\nfunction stripHtmlToText(html, fallbackText = '') {\n  let h = String(html || '');\n  if (!h) return String(fallbackText || '');\n  h = h.replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n       .replace(/<style[\\s\\S]*?<\\/style>/gi, '');\n  let t = h.replace(/<\\/?[^>]+>/g, ' ');\n  return t.replace(/\\s+/g, ' ').trim();\n}\nfunction simpleHash(str) {\n  let hash = 0;\n  const s = String(str || '');\n  for (let i = 0; i < s.length; i++) {\n    hash = (hash << 5) - hash + s.charCodeAt(i);\n    hash |= 0; // 32-bit\n  }\n  return Math.abs(hash).toString(16);\n}\n\n/* ---------- PROSES SEMUA ITEM ---------- */\nconst titleMax = 140;\nconst snippetMax = 260;\n\nreturn items.map((item) => {\n  const j = item.json || {};\n\n  // 1) SUBJECT (multi-jalur)\n  const subject =\n    j.subject ??\n    j.headers?.subject ??\n    j.message?.subject ??\n    '(no subject)';\n\n  // 2) BODY (multi-jalur) — dukung hasil HTML node juga (mis. bodyText)\n  const htmlCandidates = [\n    j.bodyTextHtml,   // beberapa node\n    j.textHtml,\n    j.html,\n    j.body?.html,\n    j.message?.html,\n  ];\n  const textCandidates = [\n    j.bodyText,       // kalau HTML node menaruh hasil disini\n    j.textPlain,\n    j.text,\n    j.body?.text,\n    j.message?.text,\n  ];\n\n  const htmlSrc = htmlCandidates.find(v => v && String(v).trim().length > 0);\n  let text = textCandidates.find(v => v && String(v).trim().length > 0) || '';\n\n  if (htmlSrc) {\n    text = stripHtmlToText(htmlSrc, text);\n  } else {\n    text = String(text).replace(/\\s+/g, ' ').trim();\n  }\n\n  // 3) DATE (multi-jalur)\n  const rawDate =\n    j.date ??\n    j.internalDate ??\n    j.headers?.date ??\n    j.message?.date ??\n    new Date().toISOString();\n  const sentAt = toISO(rawDate);\n\n  // 4) FROM (multi-jalur)\n  const fromCandidate =\n    j.from ??\n    j.headers?.from ??\n    j.message?.from ??\n    '';\n  const fromAddress = extractFromAddress(fromCandidate);\n\n  // 5) Title/Slug/Snippet\n  const title = limit(String(subject || '(no subject)').trim(), titleMax);\n  const slug = slugify(title);\n  const snippet = limit(text, snippetMax);\n\n  // 6) URL pertama (opsional)\n  const sourceUrl = firstUrlFrom(text) || '';\n\n  // 7) messageId (fallback hash)\n  let messageId =\n    (j.messageId ?? j.headers?.['message-id'] ?? j.message?.messageId ?? '').toString().trim();\n  if (!messageId) {\n    messageId = simpleHash(`${title}__${sentAt}`);\n  }\n\n  // 8) Debug asal field (opsional, boleh dihapus nanti)\n  const debugFields = {\n    subjectPickedFrom: subject === j.subject ? 'subject'\n      : subject === j.headers?.subject ? 'headers.subject'\n      : subject === j.message?.subject ? 'message.subject'\n      : '(default)',\n    bodyPickedFrom: htmlSrc ? 'HTML→text'\n      : (textCandidates.find(v => v && String(v).trim().length > 0) ? 'plain text' : '(none)'),\n    datePickedFrom: rawDate === j.date ? 'date'\n      : rawDate === j.internalDate ? 'internalDate'\n      : rawDate === j.headers?.date ? 'headers.date'\n      : rawDate === j.message?.date ? 'message.date'\n      : '(default now)',\n    fromPickedFrom: typeof fromCandidate === 'string' ? '(string)'\n      : fromCandidate?.value ? 'from.value[0]'\n      : fromCandidate?.text ? 'from.text'\n      : '(unknown)',\n  };\n\n  return {\n    json: {\n      title,\n      snippet,\n      bodyText: text,\n      slug,\n      messageId,\n      sentAt,\n      fromAddress,\n      sourceUrl,\n      debugFields, // hapus kalau sudah yakin\n    }\n  };\n});\n"
      },
      "typeVersion": 2
    },
    {
      "id": "0878f213-7ea0-4c16-98fd-2f680aa72254",
      "name": "执行 SQL 查询3",
      "type": "n8n-nodes-base.postgres",
      "disabled": true,
      "position": [
        -5712,
        2064
      ],
      "parameters": {
        "query": "SELECT EXISTS(\n  SELECT 1\n  FROM email_kb_index\n  WHERE message_id = '{{ $json.messageId }}'\n) AS exists;\n",
        "options": {},
        "operation": "executeQuery"
      },
      "typeVersion": 2.6
    },
    {
      "id": "e0b2d5c4-c3bf-4025-a56f-bd8123eaf6c2",
      "name": "如果3",
      "type": "n8n-nodes-base.if",
      "disabled": true,
      "position": [
        -5712,
        2224
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "086a03b2-23c7-4a90-904e-420bbd480a0a",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              },
              "leftValue": "={{ $json.exists }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "56809d81-55f3-45b5-baaa-116378c4bd25",
      "name": "创建数据库页面3",
      "type": "n8n-nodes-base.notion",
      "disabled": true,
      "position": [
        -5024,
        1840
      ],
      "parameters": {
        "title": "={{ $('Code2').item.json.title }}",
        "options": {},
        "resource": "databasePage",
        "databaseId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultUrl": "",
          "cachedResultName": "Email Knowledge Base"
        },
        "propertiesUi": {
          "propertyValues": [
            {
              "key": "date|date",
              "date": "={{ $('Code2').item.json.sentAt }}"
            },
            {
              "key": "summary|rich_text",
              "textContent": "={{ $('Code2').item.json.snippet }}"
            },
            {
              "key": "sourceUrl|url",
              "urlValue": "={{ $('Code2').item.json.sourceUrl }}",
              "ignoreIfEmpty": true
            },
            {
              "key": "From|rich_text",
              "textContent": "={{ $('Code2').item.json.fromAddress }}"
            },
            {
              "key": "Slug|rich_text",
              "textContent": "={{ $('Code2').item.json.slug }}"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "48463d2d-bba3-4d85-99a5-4ca217c91a3a",
      "name": "发送短信3",
      "type": "n8n-nodes-base.telegram",
      "disabled": true,
      "position": [
        -5040,
        2080
      ],
      "webhookId": "",
      "parameters": {
        "additionalFields": {}
      },
      "typeVersion": 1.2
    }
  ],
  "pinData": {},
  "connections": {
    "If": {
      "main": [
        [
          {
            "node": "Create a database page",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If2": {
      "main": [
        [
          {
            "node": "Create a database page2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code": {
      "main": [
        [
          {
            "node": "Execute a SQL query",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code1": {
      "main": [
        []
      ]
    },
    "Code2": {
      "main": [
        [
          {
            "node": "Execute a SQL query2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute a SQL query": {
      "main": [
        [
          {
            "node": "If",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email Trigger (IMAP)": {
      "main": [
        [
          {
            "node": "Code",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute a SQL query1": {
      "main": [
        []
      ]
    },
    "Execute a SQL query2": {
      "main": [
        [
          {
            "node": "If2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email Trigger (IMAP)1": {
      "main": [
        []
      ]
    },
    "Email Trigger (IMAP)2": {
      "main": [
        [
          {
            "node": "Code2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create a database page": {
      "main": [
        [
          {
            "node": "Send a text message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create a database page1": {
      "main": [
        [
          {
            "node": "Send a text message1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create a database page2": {
      "main": [
        [
          {
            "node": "Send a text message2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create a database page3": {
      "main": [
        [
          {
            "node": "Send a text message3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
常见问题

如何使用这个工作流?

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

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

高级 - 内部知识库, 多模态 AI

需要付费吗?

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

工作流信息
难度等级
高级
节点数量28
分类2
节点类型7
难度说明

适合高级用户,包含 16+ 个节点的复杂工作流

作者
Ariyanto Catur Pamungkas

Ariyanto Catur Pamungkas

@shioon
外部链接
在 n8n.io 查看

分享此工作流