hello guys i want to build an workflow that sort my email in different folder, for that i decided to build an ai that help me to defnie the best ctagorie for each mail i recieve but the problem is it does not work very well any ideas ?{
“nodes”: [
{
“parameters”: {
“options”: {}
},
“type”: “n8n-nodes-base.emailReadImap”,
“typeVersion”: 2.2,
“position”: [
-1920,
-352
],
“id”: “b5a3e306-0af1-44a2-964c-263c2131fcdd”,
“name”: “Email Trigger (IMAP)”,
“credentials”: {
“imap”: {
“id”: “yxFUHY5GyTLBllPr”,
“name”: “IMAP account”
}
}
},
{
“parameters”: {
“jsCode”: “const maxLength = 5000;\n\nreturn $input.all().map((item) => {\n let text =\n item.json.htmlOrBody ||\n item.json.textHtml ||\n item.json.html ||\n item.json.textPlain ||\n item.json.text ||\n item.json.textBody ||\n ‘’;\n\n text = text.replace(/<style[^>]>[\s\S]?<\/style>/gi, ‘’);\n text = text.replace(/<script[^>]>[\s\S]?<\/script>/gi, ‘’);\n text = text.replace(/<[^>]+>/g, ’ ');\n text = text.replace(/ /gi, ’ ');\n text = text.replace(/&/gi, ‘&’);\n text = text.replace(/</gi, ‘<’);\n text = text.replace(/>/gi, ‘>’);\n text = text.replace(/\s+/g, ’ ').trim();\n\n if (text.length > maxLength) {\n text = text.substring(0, maxLength) + ‘… [tronque]’;\n }\n\n return {\n json: {\n …item.json,\n cleanText: text,\n email_uid_safe:\n item.json.uid ??\n item.json.messageUid ??\n item.json.attributes?.uid ??\n null\n }\n };\n});\n”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
-592,
-128
],
“id”: “66504230-af8e-48a6-b939-f2217f5654d8”,
“name”: “clean text”
},
{
“parameters”: {
“resource”: “document”,
“modelId”: {
“__rl”: true,
“value”: “models/gemini-3.1-flash-lite”,
“mode”: “list”,
“cachedResultName”: “models/gemini-3.1-flash-lite”
},
“text”: “=Tu es un moteur de classification automatique d’e-mails.\n\nTa seule mission est de classer l’e-mail fourni dans UNE seule categorie autorisee.\n\n==================================================\n1. FORMAT DE SORTIE OBLIGATOIRE\n==================================================\n\nTu dois repondre uniquement avec un JSON valide, sans aucun texte avant ou apres.\n\nFormat exact autorise :\n\n{“category”:“spam”}\n\nRemplace seulement la valeur “spam” par la bonne categorie.\n\nLa valeur de “category” doit etre strictement l’une des valeurs suivantes, en minuscules exactes :\n\n- spam\n- important\n- professionnel\n- personnel\n- promotion\n- newsletter\n- notification\n- transaction\n- support\n- recrutement\n- autre\n\nInterdictions absolues :\n- ne retourne jamais autre chose qu’un JSON ;\n- ne pose jamais de question ;\n- ne demande jamais d’information supplementaire ;\n- n’ajoute jamais d’explication ;\n- n’ajoute jamais de markdown ;\n- n’ajoute jamais de bloc de code ;\n- n’invente jamais une categorie ;\n- ne retourne jamais plusieurs categories ;\n- ne retourne jamais “autres”, “inconnu” ou “indetermine”.\n\nSi des informations manquent, tu dois quand meme choisir la categorie la plus probable.\n\n==================================================\n2. PRINCIPE DE DECISION\n==================================================\n\nChoisis la categorie qui correspond le mieux a l’intention principale du message.\n\nTu dois analyser ensemble :\n- l’expediteur ;\n- l’objet ;\n- le contenu ;\n- les liens mentionnes ;\n- les pieces jointes mentionnees ;\n- le ton ;\n- l’action demandee ;\n- les indices d’automatisation ;\n- les indices de fraude, d’urgence artificielle ou d’envoi massif.\n\nLa categorie “autre” est un dernier recours.\nNe choisis “autre” que si aucune autre categorie ne convient raisonnablement.\n\n==================================================\n3. PRIORITE EN CAS D’HESITATION\n==================================================\n\nSi plusieurs categories semblent plausibles, utilise cet ordre de priorite :\n\n1. spam\n2. important\n3. transaction\n4. support\n5. recrutement\n6. professionnel\n7. personnel\n8. promotion\n9. newsletter\n10. notification\n11. autre\n\n==================================================\n4. DEFINITIONS DES CATEGORIES\n==================================================\n\nspam :\nMessage frauduleux, trompeur, malveillant, suspect, phishing, arnaque, usurpation, faux paiement, faux support, faux colis, faux cadeau, demande sensible illegitime, pression artificielle, lien suspect, piece jointe suspecte, envoi massif douteux.\n\nimportant :\nMessage legitime demandant une attention prioritaire ou une action rapide credible : incident critique, echeance proche, blocage important, alerte authentique serieuse, demande urgente d’un interlocuteur fiable, probleme ayant un fort impact.\n\nprofessionnel :\nEchange lie au travail sans relever d’une categorie plus precise : projet, client, reunion, compte rendu, devis, collaboration, document de travail, validation non urgente, demande professionnelle generale.\n\npersonnel :\nEchange prive entre proches ou connaissances : famille, amis, invitation personnelle, organisation privee, nouvelles personnelles, photos, message informel hors cadre professionnel.\n\npromotion :\nMessage commercial legitime dont le but principal est de vendre : reduction, offre limitee, code promo, panier, campagne marketing, lancement produit, ventes privees, relance commerciale.\n\nnewsletter :\nContenu editorial ou informatif envoye regulierement : lettre d’information, digest, resume, actualites, selection d’articles, veille, bulletin communautaire.\n\nnotification :\nMessage automatique informant d’un evenement ou d’une activite : connexion, commentaire, mention, rappel, mise a jour, alerte applicative, modification de parametre, message systeme non transactionnel.\n\ntransaction :\nMessage legitime lie a une operation precise : facture, recu, paiement, remboursement, commande, expedition, reservation, renouvellement, abonnement, livraison, confirmation bancaire.\n\nsupport :\nDemande ou suivi d’assistance : ticket, incident, probleme technique, service client, demande d’aide, diagnostic, resolution, reponse support.\n\nrecrutement :\nMessage lie a l’emploi ou a l’embauche : candidature, CV, entretien, offre d’emploi, recruteur, test technique, disponibilite pour un poste.\n\nautre :\nA utiliser uniquement si le contenu est trop pauvre, vide, incomprehensible, ou ne correspond raisonnablement a aucune categorie ci-dessus.\n\n==================================================\n5. DISTINCTIONS IMPORTANTES\n==================================================\n\n- Publicite legitime = promotion ; publicite frauduleuse ou tres suspecte = spam.\n- Contenu editorial recurrent = newsletter ; contenu principalement commercial = promotion.\n- Activite de compte ou d’application = notification ; achat, facture, commande, paiement, livraison = transaction.\n- Discussion de travail generale = professionnel ; demande d’assistance ou suivi de probleme = support.\n- Sujet emploi ou candidature = recrutement.\n- Une simple mention du mot “urgent” ne suffit pas a classer en important.\n- Un expéditeur inconnu n’est pas automatiquement du spam.\n- Un message mal ecrit n’est pas automatiquement du spam.\n\n==================================================\n6. VERIFICATION FINALE OBLIGATOIRE\n==================================================\n\nAvant de repondre :\n- verifie que la sortie est un JSON valide ;\n- verifie que “category” existe ;\n- verifie que sa valeur est exactement l’une des categories autorisees ;\n- si ce n’est pas le cas, corrige avant de repondre.\n\n==================================================\n7. E-MAIL A CLASSER\n==================================================\n\nSujet : {{ $json.subject || “” }}\nExpediteur : {{ $json.from || “” }}\nDate : {{ $json.date || “” }}\nContenu : {{ $json.cleanText || “” }}\n”,
“options”: {}
},
“type”: “@n8n/n8n-nodes-langchain.googleGemini”,
“typeVersion”: 1.2,
“position”: [
-304,
-176
],
“id”: “f3ad79ab-7fab-4156-8338-f0eccd74cb86”,
“name”: “analyze email”,
“credentials”: {
“googlePalmApi”: {
“id”: “HMtO75ETE70NhaCg”,
“name”: “Google Gemini(PaLM) Api account”
}
}
},
{
“parameters”: {
“mode”: “insert”,
“pineconeIndex”: {
“__rl”: true,
“value”: “email-memory-3072”,
“mode”: “list”,
“cachedResultName”: “email-memory-3072”
},
“options”: {}
},
“type”: “@n8n/n8n-nodes-langchain.vectorStorePinecone”,
“typeVersion”: 1.3,
“position”: [
656,
-640
],
“id”: “269fa6ca-29bd-48e3-abf6-3575525b3d9a”,
“name”: “Pinecone Vector Store”,
“credentials”: {
“pineconeApi”: {
“id”: “wkAWosNv9JzN9AJN”,
“name”: “Pinecone account”
}
}
},
{
“parameters”: {
“options”: {}
},
“type”: “@n8n/n8n-nodes-langchain.documentDefaultDataLoader”,
“typeVersion”: 1.1,
“position”: [
784,
-480
],
“id”: “b829758f-a6cd-46b2-9ee8-73af8e86cb9b”,
“name”: “Default Data Loader”
},
{
“parameters”: {},
“type”: “@n8n/n8n-nodes-langchain.embeddingsGoogleGemini”,
“typeVersion”: 1,
“position”: [
608,
-480
],
“id”: “3d0f7a70-d2b6-4948-b767-98456ef54739”,
“name”: “Embeddings Google Gemini”,
“credentials”: {
“googlePalmApi”: {
“id”: “HMtO75ETE70NhaCg”,
“name”: “Google Gemini(PaLM) Api account”
}
}
},
{
“parameters”: {
“jsCode”: “return $input.all().map((item) => {\n const metadata = {\n source: “email”,\n from: item.json.from ?? “”,\n subject: item.json.subject ?? “”,\n translated_subject: item.json.translated_subject ?? “”,\n date: item.json.date ?? “”,\n language: item.json.language ?? “inconnu”,\n mail_type: item.json.mail_type ?? “autres”,\n importance: item.json.importance ?? “normal”,\n sender_type: item.json.sender_type ?? “inconnu”,\n short_summary: item.json.short_summary ?? “”,\n key_entities: Array.isArray(item.json.key_entities) ? item.json.key_entities : ,\n target_folder: item.json.target_folder ?? “INBOX.autres”,\n ai_parse_error: item.json.ai_parse_error ?? false,\n thread_hint: `${item.json.from ?? “”}|${item.json.subject ?? “”}`.toLowerCase(),\n };\n\n const pageContent = `Type: email\nExpediteur: ${item.json.from ?? “”}\nSujet original: ${item.json.subject ?? “”}\nSujet traduit: ${item.json.translated_subject ?? “”}\nDate: ${item.json.date ?? “”}\nLangue: ${item.json.language ?? “”}\nType de mail: ${item.json.mail_type ?? “”}\nImportance: ${item.json.importance ?? “”}\nType d’expediteur: ${item.json.sender_type ?? “”}\nDossier cible: ${item.json.target_folder ?? “”}\nResume: ${item.json.short_summary ?? “”}\nEntites: ${Array.isArray(item.json.key_entities) ? item.json.key_entities.join(”, “) : “”}\n\nContenu traduit:\n${item.json.translated_content ?? “”}\n\nContenu original nettoye:\n${item.json.cleanText ?? “”}`;\n\n return {\n json: {\n …item.json,\n pageContent,\n metadata\n }\n };\n});\n”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
464,
-544
],
“id”: “831ae1b6-fffc-4269-ae9d-8d500e16624c”,
“name”: “prepare pinecode”
},
{
“parameters”: {
“jsCode”: “return $input.all().map((item) => ({\n json: {\n full_json: item.json,\n top_level_keys: Object.keys(item.json),\n attributes: item.json.attributes ?? null,\n messageUid: item.json.messageUid ?? null,\n uid: item.json.uid ?? null,\n messageId: item.json.messageId ?? null,\n seq: item.json.seq ?? null,\n path: item.json.path ?? null,\n mailbox: item.json.mailbox ?? null\n }\n}));\n”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
-1424,
-288
],
“id”: “58806387-227e-44a6-9cb9-6b3ba7257c38”,
“name”: “Code in JavaScript1”
},
{
“parameters”: {
“authentication”: “coreImapAccount”,
“resource”: “email”,
“operation”: “moveEmail”,
“sourceMailbox”: {
“__rl”: true,
“mode”: “list”,
“value”: “INBOX”
},
“emailUid”: “=={{ ($json.email_uid_safe ?? $json.uid ?? $json.messageUid ?? ‘’).toString().trim() }}\n”,
“destinationMailbox”: {
“__rl”: true,
“value”: “INBOX.spam”,
“mode”: “path”
}
},
“type”: “n8n-nodes-imap.imap”,
“typeVersion”: 1,
“position”: [
1104,
-352
],
“id”: “3ee4778e-0118-4ea1-9ee1-789bbf5dcea6”,
“name”: “spam”,
“credentials”: {
“imap”: {
“id”: “yxFUHY5GyTLBllPr”,
“name”: “IMAP account”
}
}
},
{
“parameters”: {
“authentication”: “coreImapAccount”,
“resource”: “email”,
“operation”: “moveEmail”,
“sourceMailbox”: {
“__rl”: true,
“mode”: “list”,
“value”: “INBOX”
},
“emailUid”: “=={{ ($json.email_uid_safe ?? $json.uid ?? $json.messageUid ?? $json.attributes?.uid ?? ‘’).toString().trim() }}\n”,
“destinationMailbox”: {
“__rl”: true,
“value”: “INBOX.autre”,
“mode”: “path”
}
},
“type”: “n8n-nodes-imap.imap”,
“typeVersion”: 1,
“position”: [
1104,
-208
],
“id”: “7c8173de-8498-4598-9c1a-d3fc65f1effc”,
“name”: “autres”,
“credentials”: {
“imap”: {
“id”: “yxFUHY5GyTLBllPr”,
“name”: “IMAP account”
}
}
},
{
“parameters”: {
“authentication”: “coreImapAccount”,
“resource”: “email”,
“operation”: “moveEmail”,
“sourceMailbox”: {
“__rl”: true,
“mode”: “list”,
“value”: “INBOX”
},
“emailUid”: “=={{ ($json.email_uid_safe ?? $json.uid ?? $json.messageUid ?? ‘’).toString().trim() }}\n”,
“destinationMailbox”: {
“__rl”: true,
“value”: “INBOX.autres_urgent”,
“mode”: “path”
}
},
“type”: “n8n-nodes-imap.imap”,
“typeVersion”: 1,
“position”: [
1104,
-64
],
“id”: “b4cf771b-e1d4-4f7d-9ffd-ad7120edc9a7”,
“name”: “autres_urgent”,
“credentials”: {
“imap”: {
“id”: “yxFUHY5GyTLBllPr”,
“name”: “IMAP account”
}
}
},
{
“parameters”: {
“authentication”: “coreImapAccount”,
“resource”: “email”,
“operation”: “moveEmail”,
“sourceMailbox”: {
“__rl”: true,
“mode”: “list”,
“value”: “INBOX”
},
“emailUid”: “=={{ ($json.email_uid_safe ?? $json.uid ?? $json.messageUid ?? ‘’).toString().trim() }}\n”,
“destinationMailbox”: {
“__rl”: true,
“value”: “INBOX.client_faible”,
“mode”: “path”
}
},
“type”: “n8n-nodes-imap.imap”,
“typeVersion”: 1,
“position”: [
1104,
96
],
“id”: “a30e2d01-07b9-4840-ae5f-124cb128f524”,
“name”: “client_faible”,
“credentials”: {
“imap”: {
“id”: “yxFUHY5GyTLBllPr”,
“name”: “IMAP account”
}
}
},
{
“parameters”: {
“authentication”: “coreImapAccount”,
“resource”: “email”,
“operation”: “moveEmail”,
“sourceMailbox”: {
“__rl”: true,
“mode”: “list”,
“value”: “INBOX”
},
“emailUid”: “=={{ ($json.email_uid_safe ?? $json.uid ?? $json.messageUid ?? ‘’).toString().trim() }}\n”,
“destinationMailbox”: {
“__rl”: true,
“value”: “INBOX.client_normal”,
“mode”: “path”
}
},
“type”: “n8n-nodes-imap.imap”,
“typeVersion”: 1,
“position”: [
1104,
256
],
“id”: “54abead4-628a-414d-8efd-4153fe875f85”,
“name”: “client_normal”,
“credentials”: {
“imap”: {
“id”: “yxFUHY5GyTLBllPr”,
“name”: “IMAP account”
}
}
},
{
“parameters”: {
“authentication”: “coreImapAccount”,
“resource”: “email”,
“operation”: “moveEmail”,
“sourceMailbox”: {
“__rl”: true,
“mode”: “list”,
“value”: “INBOX”
},
“emailUid”: “=={{ ($json.email_uid_safe ?? $json.uid ?? $json.messageUid ?? ‘’).toString().trim() }}\n”,
“destinationMailbox”: {
“__rl”: true,
“value”: “INBOX.client_urgent”,
“mode”: “path”
}
},
“type”: “n8n-nodes-imap.imap”,
“typeVersion”: 1,
“position”: [
1104,
400
],
“id”: “6c4fdfdd-c40e-482d-bf59-309787b8c011”,
“name”: “client_urgent”,
“credentials”: {
“imap”: {
“id”: “yxFUHY5GyTLBllPr”,
“name”: “IMAP account”
}
}
},
{
“parameters”: {
“authentication”: “coreImapAccount”,
“resource”: “email”,
“operation”: “moveEmail”,
“sourceMailbox”: {
“__rl”: true,
“mode”: “list”,
“value”: “INBOX”
},
“emailUid”: “=={{ ($json.email_uid_safe ?? $json.uid ?? $json.messageUid ?? ‘’).toString().trim() }}\n”,
“destinationMailbox”: {
“__rl”: true,
“value”: “INBOX.newsletter”,
“mode”: “path”
}
},
“type”: “n8n-nodes-imap.imap”,
“typeVersion”: 1,
“position”: [
1104,
560
],
“id”: “0db03ac6-3a98-4692-806d-b0fd5ed9877e”,
“name”: “newsletter”,
“credentials”: {
“imap”: {
“id”: “yxFUHY5GyTLBllPr”,
“name”: “IMAP account”
}
}
},
{
“parameters”: {
“jsCode”: “const analyses = $input.all();\nconst emails = $(‘clean text’).all();\n\nreturn analyses.map((analysisItem, index) => {\n const email = emails[index]?.json ?? {};\n\n const rawAi =\n analysisItem.json?.output ??\n analysisItem.json?.text ??\n analysisItem.json?.content ??\n analysisItem.json?.response ??\n analysisItem.json ??\n {};\n\n let parsedAi = {};\n\n if (typeof rawAi === ‘string’) {\n const cleaned = rawAi\n .replace(/^```json\s*/i, ‘’)\n .replace(/^```\s*/i, ‘’)\n .replace(/\s*```$/i, ‘’)\n .trim();\n\n try {\n parsedAi = JSON.parse(cleaned);\n } catch {\n parsedAi = {\n category: cleaned || ‘autre’,\n ai_raw_output: rawAi,\n ai_parse_error: true,\n };\n }\n } else if (rawAi && typeof rawAi === ‘object’) {\n parsedAi = rawAi;\n }\n\n let rawCategory = String(\n parsedAi.category ??\n parsedAi.target_folder_key ??\n parsedAi.mail_type ??\n parsedAi.target_folder ??\n ‘autre’\n )\n .trim()\n .toLowerCase()\n .normalize(‘NFD’)\n .replace(/[\u0300-\u036f]/g, ‘’);\n\n const allowedCategories = new Set([\n ‘spam’,\n ‘important’,\n ‘professionnel’,\n ‘personnel’,\n ‘promotion’,\n ‘newsletter’,\n ‘notification’,\n ‘transaction’,\n ‘support’,\n ‘recrutement’,\n ‘autre’\n ]);\n\n if (!allowedCategories.has(rawCategory)) {\n rawCategory = ‘autre’;\n }\n\n const categoryMap = {\n spam: ‘spam’,\n important: ‘autres_urgent’,\n professionnel: ‘client_normal’,\n personnel: ‘autres’,\n promotion: ‘newsletter’,\n newsletter: ‘newsletter’,\n notification: ‘autres’,\n transaction: ‘client_normal’,\n support: ‘client_normal’,\n recrutement: ‘recrutement’,\n autre: ‘autres’,\n };\n\n const emailUid =\n email.email_uid_safe ??\n email.uid ??\n email.messageUid ??\n email.attributes?.uid ??\n null;\n\n return {\n json: {\n …email,\n …parsedAi,\n email_uid_safe: emailUid != null ? String(emailUid).trim() : null,\n ai_category_original: rawCategory,\n target_folder_key: categoryMap[rawCategory] ?? ‘autres’,\n debug_has_email: Object.keys(email).length > 0,\n debug_ai_type: typeof rawAi,\n debug_email_keys: Object.keys(email),\n debug_ai_keys: parsedAi && typeof parsedAi === ‘object’ ? Object.keys(parsedAi) : ,\n }\n };\n});\n”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
32,
-160
],
“id”: “0dcc8d69-bc35-4dc4-89ae-f3aa17d4e47b”,
“name”: “Code in JavaScript”
},
{
“parameters”: {
“jsCode”: “return $input.all().map((item, index) => ({\n json: {\n index,\n allKeys: Object.keys(item.json || {}),\n fullItem: item.json,\n email_uid_safe: item.json?.email_uid_safe ?? null,\n uid: item.json?.uid ?? null,\n messageUid: item.json?.messageUid ?? null,\n subject: item.json?.subject ?? null,\n from: item.json?.from ?? null,\n target_folder_key: item.json?.target_folder_key ?? null,\n category: item.json?.category ?? null\n }\n}));\n”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
832,
-208
],
“id”: “0d0a7184-3080-40dd-99a6-22dd15f0506e”,
“name”: “Code in JavaScript2”
},
{
“parameters”: {
“rules”: {
“values”: [
{
“conditions”: {
“options”: {
“caseSensitive”: true,
“leftValue”: “”,
“typeValidation”: “strict”,
“version”: 3
},
“conditions”: [
{
“leftValue”: “=={{ $json.target_folder_key }}”,
“rightValue”: “autres”,
“operator”: {
“type”: “string”,
“operation”: “equals”
},
“id”: “3a244d14-3687-47fd-a6fc-8304e81925d1”
}
],
“combinator”: “and”
}
}
]
},
“options”: {}
},
“type”: “n8n-nodes-base.switch”,
“typeVersion”: 3.4,
“position”: [
256,
-160
],
“id”: “dd3161f7-62d3-4ccd-b76f-a8ea77839404”,
“name”: “Switch”
}
],
“connections”: {
“Email Trigger (IMAP)”: {
“main”: [
[
{
“node”: “Code in JavaScript1”,
“type”: “main”,
“index”: 0
}
]
]
},
“clean text”: {
“main”: [
[
{
“node”: “analyze email”,
“type”: “main”,
“index”: 0
}
]
]
},
“analyze email”: {
“main”: [
[
{
“node”: “prepare pinecode”,
“type”: “main”,
“index”: 0
},
{
“node”: “Code in JavaScript”,
“type”: “main”,
“index”: 0
}
]
]
},
“Default Data Loader”: {
“ai_document”: [
[
{
“node”: “Pinecone Vector Store”,
“type”: “ai_document”,
“index”: 0
}
]
]
},
“Embeddings Google Gemini”: {
“ai_embedding”: [
[
{
“node”: “Pinecone Vector Store”,
“type”: “ai_embedding”,
“index”: 0
}
]
]
},
“prepare pinecode”: {
“main”: [
[
{
“node”: “Pinecone Vector Store”,
“type”: “main”,
“index”: 0
}
]
]
},
“Code in JavaScript1”: {
“main”: [
[
{
“node”: “clean text”,
“type”: “main”,
“index”: 0
}
]
]
},
“Code in JavaScript”: {
“main”: [
[
{
“node”: “Switch”,
“type”: “main”,
“index”: 0
}
]
]
},
“Code in JavaScript2”: {
“main”: [
[
{
“node”: “autres”,
“type”: “main”,
“index”: 0
}
]
]
},
“Switch”: {
“main”: [
[
{
“node”: “Code in JavaScript2”,
“type”: “main”,
“index”: 0
}
]
]
}
},
“pinData”: {},
“meta”: {
“templateCredsSetupCompleted”: true,
“instanceId”: “5727c71c8d6802df061f9cc93794a4c9181d34ba116d2c40a8e91ff9407a367d”
}
}
Hi @bjornlebon Welcome!
Drop the hand written prompt and the JSON parsing and use the Text Classifier node instead. You give it a name and a description per category, it gives you one output branch per category, and each branch wires straight into its own IMAP move node, so the Switch, the fence stripping, and the category map in the Code node all disappear. Set “When No Clear Match” to the extra Other branch and that becomes your autres folder.
Your current wiring is part of it too, the Switch only has a rule for autres and the other six move nodes have nothing connected to them, so nothing else can move whatever the model decides.
On accuracy, important is an urgency level rather than a type, so it overlaps with all ten other categories and the model has to guess which axis you meant. Keep the list to one axis and do urgency as a second pass.
Welcome to the n8n community @bjornlebon!
I recommend fixing the email data loss first and having the AI return the destination folder directly, then using the move email node afterward. The JavaScript Code node1 puts the original email inside full_json, but the next node looks for subject, from, and email body at the top level, so the AI might be receiving empty or incomplete data. I would simplify by removing that node, connecting IMAP directly to text processing, and having the AI return the destination folder already; this way you can use a single move node and eliminate the Switch, category mapping, and most of the code. I’d also leave Pinecone out for now, since it’s storing the emails but isn’t being queried to help with classification.
Both answers above are right, and the Text Classifier suggestion will delete most of your code. One thing neither covers, which will bite you as soon as the sorting starts working.
IMAP UIDs are per folder, not per message. When you move an email into Promotions it gets a new UID there, and the old one is gone. So email_uid_safe identifies the message only until the workflow succeeds, and any log or dedupe keyed on it points at nothing afterwards. That fallback chain you wrote across uid, messageUid and attributes.uid is a sign the identifier itself is the problem rather than which field holds it.
Use the Message-ID header instead. It is assigned by the sending server, it survives the move, and it is the same value if you ever reprocess the mailbox from another client. Keep the UID only for the move operation itself, in the same execution that read it.
One more on accuracy, building on the point about important being an urgency rather than a type: with eleven categories on two mixed axes the model has to guess which axis you meant, and it will guess differently for similar mails. Cutting to five or six single-axis categories will do more for your results than any prompt change.