# Sort your Gmail with AI labels, set up from your assistant

Source: https://clickruntime.com/use-cases/gmail-triage

> Your assistant builds an automation that checks for new mail on a schedule, labels each message (invoice, customer, newsletter, needs reply), and tells you in Slack or by email when something is urgent.

## Can ChatGPT or Claude sort my Gmail automatically?

An assistant with a Gmail connector can sort mail while you're chatting. It doesn't keep working in the background or remember which messages it already handled. With ClickRuntime, the assistant sets up an automation that checks Gmail every 15 minutes (or as often as every 5), labels new messages with the built-in AI, and remembers where it left off.

### Why the assistant can't do this on its own

- No background work. Sorting has to happen when mail arrives, not when you next open a chat.
- No memory of what was handled. The automation keeps the last message it labelled in its state, so nothing is labelled twice or skipped.
- Gmail filters only match fixed words. AI labels read the message and decide, which handles the mail filters miss.

## Set it up from your AI assistant

Prompt to copy:

> Create a ClickRuntime automation: every 15 minutes, look at new messages in my Gmail inbox and add one label: Invoice, Customer, Newsletter or Needs reply. Email me straight away when a customer message sounds urgent.

1. **Connect ClickRuntime to your assistant.** Add ClickRuntime as a connector (MCP server) in ChatGPT, Claude, Cursor or another MCP client, using https://clickruntime.com/api/mcp. You sign in with Google or email; there is no API key to copy. This is done once per assistant.
2. **Paste the prompt.** Start a new chat and paste: “Create a ClickRuntime automation: every 15 minutes, look at new messages in my Gmail inbox and add one label: Invoice, Customer, Newsletter or Needs reply. Email me straight away when a customer message sounds urgent.” Change the details (times, channels, addresses) to yours.
3. **Read the draft.** The assistant restates what will happen, asks for anything missing, such as your timezone or which channel to post to, and saves a draft automation. A draft never runs on its own, so nothing happens until you agree.
4. **Connect accounts and save keys.** The assistant asks you to connect your Google account in the ClickRuntime dashboard with Gmail access (Google's own consent screen). It creates the four labels in Gmail with a one-time setup script if they don't exist.
5. **Test it.** The assistant runs it once against the last day of mail and shows which label each message got, before turning on the schedule. You can ask it to change the rules if a label looks wrong.
6. **Turn it on.** The assistant tells you what will run, when, and which services it will contact, then asks your permission to turn it on. From then on it runs on ClickRuntime's servers, and you can close the chat.
7. **Check it in the ClickRuntime dashboard.** Each run shows how many new messages it found and labelled. Runs that find nothing new and finish quickly aren't counted toward your monthly runs. State shows the time of the last message handled.

Connector setup for each assistant: https://clickruntime.com/assistants

## What the assistant writes

`gmail_ai_labels.py`

```python
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from clickruntime import on_trigger, report_fetched, credentials, state, ai, notify

LABEL_IDS = {"Invoice": "Label_1", "Customer": "Label_2", "Newsletter": "Label_3", "Needs reply": "Label_4"}
SCHEMA = {"type": "object", "properties": {
    "label": {"type": "string", "enum": list(LABEL_IDS)}, "urgent": {"type": "boolean"}},
    "required": ["label", "urgent"]}

@on_trigger
def run(event):
    gmail = build("gmail", "v1", credentials=Credentials(credentials.connection("google", "work")), cache_discovery=False)
    since = state.get("since") or 0
    q = "in:inbox" + (f" after:{since}" if since else " newer_than:1d")
    ids = [m["id"] for m in gmail.users().messages().list(userId="me", q=q, maxResults=50).execute().get("messages", [])]
    done = set(state.get("done") or [])
    new = [i for i in ids if i not in done]
    report_fetched(len(new))
    if not new:
        return {"summary": "Nothing new"}

    newest = since
    for mid in new:
        m = gmail.users().messages().get(userId="me", id=mid, format="metadata",
                                         metadataHeaders=["From", "Subject"]).execute()
        h = {x["name"]: x["value"] for x in m["payload"]["headers"]}
        text = f"From: {h.get('From')}\nSubject: {h.get('Subject')}\n{m.get('snippet', '')}"
        try:
            d = ai.generate(text, system="Label this email.", json_schema=SCHEMA, max_output_tokens=40).json
        except ai.AIError:
            d = {"label": "Needs reply", "urgent": False}
        gmail.users().messages().modify(userId="me", id=mid, body={"addLabelIds": [LABEL_IDS[d["label"]]]}).execute()
        if d["urgent"] and d["label"] == "Customer":
            notify.email_me("Urgent: " + (h.get("Subject") or "")[:150], text)
        newest = max(newest, int(m["internalDate"]) // 1000)

    state.set("since", newest)
    state.set("done", (list(done) + new)[-500:])
    return {"labelled": len(new)}
```

- Only the sender, subject and Gmail's short snippet are sent to the AI, not the full message or attachments.
- Label ids come from the one-time setup script that created the labels; the assistant writes them into the script.
- The automation remembers the newest message time and the last 500 message ids, so each message is labelled once.

## A schedule, not a trigger link

Use a schedule. Every 15 minutes suits most inboxes; 5 minutes is the shortest interval.

Checks that find no new mail return straight away and, when they finish quickly, aren't counted toward your monthly runs.

## Limits

- The shortest interval is every 5 minutes, so labels appear within minutes, not instantly.
- Up to 50 calls to the built-in AI per run; the script handles at most 50 messages per run and picks up the rest next time.
- Gmail access uses your own Google OAuth app added in the ClickRuntime dashboard.

## Troubleshooting

### Runs fail with 403 insufficient permissions.

The Google connection was made without Gmail access. Reconnect it in the ClickRuntime dashboard and allow Gmail.

### Labels are wrong for some senders.

Tell your assistant, for example “mail from billing@ is always Invoice”. It adds a rule before the AI step, which also saves AI tokens.

### It stopped labelling.

Check the run log in the ClickRuntime dashboard. A failed run sends you an email; ask your assistant to read the error and fix it.

## Related

- [Gmail automations](https://clickruntime.com/apps/gmail)
- [Slack automations](https://clickruntime.com/apps/slack)
- [Google Sheets automations](https://clickruntime.com/apps/google-sheets)
- [Outlook automations](https://clickruntime.com/apps/outlook)
- [triage-support-requests](https://clickruntime.com/templates/triage-support-requests)
- [follow-up-reminders-for-unanswered-sent-mail](https://clickruntime.com/templates/follow-up-reminders-for-unanswered-sent-mail)
- [AI triage and summaries](https://clickruntime.com/use-cases/ai-classify-and-summarise)
- [Inbox summary each morning](https://clickruntime.com/use-cases/email-summary-every-morning)
- [Stateful automations](https://clickruntime.com/use-cases/stateful-automations)
- [Google Apps Script alternative](https://clickruntime.com/alternatives/google-apps-script)
- [Assistant scheduled tasks alternative](https://clickruntime.com/alternatives/chatgpt-claude-scheduled-tasks)
- [Docs: connections-and-secrets](https://clickruntime.com/docs/connections-and-secrets)
- [Docs: state](https://clickruntime.com/docs/state)

## Extend it: what you can add next

The first version is rarely the last. Because the automation is a Python script with memory, AI and any API available, you grow it by asking your assistant for the change. Each change is a new version, and a failed deploy never replaces the working one.

- **Draft replies to customer messages and leave them in Gmail drafts** (Built-in AI)
  Prompt: "Change my Gmail AI labels automation so that for each Customer message it saves a short draft reply in Gmail for me to edit and send."
- **Post urgent customer messages to #support in Slack** (Any app or API)
  Prompt: "Change my Gmail AI labels automation so urgent customer messages are posted to #support in Slack instead of emailed to me."
- **Log every invoice email to a Google Sheet** (Any app or API)
  Prompt: "Add to my Gmail AI labels automation: for each Invoice message, add a row to my Invoices sheet with sender, subject and date."
- **Pull the amount and due date out of invoice emails** (Built-in AI)
  Prompt: "Change my Gmail AI labels automation so that for Invoice messages it also reads the amount and due date from the text and adds them to the Invoices sheet."
- **A 17:00 email listing messages still labelled Needs reply** (Schedules)
  Prompt: "Add to my Gmail AI labels automation: every weekday at 17:00, email me the messages labelled Needs reply that I haven't answered."
- **Learn senders: once a sender is labelled three times, skip AI for them** (Memory between runs)
  Prompt: "Change my Gmail AI labels automation so it remembers the label for each sender, and after three of the same, uses it without asking the AI."
- **Archive newsletters after labelling them** (Multi-step logic)
  Prompt: "Change my Gmail AI labels automation so Newsletter messages are labelled and archived out of the inbox."

## Questions

### Can ChatGPT automatically sort my Gmail?

With ClickRuntime connected, ChatGPT can set up an automation that labels new Gmail messages on a schedule, after the chat is closed. ChatGPT alone only acts while you chat.

### Does the AI read my whole email?

The example sends the sender, subject and Gmail's snippet only. You can choose what is sent; attachments are never sent.

### How quickly are messages labelled?

Within the schedule's interval: every 15 minutes in the example, every 5 at the shortest.

### Does it work with Outlook?

Yes, through Microsoft Graph with a Microsoft OAuth app added in the ClickRuntime dashboard. Ask your assistant for Outlook instead of Gmail.

### Do I need an OpenAI key?

No. The built-in AI needs no key and is included, including on the free plan.
