Gmail + OpenAI: drafts, labels, and fewer misses
Your inbox isn’t “busy.” It’s chaotic. Important threads get buried, you reread the same email chain three times, and the one message with the key attachment somehow disappears right when you need it.
Marketing leads feel it when approvals stall. Client-facing teams feel it when response time slips. And if you run a small business, Gmail OpenAI automation can be the difference between “on top of it” and “constantly behind.”
This workflow watches new emails, classifies them, drafts replies in your voice, labels everything cleanly, and pings you only when it’s truly urgent. You’ll see how it works, what you need, and where teams usually tweak it.
How This Automation Works
The full n8n workflow, from trigger to final output:
n8n Workflow Template: Gmail + OpenAI: drafts, labels, and fewer misses
flowchart LR
subgraph sg0["Email_ Flow"]
direction LR
n0@{ icon: "mdi:robot", form: "rounded", label: "Auto-fixing Output Parser", pos: "b", h: 48 }
n1@{ icon: "mdi:robot", form: "rounded", label: "Structured Output Parser", pos: "b", h: 48 }
n2@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Check for Attachments", pos: "b", h: 48 }
n3@{ icon: "mdi:play-circle", form: "rounded", label: "Email_Trigger", pos: "b", h: 48 }
n4@{ icon: "mdi:message-outline", form: "rounded", label: "Get Conversation Thread", pos: "b", h: 48 }
n5@{ icon: "mdi:cog", form: "rounded", label: "Get Latest Message ID", pos: "b", h: 48 }
n6@{ icon: "mdi:message-outline", form: "rounded", label: "Get Latest Message Content", pos: "b", h: 48 }
n7@{ icon: "mdi:robot", form: "rounded", label: "AI Email Classifier", pos: "b", h: 48 }
n8@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Smart Action Router", pos: "b", h: 48 }
n9@{ icon: "mdi:cog", form: "rounded", label: "Aggregate Label IDs", pos: "b", h: 48 }
n10@{ icon: "mdi:robot", form: "rounded", label: "AI Response Generator", pos: "b", h: 48 }
n11@{ icon: "mdi:cog", form: "rounded", label: "Upload to Google Drive", pos: "b", h: 48 }
n12@{ icon: "mdi:message-outline", form: "rounded", label: "Create Draft Response", pos: "b", h: 48 }
n13@{ icon: "mdi:message-outline", form: "rounded", label: "Assign Classification Label", pos: "b", h: 48 }
n14@{ icon: "mdi:message-outline", form: "rounded", label: "Mark as Processed", pos: "b", h: 48 }
n15["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/telegram.svg' width='40' height='40' /></div><br/>Send Urgent Alert"]
n16@{ icon: "mdi:cog", form: "rounded", label: "Check Existing Attachments", pos: "b", h: 48 }
n17@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Check if File Exists", pos: "b", h: 48 }
n18["<div style='background:#f5f5f5;padding:10px;border-radius:8px;display:inline-block;border:1px solid #e0e0e0'><img src='https://flowpast.com/wp-content/uploads/n8n-workflow-icons/merge.svg' width='40' height='40' /></div><br/>Merge Attachment Data"]
n19@{ icon: "mdi:swap-vertical", form: "rounded", label: "Process One by One", pos: "b", h: 48 }
n20@{ icon: "mdi:message-outline", form: "rounded", label: "Get All Gmail Labels", pos: "b", h: 48 }
n21@{ icon: "mdi:swap-horizontal", form: "rounded", label: "Filter User Labels", pos: "b", h: 48 }
n22@{ icon: "mdi:cog", form: "rounded", label: "Get User Labels", pos: "b", h: 48 }
n23@{ icon: "mdi:brain", form: "rounded", label: "AI Language Model", pos: "b", h: 48 }
n25@{ icon: "mdi:code-braces", form: "rounded", label: "Get All Attachments", pos: "b", h: 48 }
n3 --> n19
n22 --> n7
n23 -.-> n7
n23 -.-> n0
n23 -.-> n10
n14 --> n19
n21 --> n22
n19 --> n4
n7 --> n8
n9 --> n14
n9 --> n13
n25 --> n16
n25 --> n18
n8 --> n10
n8 --> n2
n8 --> n15
n8 --> n9
n17 --> n18
n20 --> n21
n10 --> n12
n2 --> n25
n5 --> n6
n18 --> n11
n4 --> n5
n1 -.-> n0
n0 -.-> n7
n16 --> n17
n6 --> n20
end
subgraph sg1["Flow 2"]
direction LR
n24@{ icon: "mdi:code-braces", form: "rounded", label: "Get Specific File Types", pos: "b", h: 48 }
end
%% Styling
classDef trigger fill:#e8f5e9,stroke:#388e3c,stroke-width:2px
classDef ai fill:#e3f2fd,stroke:#1976d2,stroke-width:2px
classDef aiModel fill:#e8eaf6,stroke:#3f51b5,stroke-width:2px
classDef decision fill:#fff8e1,stroke:#f9a825,stroke-width:2px
classDef database fill:#fce4ec,stroke:#c2185b,stroke-width:2px
classDef api fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef code fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
classDef disabled stroke-dasharray: 5 5,opacity: 0.5
class n3 trigger
class n0,n1,n7,n10 ai
class n23 aiModel
class n2,n8,n17,n21 decision
class n25,n24 code
classDef customIcon fill:none,stroke:none
class n15,n18 customIcon
The Problem: Email triage steals your best hours
Most inboxes fail in a very specific way. You don’t lose time on one email, you lose it in the constant context switching: read, search the thread, download an attachment, decide urgency, remember to follow up, then repeat. After a few days, you have half-labeled conversations, “I’ll reply later” messages that never get replied to, and a vague anxiety that you missed something important. The worst part is that the work feels necessary, so it’s hard to stop doing it manually.
The friction compounds. Here’s where it breaks down in real life.
- You reread long threads just to figure out what changed since the last message.
- Urgent emails blend in with newsletters and “quick questions,” so you check Gmail more often than you should.
- Drafting replies eats the day because you’re starting from a blank page each time.
- Attachments get saved inconsistently, which means searching Drive later (again) when someone asks for “that PDF.”
The Solution: AI-assisted Gmail triage that drafts and organizes
This n8n workflow acts like a quiet email assistant that never gets tired. When a new message hits Gmail, the workflow pulls the full conversation context, grabs the latest message body, and checks your existing Gmail labels so it can stay consistent with your current system. Then OpenAI classifies the email by urgency, priority, and “what should happen next” (reply, follow up, upload attachments, forward to a team, and so on). Based on that classification, it takes action: it applies the right label, marks the email as processed, and generates a context-aware draft reply that you can review in Gmail. If the message is genuinely urgent, you also get an instant Telegram alert so it doesn’t sit unseen.
The workflow starts with Gmail intake and thread retrieval. OpenAI handles classification and reply drafting with memory for better continuity. Finally, Gmail gets labeled and drafted, and attachments can be uploaded to Google Drive with duplicate checks so you don’t end up with five copies of the same file.
What You Get: Automation vs. Results
| What This Workflow Automates | Results You’ll Get |
|---|---|
|
|
Example: What This Looks Like
Say you get about 30 meaningful emails a day. If you spend roughly 5 minutes per email to skim, decide priority, label it, and start a reply, that’s about 2.5 hours daily. With this workflow, you mostly do two things: scan the label/priority and approve or edit a draft. Call it 1 minute per email plus a few urgent pings, so around 30–40 minutes. That’s close to 2 hours back on a normal day.
What You’ll Need
- n8n instance (try n8n Cloud free)
- Self-hosting option if you prefer (Hostinger works well)
- Gmail for triggering, labeling, and saving drafts.
- OpenAI to classify emails and draft replies.
- OpenAI API key (get it from your OpenAI dashboard).
Skill level: Intermediate. You’ll connect credentials, paste in your label IDs, and tweak a couple of prompts for your voice.
Don’t want to set this up yourself? Talk to an automation expert (free 15-minute consultation).
How It Works
A new email arrives in Gmail. The workflow triggers on incoming messages and batches them so one busy hour doesn’t overwhelm your setup.
The thread and message content are pulled in. It fetches the conversation thread, identifies the latest message, and extracts the body so the AI isn’t guessing from a subject line.
OpenAI classifies, then routes the next action. The classifier looks at urgency, priority, and category (to reply, date-related, requires follow-up, attachments to upload, and more). A routing switch decides what happens next: draft a response, label it, upload attachments, send an urgent alert, or some combination.
Drafts, labels, and alerts land where you already work. You’ll see a prepared draft inside Gmail, classification labels applied automatically, and Telegram alerts only when the workflow flags something as urgent.
You can easily modify the categories and urgency keywords to match your business, then change where alerts go (Telegram to Slack, for example) based on your needs. See the full implementation guide below for customization options.
Step-by-Step Implementation Guide
Step 1: Configure the Gmail Trigger
Set up the workflow to watch your inbox and pull full email content with attachments.
- Add and open Gmail Intake Trigger.
- Set Simple to
false. - Set Filters → q to
-from:me. - Enable Options → Download Attachments to
true. - Set Poll Times to
everyHour.
Credential Required: Connect your Gmail credentials to Gmail Intake Trigger.
Step 2: Connect Gmail Data Retrieval and Label Discovery
Pull the full thread, isolate the most recent message, and collect user-defined labels for classification.
- In Iterate Messages, keep default settings to batch through incoming items from Gmail Intake Trigger.
- Configure Fetch Conversation Thread with Resource set to
threadand Thread ID to{{ $('Gmail Intake Trigger').item.json.threadId }}. - Set Retrieve Latest Message ID to keep
lastItems. - Set Fetch Latest Message Body with Message ID to
{{ $('Retrieve Latest Message ID').item.json.id }}and Simple tofalse. - In Retrieve Gmail Labels, set Resource to
labeland Return All totrue. - In Filter User-Only Labels, keep the condition
{{ $('Retrieve Gmail Labels').item.json.type }}equalsuser. - In Aggregate User Labels, aggregate fields
idandnamewith Merge Lists enabled.
Credential Required: Connect your Gmail credentials to all Gmail nodes (6 total), including Fetch Conversation Thread, Fetch Latest Message Body, Retrieve Gmail Labels, Generate Draft Reply, Apply Classification Label, and Flag as Processed.
Step 3: Set Up AI Classification and Parsing
Configure the language model, output parsers, and AI prompt used to classify each email.
- Open AI Chat Model and select model
gpt-4o-mini. - In Structured Result Parser, keep Schema Type set to
manualand the JSON schema as provided. - In Auto Correcting Parser, leave defaults; it will be linked as the output parser for AI Mail Classifier.
- In AI Mail Classifier, set Text to the full prompt block:
=<message> {{ $('Fetch Latest Message Body').item.json.textAsHtml }} </message> <subject> {{ $('Fetch Latest Message Body').item.json.subject }} </subject> <metadata> {{ $('Fetch Latest Message Body').item.json.headers.from }} {{ $('Fetch Latest Message Body').item.json.headers.date }} </metadata> <attachments> {{ $('Gmail Intake Trigger').item.binary ? true : false }} </attachments> <categories> {{ JSON.stringify($('Aggregate User Labels').all(), null, 2) }} </categories> <current_category_labels> {{ $('Gmail Intake Trigger').item.json.labelIds }} </current_category_labels> <message_thread> {{ $('Gmail Intake Trigger').item.json.textAsHtml }} </message_thread> - Ensure AI Mail Classifier has Has Output Parser enabled so it uses Auto Correcting Parser → Structured Result Parser.
Credential Required: Connect your OpenAI credentials to AI Chat Model. This model is used by AI Mail Classifier and AI Reply Composer.
Auto Correcting Parser and Structured Result Parser are connected as AI output parsers for AI Mail Classifier — ensure credentials are added to AI Chat Model, not these parser nodes.
Step 4: Configure Routing, Draft Replies, and Label Actions
Route the AI decision into replies, alerts, and label application.
- Open Action Routing Switch and verify the rule conditions use:
{{ $json.output.classification.toReply }},{{ $json.output.classification.attachmentsToUpload }}, and{{ $json.output.classification.urgent }}. - In AI Reply Composer, set Text to
=Subject: {{ $('Gmail Intake Trigger').item.json.subject }} Message: {{ $('Gmail Intake Trigger').item.json.textAsHtml }}. - In Generate Draft Reply, set Message to
{{ $('AI Reply Composer').item.json.text.replace(/\n/g, "<br />\n") }}and Subject to{{ $('Gmail Intake Trigger').item.json.headers.subject }}. - In Collect Label Identifiers, aggregate output.classification.label_ids into
label_ids. - In Apply Classification Label, set Label IDs to
{{ $('Collect Label Identifiers').item.json.label_ids[0] }}and Message ID to{{ $('Gmail Intake Trigger').item.json.id }}. - In Flag as Processed, set Label IDs to
[YOUR_ID]and Message ID to{{ $('Gmail Intake Trigger').item.json.id }}. - In Dispatch Urgent Alert, set Chat ID to
[YOUR_ID]and keep the alert text template as provided.
Action Routing Switch routes to multiple outputs; when a message qualifies, it can trigger both reply drafting and label processing.
Credential Required: Connect your Gmail credentials to Generate Draft Reply, Apply Classification Label, and Flag as Processed.
Credential Required: Connect your Telegram credentials to Dispatch Urgent Alert.
Step 5: Configure Attachment Handling and Google Drive Storage
Verify attachments, extract files, check for duplicates, and upload to Google Drive.
- In Verify Attachments, keep the condition checking
{{ $('Gmail Intake Trigger').item.binary }}exists. - In Extract All Attachments, keep the function code that outputs all attachment binaries.
- Confirm parallel execution: Extract All Attachments outputs to both Search Existing Files and Merge Attachment Info in parallel.
- Set Search Existing Files with Query String to:
{{ $('AI Mail Classifier').item.json.output.metadata.receivedDate.toDateTime().format('yyyy.MM.dd') + " - " + $('Gmail Intake Trigger').item.json.from.value[0].address + ' - ' + $('Extract All Attachments').item.json.fileName.split(".")[0] + "." + $('Extract All Attachments').item.json.fileName.split(".")[1]}}and set Return All totrue. - In Evaluate File Presence, keep the check that
{{ $('Search Existing Files').item.json }}is not empty. - In Merge Attachment Info, set Mode to
chooseBranchand Use Data Of Input to2. - In Upload to Drive Storage, set Folder ID to
[YOUR_ID]and keep the Name expression for standardized file naming.
Credential Required: Connect your Google Drive credentials to Search Existing Files and Upload to Drive Storage.
Step 6: Test and Activate Your Workflow
Run a full test to verify classifications, drafts, labels, and uploads, then enable the workflow.
- Click Execute Workflow and send a test email to trigger Gmail Intake Trigger.
- Confirm AI Mail Classifier outputs structured JSON matching Structured Result Parser.
- Verify drafts appear in Gmail from Generate Draft Reply, labels are applied by Apply Classification Label and Flag as Processed, and urgent alerts are sent by Dispatch Urgent Alert.
- Check Google Drive to confirm files were created by Upload to Drive Storage when attachments exist.
- Toggle the workflow to Active for production use.
Common Gotchas
- Gmail credentials can expire or be missing scopes. If things break, check the Gmail OAuth connection in n8n’s Credentials first, then re-test the Gmail Trigger node.
- If you’re using Wait nodes or external rendering, processing times vary. Bump up the wait duration if downstream nodes fail on empty responses.
- Default prompts in AI nodes are generic. Add your brand voice early or you’ll be editing outputs forever.
Frequently Asked Questions
About an hour if your Gmail and OpenAI credentials are ready.
No. You’ll mostly connect accounts and paste in a few label IDs. The only “technical” part is tweaking the AI prompts so the drafts sound like you.
Yes. n8n has a free self-hosted option and a free trial on n8n Cloud. Cloud plans start at $20/month for higher volume. You’ll also need to factor in OpenAI API costs, which are usually a few cents per email depending on model and thread length.
Two options: n8n Cloud (managed, easiest setup) or self-hosting on a VPS. For self-hosting, Hostinger VPS is affordable and handles n8n well. Self-hosting gives you unlimited executions but requires basic server management.
Yes, but you’ll swap the notification step. Replace the “Dispatch Urgent Alert (telegram)” node with a Slack node (or Microsoft Teams), then keep the same routing logic from the “Action Routing Switch.” Common customizations include changing urgency keywords, adding your standard sign-off in the “AI Reply Composer,” and mapping categories to your existing Gmail labels.
Most of the time it’s OAuth scope or an expired token. Reconnect the Gmail credential in n8n, then re-test the Gmail Trigger and any Gmail “Get thread / Create draft / Apply label” nodes. Also check that the workflow isn’t hitting Gmail API quota if you’re processing a backlog, because that can look like random failures. Finally, make sure the label IDs you hardcoded still exist in Gmail.
Practically, it can handle a normal small-team inbox without trouble. On n8n Cloud Starter you’re limited by monthly executions, while self-hosting has no fixed execution cap (your server is the limit). If you process hundreds of emails a day, keep an eye on OpenAI cost and Gmail API quotas, and consider batching plus stricter “urgent” rules.
Often, yes. This workflow uses branching logic, attachment handling, and multi-step routing that gets expensive and awkward in Zapier. n8n also gives you a self-host option, which matters if you want predictable costs. That said, if you only want “new email → send Slack message,” Zapier or Make is simpler. For anything involving drafts, labels, and classification categories, n8n is usually the calmer choice. If you want a second opinion, Talk to an automation expert.
Your inbox can stay busy without staying messy. Set this up once, then spend your attention on the emails that actually deserve it.
Need Help Setting This Up?
Our automation experts can build and customize this workflow for your specific needs. Free 15-minute consultation—no commitment required.