n8nCreativeWritingAI score · PendingAI-assisted edit · no obvious prompt-injection riskn8n.io

Auto-categorize Gmail and draft replies with Groq in n8n

Gmail trigger → field extraction → Groq AI analysis → JSON parsing → priority alert + Google Sheets logging → conditional draft reply

Some experienceStepsWorkflowPromptTip
Who
Users who need to automate Gmail inbox processing with AI-assisted categorization, summarization, and pre-drafted replies
You get
New emails are auto-categorized, summarized, and draft-replied; high-priority emails trigger instant alerts; all analyses are logged to Google Sheets
You need
n8n · gmail · google-sheets

Constraints

Prerequisites: n8n instance (self-hosted or cloud); Gmail OAuth2 credential (read emails + create drafts); Groq API key; optional Google Sheets OAuth2 credential. Cost: Groq API billed per token; n8n and Google APIs have free-tier limits.

What they did

Author utkarsh-automates published this workflow template on the n8n platform. The template configures a Gmail trigger polling every minute, filters empty-content emails via an If node, extracts sender/subject/body fields with a Set node, then passes them to a Groq AI Agent (llama-3.3-70b-versatile) to generate structured JSON analysis (category, priority, summary, draft reply, etc.). A Code node parses and normalizes the AI output, after which the workflow sends priority alerts via Gmail, logs analyses to Google Sheets, and creates Gmail drafts when responses are required.

How it went

Author reports the template enables: automatic categorization, summarization, draft generation, high-priority alerts, and Sheet logging (author_report). No quantitative ROI or long-term stability data is provided.

Worth knowing

1) This site has not tested the workflow; reproduction=not_tested. 2) AI output relies on JSON format compliance; despite fallback parsing, model formatting errors may still cause parse failures. 3) Body is truncated to 3000 characters; very long emails may lose context. 4) Groq parameters (temperature 0.3, maxTokens 2048) are template defaults and adjustable. 5) Google Sheets logging is optional and can be disabled without affecting the core flow. 6) Draft replies are not auto-sent; they require manual review before sending. 7) One-minute polling may approach Gmail API quotas; evaluate polling intervals for high-volume scenarios.

n8n workflow template

Structure checked · Not run-tested

Use “Import from File” in n8n, or copy the JSON and paste it into the editor. Connect your own accounts, then try test data. The template is inactive by default.

Setup and test checklist

Credentials to connect

  • After import, connect your own credentials on auth-required nodes; author secrets are not included.

Configuration to replace

  • Source template is n8n public workflow #16592 (~19 nodes). Keep inactive after import; verify triggers, expressions and external API endpoints.
  • Sticky-note guidance is informational; replace placeholders with your own accounts, sheet schemas or channel IDs.

Test input and expected output

  • Manually run the main path once in a test workspace and confirm credentialed nodes authenticate without errors.
  • Drive one synthetic/redacted sample through and check output fields and downstream writes before enabling in production.

Template changes

  • Author credential bindings, webhookId and execution data are removed; the workflow is inactive. Nodes, connections and original prompts are preserved. Not run-tested in n8n.
  • No business-logic edits; verify keys, quotas and privacy compliance before use.

Template retrieved: 2026-10-24

Steps

  1. Configure Gmail trigger and content filter

    Add a 'Gmail Trigger' node in n8n, set polling interval to every minute (pollTimes: everyMinute). Add an 'If' node (Check Email Content) with condition {{ $json.text || $json.snippet }} not equal to empty string, skipping emails without body or snippet.

  2. Extract key email fields

    Add an 'Edit Fields (Set)' node mapping: sender (from address), sender_name (from name), subject (default '(No Subject)'), body (text or snippet truncated to 3000 chars), email_id, received_date.

  3. AI analysis and categorization

    Add an 'AI Agent' node (Email Analysis Agent), set promptType to define. Fill the text field with the user prompt and options.systemMessage with the system prompt. Connect a 'Groq Chat Model' sub-node, select model llama-3.3-70b-versatile, temperature 0.3, maxTokensToSample 2048.

    Execution prompt · Source text。AI Agent node text field (user prompt)

    =Analyze and categorize this email, then draft an appropriate response.
    
    FROM: {{ $json.sender_name }} <{{ $json.sender }}>
    SUBJECT: {{ $json.subject }}
    BODY:
    {{ $json.body }}
    
    Respond ONLY with valid JSON.

    Execution prompt · Source text。AI Agent node options.systemMessage field

    You are an expert email assistant. Your job is to analyze incoming emails, categorize them by urgency and type, and draft professional responses.
    
    You MUST respond ONLY with valid JSON. No markdown, no code blocks.
    
    Required JSON structure:
    {
      "category": "One of: URGENT | ACTION_REQUIRED | FOLLOW_UP | FYI | NEWSLETTER | SPAM | PROMOTION | PERSONAL",
      "priority": "One of: HIGH | MEDIUM | LOW",
      "summary": "2-3 sentence summary of what this email is about",
      "key_asks": ["What the sender wants — each ask as a separate item"],
      "sentiment": "One of: positive | neutral | negative | frustrated",
      "requires_response": true,
      "suggested_response_time": "Respond within: 1 hour / 4 hours / 24 hours / 48 hours / No response needed",
      "draft_response": {
        "subject": "Re: original subject or new subject if needed",
        "body": "Professional, concise draft reply. Match the tone of the original email. If the email is a newsletter or promotion, leave this empty.",
        "tone": "The tone used: professional / friendly / formal / apologetic / enthusiastic"
      },
      "action_items": ["Any to-do items this email creates for you"],
      "labels_suggested": ["Suggested Gmail labels: work, personal, finance, travel, project-X, etc."]
    }
    
    Rules:
    - SPAM/NEWSLETTER/PROMOTION: set requires_response to false, draft_response body to empty string
    - URGENT: anything with deadlines within 24hrs, payment issues, or critical requests
    - ACTION_REQUIRED: needs you to do something but not time-critical
    - FOLLOW_UP: someone following up on a previous conversation
    - FYI: informational, no action needed
    - Draft responses should be concise (under 150 words)
    - Never be sycophantic in drafts — be professional and direct
    - If the email is in a non-English language, respond in the same language
    - Extract ALL action items, even implicit ones
  4. Parse and validate AI output

    Add a 'Code' node (Parse AI Analysis) running JavaScript to parse the AI JSON response. Try JSON.parse first, fallback to markdown code block extraction or regex match for {…}, return parse_status: failed if all fail. On success, normalize all fields (category, priority, summary, key_asks, sentiment, requires_response, suggested_response_time, draft_subject, draft_body, draft_tone, action_items, labels).

    Execution prompt · Source text。Parse AI Analysis node jsCode field

    const items = $input.all();
    const output = items[0].json.output;
    
    let parsed;
    try {
      parsed = JSON.parse(output);
    } catch (e) {
      const jsonMatch = output.match(/```(?:json)?\s*([\s\S]*?)```/);
      if (jsonMatch) {
        try { parsed = JSON.parse(jsonMatch[1].trim()); } catch (e2) { parsed = null; }
      }
      if (!parsed) {
        const objMatch = output.match(/\{[\s\S]*\}/);
        if (objMatch) {
          try { parsed = JSON.parse(objMatch[0]); } catch (e3) { parsed = null; }
        }
      }
    }
    
    if (!parsed) {
      return [{ json: { parse_status: 'failed', error: 'Could not parse AI analysis' } }];
    }
    
    return [{
      json: {
        parse_status: 'success',
        timestamp: new Date().toISOString(),
        sender: items[0].json.sender || '',
        sender_name: items[0].json.sender_name || '',
        original_subject: items[0].json.subject || '',
        email_id: items[0].json.email_id || '',
        category: parsed.category || 'FYI',
        priority: parsed.priority || 'LOW',
        summary: parsed.summary || '',
        key_asks: Array.isArray(parsed.key_asks) ? parsed.key_asks.join('; ') : '',
        sentiment: parsed.sentiment || 'neutral',
        requires_response: parsed.requires_response || false,
        suggested_response_time: parsed.suggested_response_time || '',
        draft_subject: parsed.draft_response?.subject || '',
        draft_body: parsed.draft_response?.body || '',
        draft_tone: parsed.draft_response?.tone || '',
        action_items: Array.isArray(parsed.action_items) ? parsed.action_items.join('; ') : '',
        labels: Array.isArray(parsed.labels_suggested) ? parsed.labels_suggested.join(', ') : ''
      }
    }];
  5. Priority check, alert, and logging

    Add an 'If' node (Check Parse Success) verifying parse_status equals success. On success, route to 'If' (Evaluate Priority Level) checking if priority equals HIGH: if yes, trigger 'Gmail' node (Send High Priority Alert) to send an HTML alert to your address. Regardless of priority, append the record via 'Google Sheets' node (Append to Google Sheets) to the 'Email Log' sheet.

  6. Conditional draft reply creation

    After Google Sheets logging, add an 'If' node (Assess Reply Necessity) checking if requires_response is true. If true, trigger 'Gmail' node (Draft Gmail Reply) with operation createDraft to create a draft reply; if false, the workflow ends.

Prompt you can copy

Setup guidance · Editorial suggestion。Hand to setup assistant; confirm inputs and permissions first

This block is the prompt. Ads are never placed here.

You are setting up an n8n workflow to monitor Gmail, categorize emails with Groq AI, and draft replies. Please confirm you have ready: 1) Gmail OAuth2 credential (read + draft permissions); 2) Groq API key; 3) Optional Google Sheets credential and Sheet ID. Then import the workflow JSON or create nodes manually, checking that the AI Agent's systemMessage and Parse AI Analysis field mappings match downstream If conditions.

Before building, ensure Gmail OAuth2 is authorized for reading emails and creating drafts; Groq API key is saved in n8n Credentials; if logging is needed, create a Google Sheet and obtain its document ID in advance.

Source

Categorize emails and draft Gmail replies with Groq and Google Sheets · utkarsh-automates · n8n.io · 2026-06-24

Comments & feedback

Tried this method? Share results, problems or improvements. Comments appear after moderation. Please avoid sensitive information.

Loading…

    Related