n8n Gmail Email Summary Automation: AI Extracts Action Items and Writes to Google Sheets
This paper focuses on reusable node structures, filtering, structured output, idempotency, and error handling, without using unverified savings ratios or success rates.
Quick Answer
- ✓ Build a Gmail email summarization workflow in n8n: use the Gmail Trigger to search and filter emails, invoke an AI agent to extract summaries, priorities, and action items, then deduplicate by Message ID before writing to Google Sheets.
Who Should Read This
- ● Developers evaluating n8n / gmail / openai / google-sheets for production use.
- ● Indie builders who need a practical implementation path instead of another generic concept article.
- ● Readers comparing architecture trade-offs, risks, tooling boundaries and next actions.
Problem Solved
- ● To automatically read new Gmail emails and generate summaries using n8n, you can build a workflow that connects the **Gmail Trigger** node with an **LLM (Large Language Model)** node. Here is the step-by-step implementation guide: ### 1. Prerequisites * An active n8n account (Cloud or Self-hosted). * A Gmail account with IMAP/POP enabled (if using standard Gmail node) or OAuth2 credentials set up in n8n. * Access to an LLM API (e.g., OpenAI, Anthropic, or a local model via Ollama) configured in n8n. ### 2. Workflow Setup #### Step 1: Add Gmail Trigger Node 1. Click **+ Add Node** and search for **Gmail**. 2. Select **On New Email** (or "On New Attachment" if needed). 3. **Credential Setup**: * Create a new Gmail credential. Use OAuth2 for best practice. * Authorize n8n to access your Gmail account. 4. **Configuration**: * Set **Operation** to `Trigger`. * Optionally filter by label (e.g., only trigger on emails labeled "Important") or sender to reduce noise. #### Step 2: Extract Email Content 1. The Gmail Trigger outputs JSON data including `subject`, `bodyPlain` (or `bodyHtml`), and `from`. 2. If the body is HTML, add a **Code** node or use the **HTML** node to convert it to plain text for cleaner summarization. * *Example Code Node (JavaScript):* ```javascript const html = $input.item.json.bodyHtml; // Simple regex to strip tags (for demo; use a library like TurndownService for production) const text = html.replace(/<[^>]*>/g, ''); return [{ json: { ...$input.item.json, bodyText: text } }]; ``` #### Step 3: Generate Summary with LLM 1. Add an **OpenAI** (or other LLM provider) node. 2. Set **Operation** to `Chat`. 3. **Model**: Choose a model like `gpt-3.5-turbo` or `gpt-4`. 4. **Messages**: Construct the prompt dynamically. * **System Message**: "You are a helpful assistant. Summarize the following email concisely in bullet points. Highlight key actions, deadlines, and important information." * **User Message**: Use expression syntax to insert the email content: ```text Subject: {{ $json.subject }} Body: {{ $json.bodyText }}
- ● How to write to-do items, priorities, and summaries from emails into Google Sheets?
- ● To deduplicate by Gmail Message ID and prevent duplicate email writes, use the Message ID as a unique key in your storage system (e.g., MongoDB's `_id`, PostgreSQL's `UNIQUE` constraint, or Redis SET). Before inserting, check if the ID already exists; if it does, skip the write operation. This ensures each email is processed only once.
See the results first: What this workflow does
This n8n workflow periodically checks Gmail for new emails, filters out noise using Gmail search conditions, extracts summaries, action items, and priorities via a model, and finally writes deduplicated entries to Google Sheets based on Message ID.
The complete execution path is as follows:
Gmail Trigger
→ Google Sheets 查询 Message ID
→ IF:是否已处理
→ 是:结束
→ 否:AI 提取结构化字段
→ 字段校验
→ Google Sheets 追加新行
→ 可选:高优先级通知
The minimum viable version requires only four types of nodes:
- Gmail Trigger: Fetches new emails;
- Google Sheets: Queries and writes data;
- AI Chat Model + Structured Output Parser: Extracts structured fields;
- IF: Controls deduplication and failure branches.
Fields Written to Google Sheets
It is recommended to create the following headers first:
| Field | Purpose |
|---|---|
| Date | Email received time |
| From | Sender |
| Subject | Email subject |
| Summary | A summary in three sentences or less |
| Action Items | To-dos extracted from the email |
| Priority | low / medium / high |
| Status | Manually maintained processing status |
| MessageID | Idempotent deduplication key |
MessageID must be retained. Without it, workflow retries or repeated polling can easily result in duplicate rows being written to the spreadsheet.
Step 1: Configure Gmail Trigger
The Gmail Trigger checks for new emails according to your configured Poll Times. The node itself also supports filtering parameters such as Read Status, Search, Sender, Label, and the number of items per poll.
During testing, start with minimal filtering conditions:
is:unread
Once the node confirms it can read the email, gradually add more conditions:
is:unread -category:social -category:promotions -from:noreply
This query serves the following purposes:
- Process only unread emails;
- Exclude the Social category;
- Exclude the Promotions category;
- Exclude common automated notification senders.
Avoid stacking a large number of filter conditions from the start. When a Trigger returns no data, it becomes difficult to determine whether the cause is an authorization failure, incorrect polling settings, or overly restrictive Search conditions that filtered out all emails.
Should Simplify Be Enabled or Disabled?
The Gmail Trigger can return simplified results by default, which include the Message ID, labels, and common email header fields. You can enable Simplify when performing subject classification. However, if you need the full email body, check the output of the current node and disable Simplify or append a Gmail Get Message node as necessary.
Step 2: Use Message ID for Idempotent Deduplication
Every email in Gmail has a unique Message ID. Querying before writing helps avoid the following issues:
- Duplicate writes caused by workflow retries;
- The same email re-entering the flow due to overlapping polling intervals;
- The entire execution restarting after a model node timeout;
- Manual re-execution of historical tasks.
Recommended workflow:
[Gmail Trigger]
→ [Google Sheets: 按 MessageID 查询]
→ [IF: 是否找到记录]
├─ True → [结束]
└─ False → [AI 摘要] → [追加新行]
Do not rely on the subject line or sender for IF conditions, as different emails may share the same subject. The unique key must be the Message ID.
Step 3: Ensure the model returns a fixed structure
Instead of simply writing “please return JSON” in the prompt, it is more robust to connect the model node to a Structured Output Parser and define the field schema.
{
"type": "object",
"properties": {
"summary": {
"type": "string",
"description": "用不超过三句话概括邮件核心内容"
},
"action_items": {
"type": "array",
"items": { "type": "string" },
"description": "收件人需要完成的具体动作,没有则返回空数组"
},
"priority": {
"type": "string",
"enum": ["low", "medium", "high"],
"description": "根据明确的时间、风险和阻塞信号判断优先级"
}
},
"required": ["summary", "action_items", "priority"]
}
Recommended Prompts:
你是邮件信息提取器。根据发件人、主题和正文提取结构化字段。
规则:
1. summary:不超过三句话,只概括邮件中明确出现的信息。
2. action_items:只提取收件人需要执行的动作;没有则返回空数组。
3. priority:
- high:包含明确的临近截止时间、服务中断、付款风险或客户升级;
- medium:需要处理但没有立即风险;
- low:通知、参考资料或无需回复的信息。
4. 不补充邮件中不存在的日期、责任人和结论。
5. 严格遵守输出 Schema。
Step 4: Validate Fields Before Writing to the Spreadsheet
Even when using structured output, it is recommended to add an IF or Code node for minimal validation before writing.
const item = $input.first().json;
if (typeof item.summary !== 'string') {
throw new Error('summary must be a string');
}
if (!Array.isArray(item.action_items)) {
throw new Error('action_items must be an array');
}
if (!['low', 'medium', 'high'].includes(item.priority)) {
throw new Error('priority is invalid');
}
return item;
Google Sheets field mapping can be used for:
Date = 邮件时间
From = 发件人
Subject = 邮件主题
Summary = summary
ActionItems = action_items.join("\n")
Priority = priority
Status = 待处理
MessageID = Gmail Message ID
Step 5: Add Notifications for High-Priority Emails
Tables serve as an archival layer and are not suitable for real-time alerts. You can use a Switch node to route traffic based on priority before writing:
high → 即时通知 → 写入 Sheets
medium → 写入 Sheets → 每日汇总
low → 只写入 Sheets
Notification nodes can be swapped out for the team’s actual tools, such as Slack, Discord, WeCom, Feishu, or email. When notifications involve external clients, payments, or production operations, they should serve only as alerts; models must not automatically reply or execute irreversible actions.
Error Workflow: Failures Must Be Detectable
The main workflow must handle at least three categories of errors:
- Gmail authorization expiration;
- Model call timeouts, rate limiting, or output validation failures;
- Google Sheets write timeouts or permission errors.
You can establish a separate Error Workflow:
Error Trigger
→ 提取 workflow、node、execution URL 和错误消息
→ 写入错误日志
→ 发送告警
Associate this Error Workflow in the main workflow’s Settings. The alert content should include at least:
- Workflow name;
- Failed node;
- Execution time;
- Error summary;
- Execution link;
- Whether safe retries are allowed.
Troubleshooting Common Issues
Gmail Trigger Returns No Data
Check the following items in order:
- Whether the workflow is activated;
- Whether Google OAuth credentials are still valid;
- Whether Poll Times match expectations;
- Whether Read Status is set to read only unread emails;
- Whether Search, Sender, or Label filters are excluding test emails;
- Whether the current email arrived after the node started listening.
During testing, first remove the Search conditions and keep only one newly sent unread email. Once the execution path is confirmed working, restore the filters.
Model Output Cannot Be Parsed
Prioritize using a Structured Output Parser instead of relying on regex to extract JSON from natural language. If it still fails, log the raw model response and route that specific execution to manual review or a retry branch. Do not write incomplete fields into the spreadsheet.
Duplicate Writes to Google Sheets
Ensure the Lookup happens before the model call and Add Row, and confirm that the query column and the write column use the same Message ID. Subject, time, and sender cannot replace an idempotency key.
Google Sheets Write Timeout
Enable limited retries with backoff for the write node. As data volume increases, avoid writing large numbers of rows concurrently. Aggregate into batches first, or use a database as the primary storage and Sheets as the presentation layer.
SQLite Locks in Self-Hosted n8n
SQLite is suitable for experimentation and low-concurrency environments. As the number of workflows, concurrent executions, and execution history grow, evaluate migrating to PostgreSQL, combined with Queue Mode and Worker isolation for long-running tasks. Back up both the database and N8N_ENCRYPTION_KEY before migration, otherwise existing credentials may become undecryptable.
Privacy and Permission Boundaries
Email bodies may contain customer information, contracts, verification codes, financial data, and internal links. Before going live, implement at least the following restrictions:
- Use dedicated Google credentials, authorizing only the necessary mailboxes;
- Use Search conditions to filter out emails that clearly should not enter the model;
- Do not send attachments to the model by default;
- Set an upper limit on body length;
- Do not save full email bodies in logs;
- Restrict sharing scope when writing to spreadsheets;
- Manual confirmation must be retained for automated replies, forwards, deletions, and payment-related actions.
Final Checklist
- Gmail Trigger can stably retrieve test emails;
- Search conditions do not accidentally filter out emails that need processing;
- Message ID lookup occurs before the model call;
- Model output passes Schema and field validation;
- Google Sheets has saved the MessageID column;
- Repeated executions do not generate duplicate rows;
- Error Workflow sends alerts containing the Execution link;
- Email bodies, attachments, and logs meet privacy requirements;
- High-risk actions are not delegated to automatic model execution.
Continue Reading
- AI Workflow Series: Self-hosted n8n, Use Cases, and Troubleshooting Guide
- Self-hosted n8n AI Workflows: Docker, Postgres, VPS, and NAS Deployment
- Error Handling, Retries, Timeouts, and Cost Monitoring in n8n
- Practical Guide to n8n Queue Mode with Redis Workers
- Choosing Between n8n and Make: A Comparison of Workflow Automation
- Building an n8n Notion Knowledge Base Agent
Continue through the production automation path
The workflow hub connects self-hosting, queue mode, webhooks, retries, observability and n8n implementation cases into one production-oriented learning path.
Next Reading
View Hub →n8n AI Workflow in Action: Slack Daily Digest Bot
A hands-on guide to building a daily briefing AI agent using self-hosted n8n, OpenAI, and the Slack API. Covers batch retrieval of Slack messages, filtering for short messages and system notifications, multi-thread context correlation, precise decision extraction by large language models, and automated push delivery.
Self-Hosted n8n Deployment Guide: Docker Compose, Postgres, VPS, and NAS Production Baseline
How to deploy self-hosted n8n for stability? This article provides a production baseline using Docker Compose + Postgres, covering version pinning, N8N_ENCRYPTION_KEY, WEBHOOK_URL, N8N_EDITOR_BASE_URL, reverse proxying, backup and recovery, NAS networking, and upgrade boundaries for Queue Mode.
n8n Webhook Production Deployment: Header Auth, Raw Body, WEBHOOK_URL, and Reverse Proxy Troubleshooting
Systematically deconstructs the critical configuration for self-hosted n8n Webhooks from testing to production deployment, covering Test URL vs. Production URL, Header Auth, JWT, Raw Body, Respond to Webhook, WEBHOOK_URL, N8N_PROXY_HOPS, reverse proxy, signature verification, idempotency deduplication, and security troubleshooting.
n8n Queue Mode + Redis in Practice: When to Offload Workflows to a Queue
A hands-on guide to deploying n8n Queue Mode, Redis, and Workers in production. Covers when to switch from regular mode to queue mode, how to split the main instance, workers, webhooks, Redis, and database, plus strategies for handling high concurrency, long-running tasks, webhook callbacks, and execution timeouts in AI workflows.

Xiaobai
Full-Stack AI Engineer
Xiaobai, a full-stack AI engineer building production Agent systems, product tools and independent software assets.
About Xiaobai & XBSTACK →Liked this article?
Join the newsletter
Every issue condenses production AI engineering changes, real failures, reproducible experiments, useful tools and new XBSTACK assets. No generic news digest and no filler.