Using Bayesian Spam Filtering to Classify Emails in Python
Contents
[
Hide
]
Using Bayesian Spam Filtering
Aspose.Email provides email filtering functionality using a Bayesian spam analyzer. It provides the SpamAnalyzer class for this purpose. This article shows how to train the filter to distinguish between spam and regular email based on a word database.
- Specify the folder paths for the ham emails (ham_folder), spam emails (spam_folder), test emails (test_folder), and the database file (database_file) for the spam filter.
- Define the helper function
print_resultto print whether a message is classified as spam or not based on the calculated spam probability. - Create a Spam Analyzer, train it with the emails from ham_folder (not spam) and spam_folder (spam) using the ’train_filter(message, is_spam)’ method, then save the trained database with ‘save_database(file_path)’.
- Create a Spam Analyzer, restore the trained database with ’load_database(file_path)’, load the .eml files from ’test_folder’, analyze each with ’test(message)’ to get the spam probability, and print the email subject and classification using ‘print_result’.
import os
from aspose.email import MailMessage
from aspose.email.antispam import SpamAnalyzer
ham_folder = "hamFolder"
spam_folder = "spamFolder"
test_folder = "testFolder"
database_file = "SpamFilterDatabase.txt"
def print_result(probability):
if probability >= 0.5:
print("The message is classified as spam.")
else:
print("The message is classified as not spam.")
print("Spam Probability: " + str(probability))
print()
def train_from_directory(analyzer, folder, is_spam):
for file in os.listdir(folder):
if file.endswith(".eml"):
analyzer.train_filter(MailMessage.load(os.path.join(folder, file)), is_spam)
def teach_and_create_database(ham_folder, spam_folder, database_file):
analyzer = SpamAnalyzer()
train_from_directory(analyzer, ham_folder, False)
train_from_directory(analyzer, spam_folder, True)
analyzer.save_database(database_file)
teach_and_create_database(ham_folder, spam_folder, database_file)
test_files = [f for f in os.listdir(test_folder) if f.endswith(".eml")]
analyzer = SpamAnalyzer()
analyzer.load_database(database_file)
for file in test_files:
file_path = os.path.join(test_folder, file)
msg = MailMessage.load(file_path)
print(msg.subject)
probability = analyzer.test(msg)
print_result(probability)