import os
import base64
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# Load your Google Cloud service account key JSON file
credentials = service_account.Credentials.from_service_account_file('your-service-account-key.json',
scopes=['https://www.googleapis.com/auth/gmail.modify'])
# Authenticate and build the Gmail API client
gmail_service = build('gmail', 'v1', credentials=credentials)
# Function to list Gmail labels
def list_labels():
results = gmail_service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'])
# Function to check spam emails
def check_spam_emails():
try:
response = gmail_service.users().messages().list(userId='me', labelIds=['SPAM']).execute()
messages = response.get('messages', [])
if not messages:
print('No spam emails found.')
else:
for message in messages:
message_info = gmail_service.users().messages().get(userId='me', id=message['id']).execute()
print('Subject:', message_info['subject'])
print('Snippet:', message_info['snippet'])
except HttpError as error:
print(f'An error occurred: {error}')
# Function to mark an email as not spam
def mark_as_not_spam(message_id):
try:
gmail_service.users().messages().modify(userId='me', id=message_id, body={'removeLabelIds': ['SPAM']}).execute()
print(f'Marked email {message_id} as not spam.')
except HttpError as error:
print(f'An error occurred: {error}')
# Function to mark an email as important
def mark_as_important(message_id):
try:
gmail_service.users().messages().modify(userId='me', id=message_id, body={'addLabelIds': ['IMPORTANT']}).execute()
print(f'Marked email {message_id} as important.')
except HttpError as error:
print(f'An error occurred: {error}')
# Function to click a link (by opening an email)
def click_link_in_email(message_id):
try:
message = gmail_service.users().messages().get(userId='me', id=message_id).execute()
for part in message['payload']['parts']:
if part['mimeType'] == 'text/html':
data = part['body']['data']
html_content = base64.urlsafe_b64decode(data).decode('utf-8')
# Here you can parse the HTML content to find and click links.
# This part will depend on your specific use case.
print('Opened email and processed links.')
break
except HttpError as error:
print(f'An error occurred: {error}')
# Example usage
if __name__ == '__main__':
list_labels()
check_spam_emails()
# Provide a message_id to mark as not spam, mark as important, and click links.
message_id = 'YOUR_MESSAGE_ID'
mark_as_not_spam(message_id)
mark_as_important(message_id)
click_link_in_email(message_id)