Guidechecked
n8n with AI
Building n8n workflows that use AI to sort emails, read data from documents and suggest replies. Including installation, error handling, data protection and operations.
What n8n is
n8n is an automation tool. A workflow consists of nodes that you connect on a canvas in the browser. Each node does one thing: fetch emails, call an API, reshape data or ask a language model. A workflow always starts with a trigger, the event that starts it, such as a new email, a schedule or a webhook. You can run n8n yourself (self-hosting) or use the paid n8n Cloud service. With self-hosting, workflows and data stay on your server, but you handle updates and backups yourself.
Requirements
To get started, a computer or small server with Docker is enough. Without Docker you can also use Node.js, according to the docs in a version between 20.19 and 24.x. You also need:
- An API key from an AI provider, for example Anthropic or OpenAI. You are billed per use.
- Access to the mailbox you want to process: IMAP details or a Google account for Gmail.
Installation
The quickest way to start n8n is with Docker. The n8n_data volume stores workflows, credentials and the key n8n uses to encrypt the credentials. Then open http://localhost:5678 and create the first account. For a permanent server the docs recommend Docker Compose. For a quick test without Docker, npx n8n is enough.
docker volume create n8n_data
docker run -it --rm \
--name n8n \
-p 5678:5678 \
-e GENERIC_TIMEZONE="Europe/Berlin" \
-e TZ="Europe/Berlin" \
-e N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true \
-v n8n_data:/home/node/.n8n \
n8nio/n8n
# Without Docker, for testing only (Node.js 20.19 to 24.x)
npx n8nCaution:n8n is licensed under the Sustainable Use License, a so-called fair-code licence. You may use n8n freely for internal purposes in your own business. You may not sell n8n as a product or service whose value comes substantially from n8n, such as hosted n8n for customers. If in doubt, read the licence itself.
First workflow and expressions
Each node receives data as a list of entries (items) and passes on a new list. You access this data with expressions. An expression is written in double curly braces. $json means the current item; $('Node name') fetches data from an earlier node.
- Create a new workflow and choose a trigger as the first node, for example Schedule Trigger.
- Use the plus on the node to add the next node, such as Edit Fields (Set), and define fields there.
- Test a single node with Execute step. The input is shown on the left, the output on the right.
- Drag fields from the input into a parameter field. n8n then writes the matching expression.
{{ $json.subject }}
{{ $('Email Trigger (IMAP)').item.json.from }}
{{ $now.toFormat('yyyy-MM-dd') }}
{{ $json.textPlain.slice(0, 4000) }} // shorten text, saves tokensTip:Which fields a node returns depends on the node and its settings. Always check the names in the output of a test run instead of guessing them.
Storing credentials safely
In n8n, passwords and API keys belong in credentials, never directly in a node or expression. n8n encrypts them in the database. n8n generates the key for this on first start and stores it in the .n8n folder. Alternatively, you set it yourself with the N8N_ENCRYPTION_KEY variable. If this key is lost, n8n can no longer decrypt stored credentials.
Caution:Exported workflows contain credential names and IDs. HTTP Request nodes imported from a cURL command can even contain auth headers. Check and clean them before sharing.
The AI nodes
The AI nodes in n8n consist of a root node and attached sub-nodes. The root node defines the task; the chat model sub-node decides the language model, for example Anthropic Chat Model, OpenAI Chat Model or Ollama Chat Model for a local model. For everyday use, these root nodes are usually enough:
- Text Classifier: assigns a text to fixed categories. Each category has a name and a description.
- Information Extractor: reads specific fields from a text, such as invoice number and amount from a PDF whose text was first provided by Extract from File.
- Basic LLM Chain: a single prompt with a response, good for summaries and reply drafts.
- AI Agent: the model decides on its own which attached tools it calls. Powerful, but harder to predict.
Tip:I use the simplest node that solves the task. For a fixed classification, Text Classifier is more reliable and cheaper than an agent.
Example: sorting incoming email
Goal: every new email is read, assigned to a category and processed further depending on the category. Nothing is sent automatically; the AI only writes drafts.
- Trigger: Email Trigger (IMAP) with an IMAP credential, mailbox name INBOX and action None so the email stays unread. For Gmail, Gmail Trigger works too.
- Attach a Text Classifier. Input prompt: subject and shortened text via expression. Create categories such as Inquiry, Invoice, Appointment and Newsletter, each with a clear description.
- Under When No Clear Match, choose Output on Extra, 'Other' Branch. Unclear emails then go to their own branch instead of being discarded.
- Inquiry branch: a Basic LLM Chain writes a reply draft, which you save as a draft, for example with the Gmail node.
- Invoice branch: an Information Extractor reads invoice number, amount and due date and creates a task from them.
- Other branch: a notification to you so a human decides.
Caution:Emails are external input. A sender can write instructions to the AI into the text (prompt injection). That is why the AI here only outputs categories and drafts and never triggers actions such as sending or deleting.
Checking structured output
For the following nodes to work reliably, the AI should return fixed JSON instead of free text. In the Basic LLM Chain, turn on Require Specific Output Format and attach a Structured Output Parser. You generate the schema from a JSON example or write it yourself as JSON Schema. Information Extractor offers the same options directly in the node.
- After the AI node, use an If node to check that required fields are filled and values are plausible, for example amount greater than zero.
- Fallback: if the check fails or the AI reports sicher = false, the item goes to a human instead of continuing automatically.
{
"type": "object",
"properties": {
"rechnungsnummer": { "type": "string" },
"betrag": { "type": "number" },
"faellig_am": { "type": "string", "description": "Datum im Format YYYY-MM-DD" },
"sicher": { "type": "boolean" }
},
"required": ["rechnungsnummer", "betrag", "sicher"]
}Error handling
AI providers have outages and rate limits. A workflow must handle them without losing emails. n8n offers two levels for this: settings on the individual node and an error workflow for the whole process.
- On the AI node, turn on Retry On Fail under Settings. Max. Tries and Wait Between Tries set the number of attempts and the delay between them.
- Under On Error, choose Continue (using error output) if failed items should take their own path instead of stopping the whole run.
- Create a separate workflow starting with the Error Trigger node that notifies you. It receives, among other things, the error message, the last node and a link to the execution.
- In the monitored workflow, enter this workflow under Settings as the error workflow. One error workflow can cover several workflows.
Costs and data protection
Even with self-hosted n8n, everything you put into a prompt leaves your server and goes to the AI provider. With emails this is almost always personal data. Under the GDPR you need a legal basis for this and a data processing agreement with the provider. Also check where the provider processes the data. Costs depend on tokens, that is, the amount of text sent and returned.
- Only send what the task needs. For classification, subject and the first paragraphs are usually enough.
- Redact first: a Code node replaces IBANs, phone numbers and email addresses with placeholders, for example.
- For very sensitive data, use a local model via Ollama Chat Model. The text then stays in your own network.
- Set a spending limit with the provider so a loop cannot create a large bill.
// Code node, Mode: Run Once for Each Item
const t = $json.textPlain ?? '';
$json.textPlain = t
.replace(/[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){3,7}(?: ?[A-Z0-9]{1,3})?/g, '[IBAN]')
.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g, '[EMAIL]')
.replace(/\+?\d[\d /-]{7,}\d/g, '[PHONE]');
return $json;Caution:Rules like these do not catch everything; names and addresses, for example, remain. Redaction lowers the risk but does not replace a legal review.
Operations: updates, backups, logs
A self-hosted n8n needs maintenance. I stick to a fixed routine: back up first, then update, then check. Executions shows every run with the data of each node; that is the first place to look when there are problems. Keep in mind that email content is stored there too.
# Backup: one JSON per workflow and credential (encrypted)
n8n export:workflow --backup --output=backups/latest/
n8n export:credentials --backup --output=backups/latest/
# Update with Docker
docker pull n8nio/n8n
# Stop the container and restart it with the same volume
# View logs
docker logs -f n8nCaution:Exported credentials can only be decrypted again with the same key. So always back up the whole volume including the .n8n folder. The --decrypted option writes all secrets to the file in plain text; use it only for a migration and delete the file afterwards.
Common problems and fixes
These are the cases you will run into most often:
- Expression returns undefined: wrong field name, or the node has no test data yet. Run the previous node once and insert the field by drag and drop.
- Text Classifier discards emails: When No Clear Match is set to Discard Item. Switch to the Other branch and sharpen the category descriptions.
- Parser reports an invalid format: schema too strict or prompt too vague. Reduce required fields, show an example in the prompt or use the Auto-fixing Output Parser.
- Error 429 from the provider: rate limit reached. Set Retry On Fail with a longer wait or process fewer items at a time.
Checklist
Before an AI workflow runs permanently, these points should be done:
- All keys are stored as credentials, and the encryption key is backed up.
- The AI returns structured JSON, an If node checks it, and unclear cases go to a human.
- Retry On Fail is active on the AI node, and an error workflow reports failures.
- Only necessary data goes to the AI, and the legal basis and data processing agreement are in place.
- Backups run regularly, and a spending limit is set with the provider.
More notes
- GuideConnecting MCP serversHow to connect Claude to your own data and tools through the Model Context Protocol, safely and step by step.
- GuideSetting up Claude CodeFrom installation to working with CLAUDE.md, skills and hooks. This is how I use Claude Code every day.
- NoteConditional Access einführen, ohne sich auszusperrenConditional Access ist mächtig, und genau das macht es riskant. Eine einzige Richtlinie mit „Alle Benutzer, alle Ressourcen, Zugriff blockieren“ sperrt die ganze Organisation aus, die Admins eingeschlossen. Die meisten Probleme entstehen nicht durch exotische Einstellungen, sondern weil eine Richtlinie direkt scharf geschaltet wird, ohne sie vorher zu testen.