ClawMart AI
← Back to Blog
August 16, 20268 min readClaw Mart Team

Connect Your Gmail to OpenClaw: Full Setup Tutorial

Connect Your Gmail to OpenClaw: Full Setup Tutorial

Connect Your Gmail to OpenClaw: Full Setup Tutorial

Let's skip the preamble: connecting Gmail to OpenClaw should take about fifteen minutes, but most people burn an entire afternoon on it because the authentication setup is genuinely confusing the first time around. I've done this enough times now that I can walk you through the whole thing without you wanting to throw your laptop out a window.

This guide covers everything β€” setting up Google Cloud credentials, configuring OAuth2, wiring it into OpenClaw, and actually testing that it works. By the end, you'll have an OpenClaw agent that can read, send, and respond to emails from your Gmail account. Let's get into it.

Why This Is Harder Than It Should Be

Here's the thing nobody tells you upfront: connecting an email account to any AI agent platform is mostly an authentication problem, not a coding problem. The actual "read email, do something smart with it, send a reply" part is straightforward. The part where you convince Google that your application is trustworthy enough to access your inbox? That's where people lose hours.

Google killed "less secure app" access a while back. You can't just throw a username and password into a config file anymore. Everything goes through OAuth2 now, which is more secure but significantly more annoying to set up for the first time. App passwords sort of work as a stopgap, but they're flaky with automated systems and Google keeps tightening the screws on them.

OpenClaw handles the email interaction layer really well once it's connected β€” smart parsing, context management, rate limiting awareness β€” but it still needs you to hand it valid credentials. That's what we're going to set up.

Step 1: Create a Google Cloud Project

Before OpenClaw can talk to Gmail, you need a Google Cloud project with the Gmail API enabled. Here's the quick version:

  1. Go to console.cloud.google.com
  2. Click Select a Project β†’ New Project
  3. Name it something you'll recognize (e.g., "OpenClaw Email Agent")
  4. Once created, make sure it's selected as your active project

Now enable the Gmail API:

  1. Go to APIs & Services β†’ Library
  2. Search for "Gmail API"
  3. Click Enable

That's it for the API side. Now comes the fun part.

Step 2: Set Up OAuth2 Credentials

This is where most people get stuck, so I'm going to be very specific.

Configure the OAuth Consent Screen first:

  1. Go to APIs & Services β†’ OAuth consent screen
  2. Choose External (unless you have a Google Workspace org and only want internal users)
  3. Fill in the required fields β€” app name, user support email, developer contact email
  4. On the Scopes screen, add these Gmail scopes:
https://www.googleapis.com/auth/gmail.readonly
https://www.googleapis.com/auth/gmail.send
https://www.googleapis.com/auth/gmail.modify

If you only need to read emails, skip gmail.send and gmail.modify. Principle of least privilege and all that. But if you want your OpenClaw agent to actually reply to emails, you'll need all three.

  1. On the Test users screen, add the Gmail address you want to connect
  2. Save and continue

Now create the actual credentials:

  1. Go to APIs & Services β†’ Credentials
  2. Click Create Credentials β†’ OAuth client ID
  3. Application type: Desktop app (this is important β€” don't choose "Web application" unless you have a publicly accessible redirect URI set up)
  4. Name it whatever you want
  5. Click Create
  6. Download the JSON file β€” this is your credentials.json

Keep that JSON file safe. Don't commit it to Git. Don't put it in a shared folder. Treat it like a password.

Step 3: Configure OpenClaw for Gmail

Now we bring OpenClaw into the picture. In your OpenClaw project directory, you'll want to set up your email skill configuration. Here's the basic structure:

# openclaw-config.yaml
skills:
  email:
    provider: gmail
    auth:
      method: oauth2
      credentials_file: ./credentials.json
      token_file: ./token.json
      scopes:
        - gmail.readonly
        - gmail.send
        - gmail.modify
    settings:
      check_interval: 30
      max_results: 20
      smart_parsing: true
      strip_signatures: true
      html_to_text: true

Let me break down what matters here:

  • credentials_file: Points to the JSON you downloaded from Google Cloud
  • token_file: OpenClaw will create this automatically after the first OAuth flow β€” it stores your access and refresh tokens
  • smart_parsing: true: This is one of OpenClaw's best features. It strips out email signatures, forwarded message headers, HTML boilerplate, and "Sent from my iPhone" nonsense so your agent gets clean content to work with
  • strip_signatures: true: Specifically removes email signatures from parsed content so your agent doesn't try to respond to someone's job title
  • html_to_text: true: Converts HTML emails to clean plain text before passing them to the agent context

That check_interval of 30 seconds is a sane default. You can go lower, but be aware of Gmail API quotas β€” you get about 250 quota units per user per second, and each list/get request costs a few units. Going too aggressive here will get you rate-limited.

Step 4: Run the Initial Authentication

The first time you run your OpenClaw email skill, it needs to complete the OAuth flow. This means a browser window will pop up asking you to authorize access.

openclaw auth email

This will:

  1. Read your credentials.json
  2. Open a browser window to Google's consent screen
  3. Ask you to sign in and authorize the scopes you configured
  4. Save the resulting tokens to token.json

If you're running this on a headless server (no browser), use the --no-browser flag:

openclaw auth email --no-browser

This will print a URL to your terminal instead. Copy it, open it in any browser, authorize it, and paste the resulting code back into the terminal.

Important: If your app is still in "Testing" mode on Google Cloud (which it will be unless you've gone through verification), only the test users you added in Step 2 can authorize. If you try with a different Gmail account, it'll fail with a cryptic error. Don't let this haunt you for two hours like it haunted me.

Step 5: Build Your Email Agent

Now the actually fun part. Here's a practical example β€” an OpenClaw agent that monitors your inbox for customer support emails and drafts responses:

from openclaw import Agent, EmailSkill

# Initialize the email skill
email = EmailSkill(config="./openclaw-config.yaml")

# Create your agent
agent = Agent(
    name="Support Assistant",
    instructions="""You are a helpful customer support assistant. 
    When you receive a customer email:
    1. Identify the core issue
    2. Check if it matches a known FAQ
    3. Draft a helpful, friendly response
    4. Flag anything you're unsure about for human review
    
    Never make up policies. If you don't know, say you'll 
    escalate to the team.""",
    skills=[email]
)

# Define what happens when new emails arrive
@agent.on_event("email.received")
async def handle_incoming(event):
    message = event.message
    
    # OpenClaw's smart parsing already cleaned this up
    print(f"From: {message.sender}")
    print(f"Subject: {message.subject}")
    print(f"Body: {message.body}")  # Clean text, no HTML garbage
    
    # Get conversation context if it's a thread
    thread = await email.get_thread(message.thread_id)
    context = thread.summarize(max_tokens=2000)
    
    # Generate a response
    response = await agent.run(
        f"New email from {message.sender}:\n\n{message.body}",
        context=context
    )
    
    # Create a draft instead of auto-sending
    draft = await email.create_draft(
        to=message.sender,
        subject=f"Re: {message.subject}",
        body=response,
        in_reply_to=message.id
    )
    
    # Notify you for review
    await agent.notify(
        f"Draft ready for review: {draft.preview_url}",
        channel="default"
    )

# Run the agent
agent.run()

A few things to notice:

Draft-first approach. This agent creates drafts for you to review rather than auto-sending. I cannot stress enough how important this is when you're starting out. You do not want your AI agent replying-all to a 50-person thread with a hallucinated refund policy. Start with drafts, build trust, then gradually allow auto-sending for specific categories.

Thread summarization. The thread.summarize(max_tokens=2000) call is doing a lot of heavy lifting. Instead of dumping an entire 47-message email thread into the context (hello, $5/day API bills), OpenClaw summarizes the conversation history intelligently. It preserves the most recent messages in full and compresses older ones.

Clean content. By the time message.body reaches your agent, OpenClaw has already stripped HTML, removed signatures, cleaned up forwarding artifacts, and handled encoding issues. Your agent works with actual content, not a mess of <div style="font-family: Arial"> tags.

Step 6: Add Filtering and Safety Rails

You probably don't want your agent processing every email in your inbox. Here's how to add filters:

@agent.on_event("email.received", 
    filters={
        "labels": ["INBOX", "support"],
        "exclude_labels": ["HR", "Finance", "Personal"],
        "from_domains": ["*.com"],  # Or specific domains
        "exclude_from": ["noreply@", "newsletter@"]
    }
)
async def handle_incoming(event):
    # Only processes emails matching the filter criteria
    ...

And add rate limiting so you don't blow through Gmail API quotas:

email = EmailSkill(
    config="./openclaw-config.yaml",
    rate_limit={
        "sends_per_hour": 20,
        "reads_per_minute": 10,
        "warn_at_percentage": 80  # Warns you at 80% of limit
    }
)

Common Issues and Fixes

"Token has been expired or revoked" Delete your token.json file and re-run openclaw auth email. Tokens expire, and sometimes the refresh token fails silently.

"Access blocked: This app's request is invalid" You probably chose "Web application" instead of "Desktop app" when creating your OAuth credentials. Go back to Google Cloud Console, delete the credential, and create a new one as a Desktop app.

"403: Rate Limit Exceeded" You're hitting Gmail API quotas. Increase your check_interval, reduce max_results, or add exponential backoff to your configuration:

settings:
  retry:
    strategy: exponential
    max_retries: 3
    initial_delay: 5

Emails showing as raw HTML Make sure smart_parsing: true and html_to_text: true are both set in your config. If they're already set and you're still getting HTML, the email might be using a non-standard encoding β€” check the message.raw field to debug.

Agent responding to its own emails Add your agent's sending address to the exclusion filter. This is embarrassing but very common:

filters={
    "exclude_from": ["your-agent-email@gmail.com"]
}

Skip the Setup Headaches

Look, I've walked you through the full manual setup because it's important to understand what's happening under the hood. But I'll be honest β€” the first time I set this up, the OAuth configuration alone took me longer than I'd like to admit. The Google Cloud Console UI changes every few months, scopes are confusing, and there are a dozen little gotchas that only show up at runtime.

If you don't want to wrestle with all of this manually, Felix's OpenClaw Starter Pack on Claw Mart includes a pre-built email skill with the Gmail configuration already dialed in. It's $29 and it comes with pre-configured skills for email, plus a bunch of other common integrations. The email skill in that pack has smart parsing, rate limiting, draft workflows, and error handling already set up β€” basically everything I covered in this post, ready to go. You still need to create your own Google Cloud credentials (nobody can do that part for you), but everything on the OpenClaw side is handled. For the time it saves, it's a no-brainer.

What to Build Next

Once your Gmail connection is working, you've got a foundation for a lot of interesting automations:

  • Customer support triage: Auto-categorize incoming emails by urgency and topic, draft responses for common questions, escalate complex issues
  • Email summarizer: Get a daily digest of your important emails with AI-generated summaries instead of reading through everything
  • Follow-up tracker: Have your agent monitor sent emails and flag conversations where you haven't gotten a reply in X days
  • Meeting prep: When you get a meeting invite, have the agent pull relevant email threads with that person and prepare a brief

The email skill is one of those building blocks that unlocks a surprising number of workflows once it's connected. The hard part β€” the part you just finished β€” is getting the authentication right. Everything else is just creative application of an agent that can read and write emails.

Now go build something useful with it.

Recommended for this post

πŸ€–

Your AI sales rep that sources leads, finds contacts, and runs full cold outreach sequences β€” on autopilot.

All platformsSales
EC
Emil Claw
$29Buy
Clarence Jr.

Clarence Jr.

Operator

The solo founder's ops operator β€” leads, email, revenue, and client management on autopilot. Use in Gmail, Notion, Slack. 24/7 Support.

All platformsSupport8 sold
Clarence MakerClarence Maker
$19Buy

Claw Mart Daily

Get one AI agent tip every morning

Free daily tips to make your OpenClaw agent smarter. No spam, unsubscribe anytime.

More From the Blog