Skip to content

Commit 3c244c7

Browse files
authored
add spam detector (#317)
1 parent 9b972ed commit 3c244c7

6 files changed

Lines changed: 956 additions & 0 deletions

File tree

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# Gmail Inbox Monitor
2+
3+
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.
4+
5+
## Prerequisites
6+
7+
- Python 3.6+
8+
- Gmail account
9+
- Google Cloud project with Gmail API enabled
10+
- (Optional) Google Gemini API key for spam detection
11+
12+
## Setup
13+
14+
1. Clone this repository
15+
2. Install dependencies:
16+
```
17+
pip install -r requirements.txt
18+
```
19+
3. Set up Google API credentials:
20+
- Go to [Google Cloud Console](https://console.cloud.google.com/)
21+
- Create a new project (or select an existing one)
22+
- Enable the Gmail API
23+
- Create OAuth credentials (Desktop application)
24+
- Download the credentials JSON file and save it as `credentials.json` in the project directory
25+
26+
4. (Optional) Set up Google Gemini for spam detection:
27+
- Go to [Google AI Studio](https://makersuite.google.com/app/apikey)
28+
- Create a new API key
29+
- Run the setup command:
30+
```
31+
python gmail_monitor.py --setup-gemini
32+
```
33+
- Follow the prompts to enter your API key
34+
35+
## Usage
36+
37+
1. Run the authentication module to set up your credentials:
38+
```
39+
python auth.py
40+
```
41+
- This will open a browser window where you need to log in with your Google account and grant permissions
42+
- After successful authentication, a `token.json` file will be created
43+
44+
2. Run the main script to monitor your inbox:
45+
```
46+
python gmail_monitor.py
47+
```
48+
49+
3. Press Ctrl+C to stop the application
50+
51+
## Spam Detection and Response
52+
53+
When spam detection is enabled:
54+
55+
- Each email is analyzed by Google's Gemini AI
56+
- If an email is identified as legitimate, a standard auto-reply is sent with the spam analysis result
57+
- If an email is identified as spam, the system generates a clever time-wasting reply
58+
- The reply is designed to bait spammers by showing interest without revealing any valuable information
59+
- It asks questions that require lengthy responses and maintains a naive but interested tone
60+
- This helps waste spammers' time and resources while keeping you safe
61+
62+
### Conversation Tracking
63+
64+
The system tracks spam email threads persistently:
65+
66+
- Once an email is identified as spam, the entire conversation thread is marked for special handling
67+
- All future replies in that thread will automatically receive AI-generated responses
68+
- The system uses different prompts for initial spam emails versus follow-up messages
69+
- Thread information is stored between sessions in `spam_threads.json`
70+
71+
To set up or reconfigure spam detection:
72+
```
73+
python gmail_monitor.py --setup-gemini
74+
```
75+
76+
## Sign Out / Switch Accounts
77+
78+
You can sign out (remove saved credentials) in two ways:
79+
80+
1. Using the main script:
81+
```
82+
python gmail_monitor.py --signout
83+
```
84+
85+
2. Using the auth module directly:
86+
```
87+
python auth.py --signout
88+
```
89+
90+
After signing out, you'll need to re-authenticate the next time you run the application, allowing you to use a different Google account.
91+
92+
## Customization
93+
94+
You can modify the following aspects of the application:
95+
- Change the refresh interval (default: 5 seconds)
96+
- Adjust email display format
97+
- Add filters for specific senders or subjects
98+
- Modify the spam detection prompt in `gemini_spam_detector.py`
99+
- Customize the spam-baiting reply generation by editing the prompt in the `generate_email_reply` function
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Gmail Spam Detection with Google Gemini
2+
3+
This extension adds AI-powered spam detection to the Gmail Inbox Monitor using Google's Gemini API.
4+
5+
## Getting Started with Gemini Spam Detection
6+
7+
### Prerequisites
8+
9+
- All the requirements from the original Gmail Inbox Monitor
10+
- Google Gemini API key
11+
12+
### Setting Up Google Gemini
13+
14+
1. **Install the required dependencies**:
15+
```
16+
pip install -r requirements.txt
17+
```
18+
19+
2. **Get a Google Gemini API Key**:
20+
- Go to [Google AI Studio](https://makersuite.google.com/app/apikey)
21+
- Create a Google account if you don't have one
22+
- Create a new API key (You may need to enter payment information, but Google offers free credits)
23+
- Save your API key in a secure place
24+
25+
3. **Configure Gemini for Spam Detection**:
26+
```
27+
python gemini_spam_detector.py
28+
```
29+
- This will prompt you to enter your API key
30+
- It will test the connection and save your configuration
31+
32+
### Using Spam Detection
33+
34+
Once set up, you can use the spam detection functionality in two ways:
35+
36+
1. **Run the example spam detection monitor**:
37+
```
38+
python spam_detector_example.py
39+
```
40+
41+
This script will:
42+
- Monitor your inbox for new emails
43+
- Analyze each email using Google Gemini
44+
- Identify potential spam emails
45+
- Handle legitimate emails normally
46+
47+
2. **Configure Gemini directly**:
48+
```
49+
python spam_detector_example.py --setup-gemini
50+
```
51+
52+
This will guide you through the Gemini setup process if you haven't done it yet.
53+
54+
## How It Works
55+
56+
The spam detection system uses Google's Gemini AI to analyze incoming emails by:
57+
58+
1. Extracting the sender, subject, and body of each email
59+
2. Sending this information to the Gemini API for analysis
60+
3. Processing the AI's response to determine if the email is spam
61+
4. Handling the email differently based on the spam determination
62+
63+
## Customization
64+
65+
You can modify the spam detection behavior by:
66+
67+
- Changing the Gemini model in `gemini_spam_detector.py` (default is "gemini-2.0-flash-lite")
68+
- Editing the prompt template in the `analyze_email` method
69+
- Adding custom handling for detected spam emails in `handle_email_with_spam_detection`
70+
71+
## Integration
72+
73+
The spam detection functionality is designed to work alongside the existing Gmail Inbox Monitor, not replace it. You can:
74+
75+
- Use just the original inbox monitor without spam detection
76+
- Use the new spam detection example that builds on the original functionality
77+
- Create your own custom integration using the `GeminiSpamDetector` class
78+
79+
## Troubleshooting
80+
81+
If you encounter issues:
82+
83+
- Ensure your API key is correct and active
84+
- Check that you have internet connectivity
85+
- Verify you have sufficient API quota/credits with Google
86+
- Look for any error messages in the console output
87+
88+
## Notes
89+
90+
- The Gemini API may have usage limits based on your account
91+
- Processing very large emails may consume more API resources
92+
- Your API key is stored locally in `gemini_config.json`

misc/ai-spam-email-monitor/auth.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import json
4+
from google.oauth2.credentials import Credentials
5+
from google_auth_oauthlib.flow import InstalledAppFlow
6+
from google.auth.transport.requests import Request
7+
from googleapiclient.discovery import build
8+
9+
# Define the scopes needed for Gmail API access
10+
# gmail.modify - Allows reading and modifying emails (marking as read, labeling)
11+
# gmail.send - Allows sending emails
12+
SCOPES = [
13+
'https://www.googleapis.com/auth/gmail.modify',
14+
'https://www.googleapis.com/auth/gmail.send'
15+
]
16+
17+
def authenticate(credentials_path='credentials.json', token_path='token.json'):
18+
"""
19+
Authenticate with Gmail API using OAuth2
20+
This function is used if you need to set up authentication from scratch
21+
"""
22+
creds = None
23+
24+
# Check if token file exists
25+
if os.path.exists(token_path):
26+
with open(token_path, 'r') as token:
27+
creds = Credentials.from_authorized_user_info(json.load(token), SCOPES)
28+
29+
# If credentials don't exist or are invalid, go through auth flow
30+
if not creds or not creds.valid:
31+
if creds and creds.expired and creds.refresh_token:
32+
creds.refresh(Request())
33+
else:
34+
flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES)
35+
creds = flow.run_local_server(port=0)
36+
37+
# Save the credentials for the next run
38+
with open(token_path, 'w') as token:
39+
token.write(creds.to_json())
40+
41+
return creds
42+
43+
def get_gmail_service(credentials_path='credentials.json', token_path='token.json'):
44+
"""
45+
Creates and returns an authenticated Gmail API service
46+
"""
47+
creds = authenticate(credentials_path, token_path)
48+
service = build('gmail', 'v1', credentials=creds)
49+
return service
50+
51+
def sign_out(token_path='token.json'):
52+
"""
53+
Signs out the user by removing the token file
54+
"""
55+
if os.path.exists(token_path):
56+
try:
57+
os.remove(token_path)
58+
return True, f"Successfully signed out. Token file '{token_path}' has been removed."
59+
except Exception as e:
60+
return False, f"Error signing out: {str(e)}"
61+
else:
62+
return False, f"Not signed in. Token file '{token_path}' does not exist."
63+
64+
if __name__ == "__main__":
65+
import sys
66+
67+
if len(sys.argv) > 1 and sys.argv[1] == "--signout":
68+
success, message = sign_out()
69+
print(message)
70+
else:
71+
# Running this file directly will test authentication
72+
print("Testing Gmail API authentication...")
73+
service = get_gmail_service()
74+
print("Authentication successful!")

0 commit comments

Comments
 (0)