← All posts
How-ToAugust 9, 2026 · 3 min

How to Automate Email with AI: A Step‑by‑Step Inbox Triage Build

How do you automate your email inbox with AI? In a few minutes you can set up an n8n workflow that reads every incoming Gmail or Outlook message, asks a large language model to classify the intent, and then automatically applies a label, drafts a reply, or forwards the mail to a teammate. The result is a hands-free inbox that routes itself, saves you time, and lets you focus on the work that truly matters.

What is AI? AI is a set of computational techniques that enable machines to perform tasks that normally require human intelligence, such as understanding language, recognizing patterns, or making decisions.

AI email automation is the use of those techniques - typically a large language model (LLM) and a workflow engine - to read, classify, and act on email messages without manual intervention.


What you need

ToolPlan / PriceRole
n8n (self-hosted Docker)Free (open-source) - check n8n's current pricing for hosted plansOrchestrates the workflow, connects to email APIs and the LLM
Gmail or Outlook accountFree (standard email)Source of inbound messages
OpenAI API (or compatible LLM)Pay-as-you-go - check OpenAI's current pricing for token usageProvides classification and draft generation
Docker (optional)FreeRuns the n8n instance locally or on a VPS
HTTPS endpoint (e.g., ngrok)Free tier available - check provider for limitsExposes n8n to Gmail push notifications (optional)

Estimated build time: 2-3 hours for a developer comfortable with Docker and JSON.


How to automate email with ai

Below is a concrete, copy-paste-ready recipe. Each step names the exact n8n node, field, or API call you need to configure.

1. Spin up n8n

If you already have an n8n instance, skip this. Otherwise, run the official Docker image:

bash
docker run -d \
 --name n8n \
 -p 5678:5678 \
 -e N8N_BASIC_AUTH_ACTIVE=true \
 -e N8N_BASIC_AUTH_USER=admin \
 -e N8N_BASIC_AUTH_PASSWORD=changeme \
 n8nio/n8n

This starts n8n on port 5678 with basic authentication. After the container is up, open http://localhost:5678 and log in with the credentials you set.

Tip: For production you'll want a reverse proxy and TLS termination; the n8n docs have a one-click Docker-Compose example.

2. Add email credentials

In n8n's Credentials panel click New CredentialGmail OAuth2 (or Microsoft Outlook OAuth2). Follow the on-screen OAuth flow; you'll need to create a Google Cloud project or Azure app and paste the client ID and secret.

  • Scope: https://mail.google.com/ for Gmail, https://outlook.office.com/IMAP.AccessAsUser.All for Outlook.
  • Redirect URL: https://your-n8n-domain.com/rest/oauth2-credential/callback.

Save the credential; n8n will store the refresh token securely.

3. Create the trigger node

Add a Gmail Trigger node (or Outlook Trigger) to the canvas. Set Event to New Email and select the credential you just created.

  • Label Filter: leave empty to catch all mail.
  • Mark As Read: false (so you still see the original in your inbox).

This node will emit a JSON object for each incoming message, e.g.:

json
{
 "id": "1789a2b3c4d5e6f7",
 "from": "alice@example.com",
 "subject": "Quarterly report needed",
 "body": "Can you send the Q2 numbers by Friday?"
}

4. Call the LLM for classification

Add an HTTP Request node right after the trigger. This node will send the email body to the OpenAI chat completion endpoint and ask the model to return a short intent label.

What this does: Sends a prompt that asks the model to classify the email into one of three buckets: action-required, informational, or spam.

Configure the node as follows:

  • Method: POST
  • URL: https://api.openai.com/v1/chat/completions
  • Authentication: Header Authorization: Bearer <YOUR_OPENAI_API_KEY> (store the key in an n8n Credential of type API Key).
  • Headers: Content-Type: application/json
  • Body (JSON):
json
{
 "model": "gpt-4o-mini",
 "messages": [
 {
 "role": "system",
 "content": "You are an email triage assistant. Classify the following email into one of: action-required, informational, spam. Respond with only the label."
 },
 {
 "role": "user",
 "content": "{{ $json.body }}"
 }
 ],
 "temperature": 0
}

The response will look like:

json
{
 "choices": [
 {
 "message": {
 "content": "action-required"
 }
 }
 ]
}

5. Extract the label

Add a Set node to pull the label out of the LLM response and store it in a new field called triageLabel.

  • Value: {{ $json.choices[0].message.content }}
  • Name: triageLabel

Now every execution carries triageLabel alongside the original email data.

6. Route based on the label

Insert a Switch node that branches on triageLabel.

  • Value to test: {{ $json.triageLabel }}
  • Cases: action-required, informational, spam

Each case will connect to a different downstream action.

#### 6a. Action-required: apply a label and draft a reply

  • Gmail Add Label node: set Label to Needs Reply.
  • OpenAI Completion node (similar to step 4 but with a different system prompt) to generate a short draft reply.

Prompt example:

You are a concise professional assistant. Draft a reply to the email below, confirming receipt and promising a detailed response within 24 hours.

Email: {{ $json.body }}
  • Gmail Send Email node: use the draft text as the body, set To to {{ $json.from }}, and set Subject to Re: {{ $json.subject }}.

#### 6b. Informational: archive and add "Info" label

  • Gmail Add Label node: label Info.
  • Gmail Move To node: move the thread to the Archive folder.

#### 6c. Spam: move to Spam folder

  • Gmail Move To node: folder Spam.

7. Test the workflow

Activate the workflow and send three test emails that match each category. Use the Execute Workflow button in n8n to watch the data flow in real time. Verify that:

  • The LLM returns the expected label.
  • Labels are applied in Gmail.
  • Draft replies are sent only for action-required.

If any step fails, open the node's Error tab; n8n will show the exact HTTP status and response body, which is invaluable for debugging.

8. Deploy and monitor

Once satisfied, set the workflow to Active. n8n will now listen for every new email and run the classification pipeline automatically.

  • Monitoring: n8n's built-in Execution List shows success/failure counts.
  • Alerting: add a Telegram or Slack node at the end of the workflow to post a summary if the execution error rate exceeds 5 %.

Quote: "A well-tuned LLM can classify inbox messages with >90 % accuracy when the prompt is kept short and the label set is limited."


Where this breaks

  1. API rate limits - Gmail's API caps at 10 queries / second per user; OpenAI enforces a per-minute token quota that varies by plan. If you exceed either limit, the HTTP Request node will return a 429 error and the workflow will pause. Mitigation: add a Delay node (e.g., 200 ms) before the LLM call, and enable Retry on Fail with exponential back-off.
  1. Credential expiration - OAuth refresh tokens can become invalid if the user revokes access or the app is removed. The symptom is a 401 error from the Gmail node. Fix: re-run the OAuth flow in n8n's credential settings; consider adding a Cron job that checks token health weekly.
  1. Classification drift - The LLM may mislabel ambiguous emails, especially if the prompt is too generic. Result: a sales inquiry could be marked as spam. Mitigation: tighten the label set, add a few few-shot examples in the system prompt, and periodically review misclassifications.
  1. Cost blowup - Each classification request consumes tokens; at high email volumes the OpenAI bill can grow quickly. Monitor usage in the OpenAI dashboard, set a hard token limit in the HTTP Request node using the max_tokens parameter, and consider switching to a cheaper model (e.g., gpt-3.5-turbo).
  1. n8n execution limits - Self-hosted n8n has no hard execution cap, but hosted plans may limit the number of workflow runs per month. If you hit the limit, the workflow will stop and you'll see a "Workflow execution limit reached" error. Upgrade the plan or self-host to avoid interruption.

For a deeper technical reference, see n8n's documentation.

FAQ

How does the LLM decide which label to assign? The model receives a short system prompt that defines the allowed labels and a user prompt containing the email body. Because the temperature is set to 0, the output is deterministic, and the model returns only the label text.

Can I use Outlook instead of Gmail? Yes. Replace the Gmail Trigger, Add Label, and Send Email nodes with their Outlook equivalents. The credential type changes to Microsoft Outlook OAuth2, and the API scopes differ, but the overall workflow remains identical.

What if I want to store drafts in a database instead of sending them immediately? Insert a PostgreSQL (or MySQL) node after the draft-generation step. Map the LLM's content field to a draft_body column, and add columns for recipient, subject, and status. You can later run a separate workflow that picks up pending drafts and sends them after a human review.

How can I keep the OpenAI cost low? - Use the smallest model that meets your accuracy needs (gpt-3.5-turbo or gpt-4o-mini). - Limit the prompt to the email body only; avoid sending full thread histories. - Set max_tokens to a low value (e.g., 20) for classification calls. - Cache recent classifications for identical subjects using an IF node and a Redis store.

Is the workflow secure? All credentials are stored encrypted in n8n's database. The HTTP Request node sends the OpenAI API key in an Authorization header over HTTPS, and Gmail/Outlook OAuth tokens are refreshed automatically. For extra security, run n8n behind a firewall and restrict inbound traffic to your trusted IP range.


If you're ready to see a live example, check out the Inbox Triage Agent on the AAB vault: https://getaab.com/vault/inbox-triage-agent. The free guide at https://getaab.com/free also walks you through the basics of n8n and LLM prompting.

By following this step-by-step build you now have a production-ready system that shows exactly how to automate email with ai - no hype, just a reproducible workflow you can adapt to any inbox. Happy triaging!

Get the full toolkit

Grab the free guide with the node-by-node build for all 10 automations.

No spam. Unsubscribe anytime. Just the good stuff.