Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions misc/ai-spam-email-monitor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Gmail Inbox Monitor

A simple Python application that monitors your Gmail inbox for unread emails and displays them in the terminal. The app refreshes every 5 seconds to show new unread emails and can analyze emails for spam using Google's Gemini AI.

## Prerequisites

- Python 3.6+
- Gmail account
- Google Cloud project with Gmail API enabled
- (Optional) Google Gemini API key for spam detection

## Setup

1. Clone this repository
2. Install dependencies:
```
pip install -r requirements.txt
```
3. Set up Google API credentials:
- Go to [Google Cloud Console](https://console.cloud.google.com/)
- Create a new project (or select an existing one)
- Enable the Gmail API
- Create OAuth credentials (Desktop application)
- Download the credentials JSON file and save it as `credentials.json` in the project directory

4. (Optional) Set up Google Gemini for spam detection:
- Go to [Google AI Studio](https://makersuite.google.com/app/apikey)
- Create a new API key
- Run the setup command:
```
python gmail_monitor.py --setup-gemini
```
- Follow the prompts to enter your API key

## Usage

1. Run the authentication module to set up your credentials:
```
python auth.py
```
- This will open a browser window where you need to log in with your Google account and grant permissions
- After successful authentication, a `token.json` file will be created

2. Run the main script to monitor your inbox:
```
python gmail_monitor.py
```

3. Press Ctrl+C to stop the application

## Spam Detection and Response

When spam detection is enabled:

- Each email is analyzed by Google's Gemini AI
- If an email is identified as legitimate, a standard auto-reply is sent with the spam analysis result
- If an email is identified as spam, the system generates a clever time-wasting reply
- The reply is designed to bait spammers by showing interest without revealing any valuable information
- It asks questions that require lengthy responses and maintains a naive but interested tone
- This helps waste spammers' time and resources while keeping you safe

### Conversation Tracking

The system tracks spam email threads persistently:

- Once an email is identified as spam, the entire conversation thread is marked for special handling
- All future replies in that thread will automatically receive AI-generated responses
- The system uses different prompts for initial spam emails versus follow-up messages
- Thread information is stored between sessions in `spam_threads.json`

To set up or reconfigure spam detection:
```
python gmail_monitor.py --setup-gemini
```

## Sign Out / Switch Accounts

You can sign out (remove saved credentials) in two ways:

1. Using the main script:
```
python gmail_monitor.py --signout
```

2. Using the auth module directly:
```
python auth.py --signout
```

After signing out, you'll need to re-authenticate the next time you run the application, allowing you to use a different Google account.

## Customization

You can modify the following aspects of the application:
- Change the refresh interval (default: 5 seconds)
- Adjust email display format
- Add filters for specific senders or subjects
- Modify the spam detection prompt in `gemini_spam_detector.py`
- Customize the spam-baiting reply generation by editing the prompt in the `generate_email_reply` function
92 changes: 92 additions & 0 deletions misc/ai-spam-email-monitor/README_gemini.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Gmail Spam Detection with Google Gemini

This extension adds AI-powered spam detection to the Gmail Inbox Monitor using Google's Gemini API.

## Getting Started with Gemini Spam Detection

### Prerequisites

- All the requirements from the original Gmail Inbox Monitor
- Google Gemini API key

### Setting Up Google Gemini

1. **Install the required dependencies**:
```
pip install -r requirements.txt
```

2. **Get a Google Gemini API Key**:
- Go to [Google AI Studio](https://makersuite.google.com/app/apikey)
- Create a Google account if you don't have one
- Create a new API key (You may need to enter payment information, but Google offers free credits)
- Save your API key in a secure place

3. **Configure Gemini for Spam Detection**:
```
python gemini_spam_detector.py
```
- This will prompt you to enter your API key
- It will test the connection and save your configuration

### Using Spam Detection

Once set up, you can use the spam detection functionality in two ways:

1. **Run the example spam detection monitor**:
```
python spam_detector_example.py
```

This script will:
- Monitor your inbox for new emails
- Analyze each email using Google Gemini
- Identify potential spam emails
- Handle legitimate emails normally

2. **Configure Gemini directly**:
```
python spam_detector_example.py --setup-gemini
```

This will guide you through the Gemini setup process if you haven't done it yet.

## How It Works

The spam detection system uses Google's Gemini AI to analyze incoming emails by:

1. Extracting the sender, subject, and body of each email
2. Sending this information to the Gemini API for analysis
3. Processing the AI's response to determine if the email is spam
4. Handling the email differently based on the spam determination

## Customization

You can modify the spam detection behavior by:

- Changing the Gemini model in `gemini_spam_detector.py` (default is "gemini-2.0-flash-lite")
- Editing the prompt template in the `analyze_email` method
- Adding custom handling for detected spam emails in `handle_email_with_spam_detection`

## Integration

The spam detection functionality is designed to work alongside the existing Gmail Inbox Monitor, not replace it. You can:

- Use just the original inbox monitor without spam detection
- Use the new spam detection example that builds on the original functionality
- Create your own custom integration using the `GeminiSpamDetector` class

## Troubleshooting

If you encounter issues:

- Ensure your API key is correct and active
- Check that you have internet connectivity
- Verify you have sufficient API quota/credits with Google
- Look for any error messages in the console output

## Notes

- The Gemini API may have usage limits based on your account
- Processing very large emails may consume more API resources
- Your API key is stored locally in `gemini_config.json`
74 changes: 74 additions & 0 deletions misc/ai-spam-email-monitor/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
import os
import json
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

# Define the scopes needed for Gmail API access
# gmail.modify - Allows reading and modifying emails (marking as read, labeling)
# gmail.send - Allows sending emails
SCOPES = [
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.send'
]

def authenticate(credentials_path='credentials.json', token_path='token.json'):
"""
Authenticate with Gmail API using OAuth2
This function is used if you need to set up authentication from scratch
"""
creds = None

# Check if token file exists
if os.path.exists(token_path):
with open(token_path, 'r') as token:
creds = Credentials.from_authorized_user_info(json.load(token), SCOPES)

# If credentials don't exist or are invalid, go through auth flow
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_path, SCOPES)
creds = flow.run_local_server(port=0)

# Save the credentials for the next run
with open(token_path, 'w') as token:
token.write(creds.to_json())

return creds

def get_gmail_service(credentials_path='credentials.json', token_path='token.json'):
"""
Creates and returns an authenticated Gmail API service
"""
creds = authenticate(credentials_path, token_path)
service = build('gmail', 'v1', credentials=creds)
return service

def sign_out(token_path='token.json'):
"""
Signs out the user by removing the token file
"""
if os.path.exists(token_path):
try:
os.remove(token_path)
return True, f"Successfully signed out. Token file '{token_path}' has been removed."
except Exception as e:
return False, f"Error signing out: {str(e)}"
else:
return False, f"Not signed in. Token file '{token_path}' does not exist."

if __name__ == "__main__":
import sys

if len(sys.argv) > 1 and sys.argv[1] == "--signout":
success, message = sign_out()
print(message)
else:
# Running this file directly will test authentication
print("Testing Gmail API authentication...")
service = get_gmail_service()
print("Authentication successful!")
Loading