Spam Email Classifier with Python
Step-by-step guide with examples and code
Spam Email Classifier with Python
Step-by-step guide with examples and code

Photo by Stephen Phillips — Hostreviews.co.uk on Unsplash
Spam detection is one of the most common applications of Natural Language Processing (NLP). In this project, we’ll build a machine learning model to classify emails as spam or not spam using Python. We’ll use a dataset of emails and apply text preprocessing, feature extraction, and machine learning techniques.
How Spam Filtering Works (Simple Example)
Imagine you get two emails:
- Email 1: “Win a free iPhone now! Click the link.”
- Email 2: “Meeting rescheduled to 3 PM tomorrow.”
As a human, you instantly know the first one looks suspicious (spam) and the second one is normal (not spam). But how can a computer decide this automatically?
The trick is to teach the computer patterns in words. For example:
- Words like “win, free, prize, claim, urgent” often appear in spam.
- Words like “meeting, project, schedule, tomorrow” appear in normal emails.
A spam filter works by learning these patterns from many emails and then predicting whether a new email is spam or not.
Now let’s build one step by step in Python.
Step 1: Load & Explore Data
We first load the dataset (CSV format with columns like Email_Text and Label).
This helps us understand what data we’re working with.
What it means: We need a dataset of emails with labels (Spam or Not Spam). Think of it like a teacher showing examples:
- “Congratulations, claim your prize” → Spam
- “Project deadline tomorrow” → Not Spam
import pandas as pd
# Load dataset
df = pd.read_csv("emails.csv")
# View sample data
print(df.head())
print(df['Label'].value_counts())
Step 2: Clean the Text
Emails contain stopwords (like the, is, at) and punctuation that don’t add much meaning. Removing them makes our model focus on important words.
Example before cleaning:
"Win a free iPhone now!!! $$$" After cleaning:
"win free iphone" This makes it easier for the model to learn.
import re
def clean_text(text):
# Remove punctuation & numbers
text = re.sub(r'[^a-zA-Z]', ' ', text)
# Convert to lowercase
text = text.lower()
return text
df["Cleaned_Text"] = df["Email_Text"].apply(clean_text)
print(df.head())
Step 3: Convert Text to Numerical Features (TF-IDF)
Machine learning models work with numbers, not raw text. We’ll use TF-IDF (Term Frequency — Inverse Document Frequency), which gives importance to rare but meaningful words. Example: *“free” appears many times in spam emails → high score*. “meeting” appears mostly in normal emails → lower score for spam. **So:
"Win free iPhone"→[0.8, 0.7, 0.9]"Meeting at 3 PM"→[0.2, 0.1, 0.3]
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(stop_words='english', max_features=5000)
X = vectorizer.fit_transform(df["Cleaned_Text"])
y = df["Label"].map({"Not Spam": 0, "Spam": 1})
Step 4: Train-Test Split
We split the dataset into:
- Training set (used to teach the model).
- Test set (used to check if the model learned well).
Example: If we have 100 emails:
- 80 go to training (teacher shows examples).
- 20 go to testing (exam for the student).
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
Step 5: Train the Model
We’ll use Logistic Regression, a simple but effective classification algorithm.
Example: The model learns patterns:
- If words like “free, win, prize” appear → more likely spam.
- If words like “meeting, project, schedule” appear → more likely not spam.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
Step 6: Make Predictions & Evaluate
Now, we test the model on unseen emails and evaluate performance.
Example:
- Input:
"Claim your free prize now"→ Model predicts: Spam - Input:
"Lunch meeting at 1 PM"→ Model predicts: Not Spam
from sklearn.metrics import accuracy_score, precision_score, recall_score
# Predict on test set
y_pred = model.predict(X_test)
# Evaluate performance
print("Accuracy :", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall :", recall_score(y_test, y_pred))
Full Python Code
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score
# 1. Load dataset
df = pd.read_csv("emails.csv") # CSV file with columns: Email_Text, Label
X = df["Email_Text"]
y = df["Label"].map({"Not Spam": 0, "Spam": 1})
# 2. Train-Test Split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 3. Vectorize text using TF-IDF
vectorizer = TfidfVectorizer(stop_words='english')
X_train_vec = vectorizer.fit_transform(X_train)
X_test_vec = vectorizer.transform(X_test)
# 4. Train Logistic Regression model
model = LogisticRegression()
model.fit(X_train_vec, y_train)
# 5. Predict on test data
y_pred = model.predict(X_test_vec)
# 6. Evaluate results
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall:", recall_score(y_test, y_pred))
Thanks for Reading!!
Buy me a coffee: https://paypal.me/vishnu918987?country.x=IN&locale.x=en_GB
Before you go
- Please take a moment to like the post and follow the writer!
- Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute here
메타데이터
- post_id
- c02a69a55d03
- slug
- spam-email-classifier-with-python-c02a69a55d03
- url
- https://python.plainenglish.io/spam-email-classifier-with-python-c02a69a55d03
- canonical_url
- https://python.plainenglish.io/spam-email-classifier-with-python-c02a69a55d03
- author_url
- https://medium.com/@vishnubhaarath30
- status
- ok
- fetched_at
- 2026-07-10 03:40:03