EMAIL SPAM FILTERING USING MACHINE LEARNING IN PYTHON
Ex no : 1
Date : 20/6/25
Aim:
To develop a spam filter using a single machine learning algorithm (e.g., Naive
Bayes) trained on a labeled dataset of SMS/email messages.
Algorithm Inference:
Model Used: Multinomial Naive Bayes (or SVM, or Random Forest)
Input: Raw text emails (spam or ham)
Preprocessing: Tokenization and vectorization using CountVectorizer
Training:
o Labeled data ([Link]) is split into training/testing sets
o Text data is converted to numerical vectors
o Model is trained to identify spam keywords/patterns
Inference:
o Given a new email message, the model transforms it to a vector
and predicts its class (spam or ham)
Output:
o If spam: print "Deleted: <email>"
o If not spam: print "Safe: <email>"
Performance Evaluation:
Metrics: Accuracy, Precision, Recall, F1-Score
Observed results depend on model used but typically:
o High precision for spam class
o Fast, lightweight model
Code :
# gmail_reader.py
import os
import base64
from [Link] import Request
from [Link] import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from [Link] import build
from classify_email import classify_email
SCOPES = ['[Link]
def authenticate_gmail():
creds = None
if [Link]('gmail_api/[Link]'):
creds = Credentials.from_authorized_user_file('gmail_api/[Link]',
SCOPES)
if not creds or not [Link]:
if creds and [Link] and creds.refresh_token:
[Link](Request())
else:
flow =
InstalledAppFlow.from_client_secrets_file('gmail_api/[Link]', SCOPES)
creds = flow.run_local_server(port=0)
with open('gmail_api/[Link]', 'w') as token:
[Link](creds.to_json())
return build('gmail', 'v1', credentials=creds)
def get_latest_emails(service, max_results=5):
results = [Link]().messages().list(userId='me',
maxResults=max_results).execute()
messages = [Link]('messages', [])
for msg in messages:
msg_data = [Link]().messages().get(userId='me',
id=msg['id']).execute()
payload = msg_data.get('payload', {})
parts = [Link]('parts', [])
data = ""
if parts:
data = parts[0]['body'].get('data', "")
else:
data = [Link]('body', {}).get('data', "")
if data:
text = base64.urlsafe_b64decode(data).decode('utf-8', errors='ignore')
print("\n--- New Email ---")
classify_email(text)
# classify_email.py
import pickle
# Load trained model and vectorizer
with open("models/spam_classifier.pkl", "rb") as f:
model = [Link](f)
with open("models/[Link]", "rb") as f:
vectorizer = [Link](f)
def classify_email(message):
vector = [Link]([message])
prediction = [Link](vector)[0]
if prediction == 1:
print(f" Deleted: {message}")
else:
print(f"✅ Safe: {message}")
# Test it directly
if __name__ == "__main__":
# Sample message to classify
test_message = "You’ve won a lottery! Click here."
classify_email(test_message)
OUTPUT :