Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
feat: added gmail api integration to get OTPs and email
Saurav Panda5f697d97bde8
diff --git a/.gitignore b/.gitignoreindex c9d3ecbe5..9ea402407 100644--- a/.gitignore+++ b/.gitignore@@ -46,3 +46,7 @@ CLAUDE.local.mduv.locktemptmp++# Google API credentials+credentials.json+token.json\ No newline at end of filediff --git a/browser_use/integrations/gmail/__init__.py b/browser_use/integrations/gmail/__init__.pynew file mode 100644index 000000000..797c3b8ab--- /dev/null+++ b/browser_use/integrations/gmail/__init__.py@@ -0,0 +1,24 @@+"""+Gmail Integration for Browser Use+Provides Gmail API integration for handling 2FA codes and email reading.+This integration enables agents to authenticate via email when 2FA is required.+Usage:+ from browser_use.integrations.gmail import GmailService, register_gmail_actions+ # Option 1: Register Gmail actions with file-based authentication+ controller = Controller()+ register_gmail_actions(controller)+ # Option 2: Register Gmail actions with direct access token (recommended for production)+ controller = Controller()+ register_gmail_actions(controller, access_token="your_access_token_here")+ # Option 3: Use the service directly+ gmail = GmailService(access_token="your_access_token_here")+ await gmail.authenticate()+ codes = await gmail.find_2fa_codes()+"""++# @file purpose: Gmail integration for 2FA email authentication and email reading++from .service import GmailService+from .actions import register_gmail_actions++__all__ = ['GmailService', 'register_gmail_actions']\ No newline at end of filediff --git a/browser_use/integrations/gmail/actions.py b/browser_use/integrations/gmail/actions.pynew file mode 100644index 000000000..2a3ce9ec2--- /dev/null+++ b/browser_use/integrations/gmail/actions.py@@ -0,0 +1,230 @@+"""+Gmail Actions for Browser Use+Defines agent actions for Gmail integration including 2FA code retrieval,+email reading, and authentication management.+"""++import asyncio+import logging+from typing import Optional, List, Dict, Any+from pydantic import BaseModel, Field++from browser_use.agent.views import ActionResult+from browser_use.controller.service import Controller+from .service import GmailService++logger = logging.getLogger(__name__)++# Global Gmail service instance - initialized when actions are registered+_gmail_service: Optional[GmailService] = None+++class Find2FACodesParams(BaseModel):+ """Parameters for finding 2FA codes in emails"""++ time_filter: str = Field(default='2m', description='Time filter for emails (e.g., "2m", "5m", "1h", "1d")')+ sender_email: Optional[str] = Field(default=None, description='Filter by specific sender email address')+ custom_patterns: Optional[List[str]] = Field(default=None, description='Additional regex patterns to search for codes')+++class GetRecentEmailsParams(BaseModel):+ """Parameters for getting recent emails"""++ max_results: int = Field(default=10, description='Maximum number of emails to fetch')+ query: str = Field(default='', description='Gmail search query (e.g., "from:[email protected]")')+ time_filter: str = Field(default='1h', description='Time filter for emails (e.g., "5m", "1h", "1d")')+++def register_gmail_actions(+ controller: Controller, gmail_service: Optional[GmailService] = None, access_token: Optional[str] = None+) -> None:+ """+ Register Gmail actions with the provided controller+ Args:+ controller: The browser-use controller to register actions with+ gmail_service: Optional pre-configured Gmail service instance+ access_token: Optional direct access token (alternative to file-based auth)+ """+ global _gmail_service++ # Use provided service or create a new one with access token if provided+ if gmail_service:+ _gmail_service = gmail_service+ elif access_token:+ _gmail_service = GmailService(access_token=access_token)+ else:+ _gmail_service = GmailService()++ @controller.action(+ description='π **USE THIS FOR VERIFICATION CODES - NOT get_recent_emails** π '+ 'When you need verification codes/OTP/2FA: USE THIS ACTION IMMEDIATELY! '+ 'This searches Gmail, finds codes, extracts them automatically. '+ 'DO NOT use get_recent_emails for verification - it cannot extract codes! '+ 'This action is specifically built for code extraction from emails. '+ 'One call gets you the actual numeric code ready to input.',+ param_model=Find2FACodesParams,+ )+ async def find_2fa_codes(params: Find2FACodesParams) -> ActionResult:+ """Find 2FA verification codes in recent emails"""+ try:+ if _gmail_service is None:+ raise RuntimeError('Gmail service not initialized')++ # Ensure authentication+ if not _gmail_service.is_authenticated():+ logger.info('π§ Gmail not authenticated, attempting authentication...')+ authenticated = await _gmail_service.authenticate()+ if not authenticated:+ return ActionResult(+ extracted_content='β Failed to authenticate with Gmail. Please ensure Gmail credentials are set up properly.',+ include_in_memory=True,+ )++ # Find 2FA codes with retry logic (4 attempts with longer waits for email delivery)+ max_retries = 4+ codes_found = None+ wait_times = [10, 20, 30] # 10s, 20s, 30s (total 60s wait time)++ for attempt in range(max_retries):+ # Ensure authentication before each attempt+ if not _gmail_service.is_authenticated():+ logger.info(f'π§ Gmail not authenticated (attempt {attempt + 1}), attempting authentication...')+ authenticated = await _gmail_service.authenticate()+ if not authenticated:+ logger.warning(f'β Gmail authentication failed on attempt {attempt + 1}')+ # Continue to next attempt rather than failing immediately+ if attempt < max_retries - 1:+ wait_time = wait_times[attempt]+ logger.info(f'π Retrying authentication in {wait_time}s...')+ await asyncio.sleep(wait_time)+ continue++ codes_found = await _gmail_service.find_2fa_codes(+ time_filter=params.time_filter, sender_email=params.sender_email, custom_patterns=params.custom_patterns+ )++ if codes_found:+ break++ # If not the last attempt, wait for email delivery+ if attempt < max_retries - 1:+ wait_time = wait_times[attempt]+ logger.info(f'π No 2FA codes found (attempt {attempt + 1}/{max_retries}), retrying in {wait_time}s...')+ await asyncio.sleep(wait_time)++ if not codes_found:+ return ActionResult(+ extracted_content=f'π No 2FA codes found in emails from the last {params.time_filter} after {max_retries} attempts. '+ f'{"Filter: " + params.sender_email if params.sender_email else ""}',+ include_in_memory=True,+ )++ # Format results+ results = []+ for email_with_codes in codes_found:+ results.append(+ {+ 'codes': email_with_codes['codes'],+ 'from': email_with_codes['from'],+ 'subject': email_with_codes['subject'],+ 'snippet': email_with_codes['body_snippet'],+ }+ )++ # Return the most recent code as the primary result+ primary_code = codes_found[0]['codes'][0]++ content = f'β Found 2FA code: {primary_code}\n'+ content += f'π§ From: {codes_found[0]["from"]}\n'+ content += f'π Subject: {codes_found[0]["subject"]}\n'++ if len(codes_found) > 1:+ content += f'\nπ Additional {len(codes_found) - 1} emails with codes found.'++ return ActionResult(extracted_content=content, include_in_memory=True)++ except Exception as e:+ logger.error(f'Error finding 2FA codes: {e}')+ return ActionResult(extracted_content=f'β Error finding 2FA codes: {str(e)}', include_in_memory=True)++ @controller.action(+ description='π§ **General Email Reading** - For newsletters, notifications, and email content analysis. '+ 'β οΈ DO NOT use when you need verification codes, OTP, 2FA, or login codes! '+ "For any verification scenario, use find_2fa_codes instead - it's specifically designed for that. "+ 'This action has limited search capabilities that miss verification emails.',+ param_model=GetRecentEmailsParams,+ )+ async def get_recent_emails(params: GetRecentEmailsParams) -> ActionResult:+ """Get recent emails from Gmail"""+ try:+ if _gmail_service is None:+ raise RuntimeError('Gmail service not initialized')++ # Ensure authentication+ if not _gmail_service.is_authenticated():+ logger.info('π§ Gmail not authenticated, attempting authentication...')+ authenticated = await _gmail_service.authenticate()+ if not authenticated:+ return ActionResult(+ extracted_content='β Failed to authenticate with Gmail. Please ensure Gmail credentials are set up properly.',+ include_in_memory=True,+ )++ # Get emails+ emails = await _gmail_service.get_recent_emails(+ max_results=params.max_results, query=params.query, time_filter=params.time_filter+ )++ if not emails:+ query_info = f" matching '{params.query}'" if params.query else ''+ return ActionResult(+ extracted_content=f'π No emails found from the last {params.time_filter}{query_info}', include_in_memory=True+ )++ # Format email summary+ content = f'π§ Found {len(emails)} recent emails:\n\n'++ for i, email in enumerate(emails[:5], 1): # Show first 5 emails+ content += f'{i}. From: {email["from"]}\n'+ content += f' Subject: {email["subject"]}\n'+ content += f' Preview: {email["body"][:100]}...\n\n'++ if len(emails) > 5:+ content += f'... and {len(emails) - 5} more emails'++ return ActionResult(extracted_content=content, include_in_memory=True)++ except Exception as e:+ logger.error(f'Error getting recent emails: {e}')+ return ActionResult(extracted_content=f'β Error getting recent emails: {str(e)}', include_in_memory=True)++ @controller.action(+ description='π§ **Gmail Setup** - Establishes Gmail connection for email access. '+ 'Usually auto-handled, but call this if email actions report authentication errors. '+ 'Enables automatic retrieval of verification codes and email content.',+ )+ async def authenticate_gmail() -> ActionResult:+ """Authenticate with Gmail API"""+ try:+ if _gmail_service is None:+ raise RuntimeError('Gmail service not initialized')++ authenticated = await _gmail_service.authenticate()++ if authenticated:+ return ActionResult(+ extracted_content='β Successfully authenticated with Gmail API. Ready to read emails.',+ include_in_memory=True,+ )+ else:+ return ActionResult(+ extracted_content='β Failed to authenticate with Gmail. Please check your credentials setup:\n'+ '1. Download OAuth credentials from Google Cloud Console\n'+ "2. Save as 'gmail_credentials.json' in ~/.config/browseruse/\n"+ '3. Try again',+ include_in_memory=True,+ )++ except Exception as e:+ logger.error(f'Error authenticating Gmail: {e}')+ return ActionResult(extracted_content=f'β Error authenticating with Gmail: {str(e)}', include_in_memory=True)\ No newline at end of filediff --git a/browser_use/integrations/gmail/service.py b/browser_use/integrations/gmail/service.pynew file mode 100644index 000000000..94d004de0--- /dev/null+++ b/browser_use/integrations/gmail/service.py@@ -0,0 +1,368 @@+"""+Gmail API Service for Browser Use+Handles Gmail API authentication, email reading, and 2FA code extraction.+This service provides a clean interface for agents to interact with Gmail.+"""++import os+import re+import time+import base64+import logging+import asyncio+from typing import List, Dict, Optional, Any+from pathlib import Path++from google.auth.transport.requests import Request+from google.oauth2.credentials import Credentials+from google_auth_oauthlib.flow import InstalledAppFlow+from googleapiclient.discovery import build+from googleapiclient.errors import HttpError++from browser_use.config import CONFIG++logger = logging.getLogger(__name__)+++class GmailService:+ """+ Gmail API service for email reading and 2FA code extraction.+ Provides functionality to:+ - Authenticate with Gmail API using OAuth2+ - Read recent emails with filtering+ - Extract 2FA codes from email content+ - Poll for new 2FA codes+ """++ # Gmail API scopes+ SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']++ def __init__(+ self,+ credentials_file: Optional[str] = None,+ token_file: Optional[str] = None,+ config_dir: Optional[str] = None,+ access_token: Optional[str] = None,+ ):+ """+ Initialize Gmail Service+ Args:+ credentials_file: Path to OAuth credentials JSON from Google Cloud Console+ token_file: Path to store/load access tokens+ config_dir: Directory to store config files (defaults to browser-use config directory)+ access_token: Direct access token (skips file-based auth if provided)+ """+ # Set up configuration directory using browser-use's config system+ if config_dir is None:+ self.config_dir = CONFIG.BROWSER_USE_CONFIG_DIR+ else:+ self.config_dir = Path(config_dir).expanduser().resolve()++ # Ensure config directory exists (only if not using direct token)+ if access_token is None:+ self.config_dir.mkdir(parents=True, exist_ok=True)++ # Set up credential paths+ self.credentials_file = credentials_file or self.config_dir / 'gmail_credentials.json'+ self.token_file = token_file or self.config_dir / 'gmail_token.json'++ # Direct access token support+ self.access_token = access_token++ self.service = None+ self.creds = None+ self._authenticated = False++ def is_authenticated(self) -> bool:+ """Check if Gmail service is authenticated"""+ return self._authenticated and self.service is not None++ async def authenticate(self) -> bool:+ """+ Handle OAuth authentication and token management+ Returns:+ bool: True if authentication successful, False otherwise+ """+ try:+ logger.info('π Authenticating with Gmail API...')++ # Check if using direct access token+ if self.access_token:+ logger.info('π Using provided access token')+ # Create credentials from access token+ self.creds = Credentials(token=self.access_token, scopes=self.SCOPES)+ # Test token validity by building service+ self.service = build('gmail', 'v1', credentials=self.creds)+ self._authenticated = True+ logger.info('β Gmail API ready with access token!')+ return True++ # Original file-based authentication flow+ # Try to load existing tokens+ if os.path.exists(self.token_file):+ self.creds = Credentials.from_authorized_user_file(str(self.token_file), self.SCOPES)+ logger.debug('π Loaded existing tokens')++ # If no valid credentials, run OAuth flow+ if not self.creds or not self.creds.valid:+ if self.creds and self.creds.expired and self.creds.refresh_token:+ logger.info('π Refreshing expired tokens...')+ self.creds.refresh(Request())+ else:+ logger.info('π Starting OAuth flow...')+ if not os.path.exists(self.credentials_file):+ logger.error(+ f'β Gmail credentials file not found: {self.credentials_file}\n'+ 'Please download it from Google Cloud Console:\n'+ '1. Go to https://console.cloud.google.com/\n'+ '2. APIs & Services > Credentials\n'+ '3. Download OAuth 2.0 Client JSON\n'+ f"4. Save as 'gmail_credentials.json' in {self.config_dir}/"+ )+ return False++ flow = InstalledAppFlow.from_client_secrets_file(str(self.credentials_file), self.SCOPES)+ # Use specific redirect URI to match OAuth credentials+ self.creds = flow.run_local_server(port=8080, open_browser=True)++ # Save tokens for next time+ with open(self.token_file, 'w') as token:+ token.write(self.creds.to_json())+ logger.info(f'πΎ Tokens saved to {self.token_file}')++ # Build Gmail service+ self.service = build('gmail', 'v1', credentials=self.creds)+ self._authenticated = True+ logger.info('β Gmail API ready!')+ return True++ except Exception as e:+ logger.error(f'β Gmail authentication failed: {e}')+ return False++ async def get_recent_emails(self, max_results: int = 10, query: str = '', time_filter: str = '1h') -> List[Dict[str, Any]]:+ """+ Get recent emails with optional query filter+ Args:+ max_results: Maximum number of emails to fetch+ query: Gmail search query (e.g., 'from:[email protected]')+ time_filter: Time filter (e.g., '5m', '1h', '1d')+ Returns:+ List of email dictionaries with parsed content+ """+ if not self.is_authenticated():+ logger.error('β Gmail service not authenticated. Call authenticate() first.')+ return []++ try:+ # Add time filter to query if provided+ if time_filter and 'newer_than:' not in query:+ query = f'newer_than:{time_filter} {query}'.strip()++ logger.info(f'π§ Fetching {max_results} recent emails...')+ if query:+ logger.debug(f'π Query: {query}')++ # Get message list+ assert self.service is not None+ results = self.service.users().messages().list(userId='me', maxResults=max_results, q=query).execute()++ messages = results.get('messages', [])+ if not messages:+ logger.info('π No messages found')+ return []++ logger.info(f'π¨ Found {len(messages)} messages, fetching details...')++ # Get full message details+ emails = []+ for i, message in enumerate(messages, 1):+ logger.debug(f'π Reading email {i}/{len(messages)}...')++ full_message = self.service.users().messages().get(userId='me', id=message['id'], format='full').execute()++ email_data = self._parse_email(full_message)+ emails.append(email_data)++ return emails++ except HttpError as error:+ logger.error(f'β Gmail API error: {error}')+ return []+ except Exception as e:+ logger.error(f'β Unexpected error fetching emails: {e}')+ return []++ def _parse_email(self, message: Dict[str, Any]) -> Dict[str, Any]:+ """Parse Gmail message into readable format"""+ headers = {h['name']: h['value'] for h in message['payload']['headers']}++ return {+ 'id': message['id'],+ 'thread_id': message['threadId'],+ 'subject': headers.get('Subject', ''),+ 'from': headers.get('From', ''),+ 'to': headers.get('To', ''),+ 'date': headers.get('Date', ''),+ 'timestamp': int(message['internalDate']),+ 'body': self._extract_body(message['payload']),+ 'raw_message': message,+ }++ def _extract_body(self, payload: Dict[str, Any]) -> str:+ """Extract email body from payload"""+ body = ''++ if payload.get('body', {}).get('data'):+ # Simple email body+ body = base64.urlsafe_b64decode(payload['body']['data']).decode('utf-8')+ elif payload.get('parts'):+ # Multi-part email+ for part in payload['parts']:+ if part['mimeType'] == 'text/plain' and part.get('body', {}).get('data'):+ part_body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8')+ body += part_body+ elif part['mimeType'] == 'text/html' and not body and part.get('body', {}).get('data'):+ # Fallback to HTML if no plain text+ body = base64.urlsafe_b64decode(part['body']['data']).decode('utf-8')++ return body++ async def find_2fa_codes(+ self, time_filter: str = '5m', sender_email: Optional[str] = None, custom_patterns: Optional[List[str]] = None+ ) -> List[Dict[str, Any]]:+ """+ Find 2FA verification codes in recent emails+ Args:+ time_filter: Time filter for emails (e.g., '5m', '1h', '1d')+ sender_email: Filter by specific sender email+ custom_patterns: Additional regex patterns to look for codes+ Returns:+ List of emails containing potential 2FA codes+ """+ logger.info(f'π Looking for 2FA codes in emails from last {time_filter}...')++ # Build search query for 2FA-related emails - very inclusive with simple terms+ query_parts = [+ f'newer_than:{time_filter}',+ '(code OR otp OR "one time password" OR "verification code" OR 2FA OR "two-factor" OR "authentication code" OR verify OR "login code" OR "access your account" OR "sign in" OR "enter the code")',+ ]++ if sender_email:+ query_parts.append(f'from:{sender_email}')++ query = ' '.join(query_parts)+ logger.info(f'π Gmail search query: {query}')++ emails = await self.get_recent_emails(max_results=10, query=query)++ codes_found = []++ for email in emails:+ codes = self._extract_codes_from_text(email['body'], custom_patterns)+ if codes:+ codes_found.append(+ {+ 'subject': email['subject'],+ 'from': email['from'],+ 'timestamp': email['timestamp'],+ 'codes': codes,+ 'body_snippet': email['body'][:200] + '...' if len(email['body']) > 200 else email['body'],+ 'email_id': email['id'],+ }+ )++ # Sort by timestamp (most recent first) and keep only the most recent per sender+ codes_found.sort(key=lambda x: x['timestamp'], reverse=True)++ # Group by sender and keep only the most recent from each+ seen_senders = set()+ filtered_codes = []+ for email_with_codes in codes_found:+ sender = email_with_codes['from']+ if sender not in seen_senders:+ seen_senders.add(sender)+ filtered_codes.append(email_with_codes)++ logger.info(f'π― Found {len(filtered_codes)} recent emails with 2FA codes (most recent per sender)')+ return filtered_codes++ def _extract_codes_from_text(self, text: str, custom_patterns: Optional[List[str]] = None) -> List[str]:+ """Extract potential verification codes from text"""+ if not text:+ return []++ # Common 2FA code patterns - prioritize context-specific patterns to avoid URL noise+ patterns = [+ # High priority: Context-specific patterns+ r'(?:code|verification|OTP)[:\s]+(\d{4,8})', # "code: 123456"+ r'(?:your|the)\s+(?:code|verification)\s+(?:is|code)[:\s]+(\d{4,8})', # "your code is 123456"+ r'(?:enter|use)\s+(?:code|verification)[:\s]+(\d{4,8})', # "enter code: 123456"+ r'(?:below|code)\.\s*(\d{4,8})', # "code below. 12345"+ r'(?:emailCode=)(\d{4,8})', # URL parameter like emailCode=77599+ # Lower priority: Standalone numbers (but exclude those in long URLs)+ r'(?<![\w\-])\d{5}(?![\w\-])', # 5-digit codes (like 80565) not in URLs+ r'(?<![\w\-])\d{6}(?![\w\-])', # 6-digit codes (most common) not in URLs+ ]++ # Add custom patterns if provided+ if custom_patterns:+ patterns.extend(custom_patterns)++ found_codes_with_priority = []++ for i, pattern in enumerate(patterns):+ matches = re.findall(pattern, text, re.IGNORECASE)+ for match in matches:+ code = match if isinstance(match, str) else str(match)+ # Assign priority based on pattern order (earlier patterns = higher priority)+ priority = len(patterns) - i+ found_codes_with_priority.append((code, priority))++ # Filter out codes from long URLs (except emailCode parameter)+ filtered_codes_with_priority = []+ for code, priority in found_codes_with_priority:+ # Skip codes that are part of long URL UUIDs or tokens+ code_index = text.find(code)+ if code_index != -1:+ # Check surrounding context for URL patterns+ context_start = max(0, code_index - 30)+ context_end = min(len(text), code_index + len(code) + 30)+ context = text[context_start:context_end]++ # Skip if it's part of a UUID in a URL (like af6e5ca8-f2ae-4932-97d9)+ if re.search(r'[a-f0-9]{8}-[a-f0-9]{4}-' + re.escape(code) + r'-[a-f0-9]{4}', context):+ continue++ # Special case: emailCode parameter gets highest priority+ if 'emailCode=' in context:+ priority = 1000++ filtered_codes_with_priority.append((code, priority))++ # Sort by priority (highest first) and remove duplicates+ filtered_codes_with_priority.sort(key=lambda x: x[1], reverse=True)++ # Remove duplicates while preserving priority order+ seen = set()+ unique_codes = []+ for code, priority in filtered_codes_with_priority:+ if code not in seen and 4 <= len(code) <= 8 and re.match(r'^\d+$', code):+ seen.add(code)+ unique_codes.append(code)++ # If no numeric codes found, allow alphanumeric but with stricter filtering+ if not unique_codes:+ for code, priority in filtered_codes_with_priority:+ if (+ code not in seen+ and 4 <= len(code) <= 8+ and re.match(r'^[A-Z0-9]+$', code, re.IGNORECASE)+ and not re.match(r'^[A-F0-9]{6}$', code) # Exclude likely hex color codes+ and code+ not in ['header', 'padding', 'button', 'margin', 'border', 'center', 'hidden', 'normal', 'mobile', 'device']+ ):+ seen.add(code)+ unique_codes.append(code)++ return unique_codesdiff --git a/examples/integrations/gmail_2fa_integration.py b/examples/integrations/gmail_2fa_integration.pynew file mode 100644index 000000000..c53931173--- /dev/null+++ b/examples/integrations/gmail_2fa_integration.py@@ -0,0 +1,107 @@+"""+Gmail 2FA Integration Example+This example demonstrates how to use the Gmail integration for handling 2FA codes+during web automation. The agent can automatically retrieve verification codes+from Gmail when encountering 2FA requirements.+Setup:+1. Enable Gmail API in Google Cloud Console+2. Create OAuth 2.0 credentials and download JSON+3. Save credentials as ~/.config/browseruse/gmail_credentials.json+4. Run this example - it will guide you through OAuth setup+"""++import asyncio+import os+import sys+from dotenv import load_dotenv++# Add the parent directory to the path so we can import browser_use+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++load_dotenv()++from browser_use import Agent, Controller+from browser_use.llm import ChatOpenAI+from browser_use.integrations.gmail import register_gmail_actions+++async def main():+ print('π Gmail 2FA Integration Example')+ print('=' * 50)++ # Initialize controller and register Gmail actions+ controller = Controller()+ register_gmail_actions(controller)++ print('β Gmail actions registered with controller')+ print('Available Gmail actions:')+ print('- find_2fa_codes: Find 2FA codes in recent emails')+ print('- poll_for_2fa_code: Wait for new 2FA code from specific sender')+ print('- get_recent_emails: Get recent emails with filtering')+ print('- authenticate_gmail: Authenticate with Gmail API')+ print()++ # Initialize LLM+ llm = ChatOpenAI(model='gpt-4o')++ # Example 1: Basic Gmail authentication test+ print('π§ Testing Gmail authentication...')+ agent = Agent(task='Authenticate with Gmail API to test the connection', llm=llm, controller=controller)++ try:+ history = await agent.run()+ print('β Gmail authentication test completed')+ except Exception as e:+ print(f'β Gmail authentication failed: {e}')+ print('\nπ Setup instructions:')+ print('1. Go to https://console.cloud.google.com/')+ print('2. Create a project and enable Gmail API')+ print('3. Create OAuth 2.0 credentials')+ print('4. Download credentials JSON as ~/.config/browseruse/gmail_credentials.json')+ return++ print('\n' + '=' * 50)++ # Example 2: Find recent 2FA codes+ print('π Testing 2FA code finding...')+ agent2 = Agent(+ task='Find any 2FA verification codes in my recent Gmail emails from the last 30 minutes', llm=llm, controller=controller+ )++ history2 = await agent2.run()+ print('β 2FA code search completed')++ print('\n' + '=' * 50)++ # Example 3: Simulate a login flow with 2FA+ print('π Example: Simulated login with 2FA')+ print('This shows how an agent would handle 2FA during login:')++ agent3 = Agent(+ task="""+ Simulate a login flow with 2FA handling:+ 1. First check if there are any recent 2FA codes in Gmail+ 2. If no codes found, explain that the agent would:+ - Fill in username/password on a login page+ - Click submit+ - When prompted for 2FA, use poll_for_2fa_code to wait for the email+ - Extract the code and enter it on the website+ """,+ llm=llm,+ controller=controller,+ )++ history3 = await agent3.run()+ print('β Simulated 2FA flow completed')++ print('\n' + '=' * 50)+ print('π Gmail integration examples completed!')+ print('\nπ‘ Usage tips:')+ print('- Use find_2fa_codes for checking recent emails')+ print('- Use poll_for_2fa_code when expecting a new 2FA email')+ print('- Specify sender_email to filter by specific services')+ print('- Custom patterns can be added for non-standard codes')+++if __name__ == '__main__':+ asyncio.run(main())\ No newline at end of filediff --git a/pyproject.toml b/pyproject.tomlindex ba63f8640..bac07c3e0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -36,6 +36,9 @@ dependencies = ["anthropic>=0.54.0","groq>=0.28.0","ollama>=0.5.1",+ "google-api-python-client>=2.174.0",+ "google-auth>=2.40.3",+ "google-auth-oauthlib>=1.2.2",]# google-api-core: only used for Google LLM APIs# pyperclip: only used for examples that use copy/paste