from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googleapiclient.discovery import build import base64 from email.mime.text import MIMEText import pickle import os # Update scopes to include all needed permissions SCOPES = [ 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.readonly' ] def test_gmail(): """Test Gmail API setup""" try: # Delete existing token to force new authentication if os.path.exists('token.pickle'): os.remove('token.pickle') # Get credentials creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # Build service service = build('gmail', 'v1', credentials=creds) # Test connection profile = service.users().getProfile(userId='me').execute() print(f"Successfully connected to Gmail API for: {profile['emailAddress']}") return True except Exception as e: print(f"Error testing Gmail API: {str(e)}") return False if __name__ == "__main__": test_gmail()