Skip to main content

Gmail - Advanced Search

Search Gmail with advanced filters including labels, attachments, and pagination. Requires OAuth authentication for full Gmail API access.

Overview

The Gmail Advanced Search tool provides power user features through the Gmail API, including label filtering, attachment searches, and pagination for handling large result sets.

Key Features:

  • All Simple Search features (text, sender, subject, dates, read/unread)
  • Gmail label filtering (INBOX, IMPORTANT, STARRED, etc.)
  • Attachment filtering
  • Pagination support for unlimited results
  • Up to 500 results per page
  • OAuth-only for full Gmail API capabilities

When to Use Advanced Search:

  • You need to filter by Gmail labels
  • You want emails with specific attachments
  • You need more than 100 results
  • You want to paginate through large result sets
  • You're comfortable with OAuth setup

When to Use Simple Search Instead:

  • Basic filters are sufficient
  • You're using App Password authentication
  • You need 100 results or fewer

Prerequisites

OAuth Authentication Required: This tool only works with OAuth authentication. App Password accounts will return an error.

Setup OAuth

Follow our Google Account OAuth Setup Guide to:

  1. Create a Google Cloud project
  2. Enable Gmail API
  3. Create OAuth credentials
  4. Connect your account to Reeva

App Password authentication is not supported for Advanced Search.

Using the Tool

1. Create an Advanced Search Tool Instance

  1. Navigate to My Tools in Reeva
  2. Click Create New Tool
  3. Select Gmail - Advanced Search from the base tools
  4. Give your tool a name (e.g., "Power Search Gmail")
  5. Select your OAuth Gmail account (not App Password)
  6. Click Create

2. Search with Labels

Filter by Gmail labels:

{
"label_ids": ["INBOX", "IMPORTANT"],
"max_results": 20
}

Common Gmail Label IDs

LabelIDDescription
InboxINBOXMain inbox
SentSENTSent mail
DraftsDRAFTDraft emails
SpamSPAMSpam folder
TrashTRASHDeleted emails
UnreadUNREADUnread messages
StarredSTARREDStarred emails
ImportantIMPORTANTImportant emails
Category SocialCATEGORY_SOCIALSocial updates
Category PromotionsCATEGORY_PROMOTIONSPromotional emails
Category UpdatesCATEGORY_UPDATESUpdate notifications
Category ForumsCATEGORY_FORUMSForum messages

You can also use custom label names if you've created them in Gmail.

3. Search for Emails with Attachments

Find all emails with attachments:

{
"has_attachment": true,
"max_results": 50
}

Combine with other filters:

{
"has_attachment": true,
"sender": "reports@company.com",
"after_date": "2024/10/01"
}

4. Pagination for Large Results

Search through large result sets using pagination:

First Request:

{
"query": "project alpha",
"max_results": 100
}

Response includes next_page_token:

{
"results": [...100 emails...],
"result_count": 100,
"next_page_token": "CAEQAA"
}

Second Request (next page):

{
"query": "project alpha",
"max_results": 100,
"page_token": "CAEQAA"
}

Third Request (and so on):

{
"query": "project alpha",
"max_results": 100,
"page_token": "<token_from_previous_response>"
}

Continue until next_page_token is null.

5. Complex Queries

Combine all advanced features:

{
"query": "quarterly report",
"sender": "finance@company.com",
"label_ids": ["INBOX", "IMPORTANT"],
"has_attachment": true,
"after_date": "2024/10/01",
"before_date": "2024/12/31",
"is_unread": false,
"max_results": 200
}

This finds read emails from finance with attachments, containing "quarterly report", labeled INBOX and IMPORTANT, between Oct and Dec 2024.

Tool Parameters

ParameterTypeRequiredDescription
querystringNoSearch text (subject and body)
max_resultsintegerNoResults per page (1-500, default 10)
page_tokenstringNoPagination token from previous response
senderstringNoFilter by sender email
subjectstringNoFilter by subject keywords
after_datestringNoEmails after date (flexible formats)
before_datestringNoEmails before date (flexible formats)
has_attachmentbooleanNoFilter emails with attachments
is_unreadbooleanNoFilter by read status
label_idsarray[string]NoFilter by Gmail label IDs

Note: max_results can go up to 500 (vs 100 in Simple Search). Use pagination for even larger searches.

Response Format

{
"results": [
{
"message_id": "18d5f2a3b4c5d6e7",
"thread_id": "18d5f2a3b4c5d6e7",
"subject": "Q4 Report with Charts",
"from": "Finance Team <finance@company.com>",
"to": "me@company.com",
"date": "Mon, 6 Dec 2024 14:20:00 -0800",
"snippet": "Attached is the Q4 financial report...",
"labels": ["INBOX", "IMPORTANT"],
"is_unread": false,
"has_attachment": true
}
],
"result_count": 1,
"next_page_token": "CAEQAA",
"query": "quarterly report from:finance@company.com label:INBOX label:IMPORTANT has:attachment after:2024/10/01 before:2024/12/31"
}

Response Fields

  • results: Array of email objects (same structure as Simple Search)
  • result_count: Number of results in this page
  • next_page_token: Token for next page (null if no more results)
  • query: The Gmail API query that was executed

Important: Message ID Compatibility

⚠️ Advanced Search uses OAuth only, so message IDs are Gmail API format:

  • Returns long hexadecimal message IDs (e.g., "18d5f2a3b4c5d6e7")
  • Can ONLY be used with OAuth authentication in other tools (like Read Email)
  • Cannot be used with App Password/IMAP authentication

When using these message IDs with other tools:

  • ✅ Advanced Search (OAuth) → Read with OAuth
  • ❌ Advanced Search (OAuth) → Read with App Password (will fail)

See Read Email documentation for more details.

Pagination Strategy

Option 1: Fetch All Results

all_results = []
page_token = None

while True:
response = search_gmail_advanced({
"query": "important emails",
"max_results": 500,
"page_token": page_token
})

all_results.extend(response["results"])
page_token = response.get("next_page_token")

if not page_token:
break

print(f"Found {len(all_results)} total emails")

Option 2: Lazy Loading

Fetch pages as needed, showing results incrementally to users.

Option 3: Limit Total Results

Set a maximum to avoid excessive API calls:

max_total = 1000
collected = []
page_token = None

while len(collected) < max_total:
remaining = max_total - len(collected)
response = search_gmail_advanced({
"query": "project",
"max_results": min(500, remaining),
"page_token": page_token
})

collected.extend(response["results"])
page_token = response.get("next_page_token")

if not page_token:
break

Error Handling

OAuth Required Error

{
"error": "Advanced Search requires OAuth authentication. Please use a Google OAuth account or use Simple Search with App Password."
}

Solution: You're trying to use Advanced Search with an App Password account. Either:

  1. Switch to an OAuth account, or
  2. Use Simple Search instead

Invalid Label ID

If you use an incorrect label ID:

{
"error": "Gmail API search failed: Invalid label: INVALID_LABEL"
}

Solution: Check the Common Gmail Label IDs table above, or verify custom label spelling.

Rate Limit Exceeded

{
"error": "Gmail API search failed: User rate limit exceeded"
}

Solution:

  • Wait a few minutes before retrying
  • Reduce max_results to make fewer requests
  • Space out pagination requests

Date Format Errors

Same as Simple Search - use flexible date formats. The tool auto-converts.

Use Cases

1. Find All Important Unread Emails

{
"label_ids": ["IMPORTANT"],
"is_unread": true,
"max_results": 50
}

2. Export All Emails from Q4

{
"after_date": "2024/10/01",
"before_date": "2024/12/31",
"max_results": 500
}

Use pagination to fetch all results.

3. Find Invoices with PDFs

{
"query": "invoice",
"has_attachment": true,
"sender": "billing@vendor.com",
"after_date": "2024/01/01"
}

4. Clean Up Old Promotional Emails

{
"label_ids": ["CATEGORY_PROMOTIONS"],
"before_date": "2024/01/01",
"max_results": 500
}

Paginate through all results for bulk operations.

5. Search Starred Emails from VIP

{
"label_ids": ["STARRED"],
"sender": "ceo@company.com",
"max_results": 100
}

Advanced Tips

1. Optimize max_results

  • Use 500 for fastest bulk fetching
  • Use 10-50 for interactive searches
  • Balance API quota with user experience

2. Combine Labels Smartly

Multiple labels use AND logic:

{
"label_ids": ["INBOX", "IMPORTANT", "UNREAD"]
}

Returns emails in ALL three categories.

3. Use Pagination Wisely

  • Don't fetch more pages than you need
  • Cache results client-side to avoid re-fetching
  • Set reasonable max_total limits (e.g., 1000-5000)

4. Date Ranges for Performance

Narrow searches with date ranges to reduce API load:

{
"after_date": "2024/11/01",
"before_date": "2024/11/30"
}

5. Combine with Attachment Filter

Finding specific document types:

{
"query": "contract",
"has_attachment": true,
"label_ids": ["INBOX"],
"after_date": "2024/01/01"
}

OAuth Scope Required

This tool requires the following Gmail API scope:

  • https://mail.google.com/ (Full Gmail access)

This is automatically requested during OAuth setup.

Troubleshooting

"OAuth credentials required"

Cause: Using App Password account with Advanced Search

Solution:

  • Use OAuth account instead
  • Or switch to Simple Search if App Password is required

Pagination token expired

Cause: Tokens expire after ~1 hour

Solution: Start a fresh search if token expires

"Invalid or expired token"

Cause: OAuth access token expired

Solution:

  1. Tool automatically refreshes tokens
  2. If persists, disconnect and reconnect Gmail account

No labels returned

Cause: Using IMAP (shouldn't happen with Advanced Search)

Solution: Verify you're using OAuth account, not App Password

Support

Need help? Reach out to our support team or join our Discord community.