NAME : SAGAR PRALHAD DHAKE
ROLL NO: 24
TITLE : SPAM EMAIL DETECTOR
BATCH : B2
CLASS : FYMCA
import imaplib, email
from email.header import decode_header
import tkinter as tk
from tkinter import simpledialog, messagebox
keywords = ["free money", "winner", "congratulations", "urgent", "credit card", "click
here", "lottery", "act now", "limited offer", "100% free", "guaranteed", "investment", "no
cost", "extra cash", "apply now", "cash bonus", "fast cash", "cheap meds", "meet
singles", "risk-free", "earn per week", "work from home", "get paid", "miracle", "exclusive
deal", "urgent response", "pre-approved", "access now", "trial offer", "join my class",
"let's have fun", "interview"]
def is_spam(text): return any(k in text.lower() for k in keywords)
def fetch_emails(user, pwd, limit):
try:
imap = imaplib.IMAP4_SSL("imap.gmail.com"); imap.login(user, pwd);
imap.select("inbox")
_, msgs = imap.search(None, "ALL"); ids = msgs[0].split()[-limit:]
for i in ids:
_, data = imap.fetch(i, "(RFC822)")
msg = email.message_from_bytes(data[0][1])
subj = "".join([p.decode(enc or "utf-8") if isinstance(p, bytes) else p for p, enc in
decode_header(msg["subject"] or "")])
body = ""
for part in msg.walk():
if part.get_content_type() == "text/plain" and not part.get('Content-
Disposition'):
body = part.get_payload(decode=True).decode(errors="ignore"); break
result = "SPAM" if is_spam(subj + " " + body) else "HAM"
print(f"[{result}] {msg.get('date')} | {subj}\n{body[:60].strip()}...\n" + "-"*60)
imap.logout()
except Exception as e: messagebox.showerror("Error", str(e))
def gui():
r = tk.Tk(); r.withdraw()
u = simpledialog.askstring("Email", "Gmail:"); p = simpledialog.askstring("Password",
"App Password:", show="*")
l = simpledialog.askinteger("Limit", "How many emails?", minvalue=1)
if u and p and l: fetch_emails(u, p, l)
gui()
OUTPUT:-
Enter email:-
Enter password:-
Enter limit of email:-