"python script to check a pop email account and save all the subject lines to a txt file"
12.8s
Add to Favorites
Cozy Upvote
Share
Export
Click any AI circle above with a to read their individual answer!
Use Python’s poplib with SSL, decode each email’s subject correctly, and write the list of subjects to a text file – all while handling credentials securely.
Quick Facts
- Connect to the POP3 server using POP3_SSL for encrypted communication.
- Decode subject headers with email.header.decode_header to support non‑ASCII text.
- Prompt for credentials (or use environment variables) instead of hard‑coding passwords.
- Write each subject on a new line (or with numbering) to a UTF‑8 text file.
- The script works with Gmail, Outlook, Yahoo, etc., by adjusting the server name.
AI Consensus
Models Agreed
- All models agree that poplib is used to connect to a POP3 server and retrieve messages.
- All models agree that the email library (with
decode_header) must be used to decode subject lines correctly. - All models agree that the extracted subjects should be written to a text file.
Points of Debate
- Model 2 suggests using plain
poplib.POP3(non‑SSL) while Models 1 and 3 recommendPOP3_SSLfor secure connections. - Model 2 hard‑codes credentials; Models 1 and 3 prompt for them or recommend environment variables for security.
Python script to read a POP3 mailbox and save all subject lines
Below is a ready‑to‑run script that:
- Connects securely to a POP3 server (SSL on port 995).
- Logs in using credentials entered at runtime (so they aren’t stored in the file).
- Iterates over every message, parses it with the standard
emaillibrary, and decodes the subject handling any RFC‑2047 encoding. - Writes each subject to
email_subjects.txt(UTF‑8).
#!/usr/bin/env python3
"""
POP3 Subject Extractor
----------------------
Connects to a POP3 server, retrieves every message, extracts the
Subject header (properly decoded), and saves all subjects to a text file.
"""
import poplib
import getpass
from email import policy
from email.parser import BytesParser
from email.header import decode_header
# -------------------- Configuration --------------------
POP_SERVER = "pop.gmail.com" # Change to your provider's POP server
POP_PORT = 995 # Standard POP3‑SSL port
OUTPUT_FILE = "email_subjects.txt"
# -----------------------------------------------------
def decode_subject(raw_subject):
"""Return a clean, Unicode string for the Subject header."""
if raw_subject is None:
return "[No Subject]"
# decode_header may return several parts (e.g., mixed encodings)
parts = decode_header(raw_subject)
decoded = ""
for part, enc in parts:
if isinstance(part, bytes):
decoded += part.decode(enc or "utf-8", errors="replace")
else:
decoded += part
return decoded.strip()
def fetch_subjects(server, user, password):
"""Log in to POP3‑SSL, fetch and decode every Subject line."""
subjects = []
# Connect securely
pop_conn = poplib.POP3_SSL(server, POP_PORT, timeout=15)
pop_conn.user(user)
pop_conn.pass_(password)
# Number of messages
resp, listings, octets = pop_conn.list()
total = len(listings)
print(f"Found {total} messages in the mailbox.\n")
for i in range(1, total + 1):
# Retrieve raw message bytes
resp, lines, octets = pop_conn.retr(i)
raw_message = b"\n".join(lines)
# Parse the message
msg = BytesParser(policy=policy.default).parsebytes(raw_message)
# Decode subject
subject = decode_subject(msg["Subject"])
subjects.append(subject)
print(f"{i}/{total}: {subject}")
pop_conn.quit()
return subjects
def save_to_file(subjects, filename):
"""Write the list of subjects to a UTF‑8 text file."""
with open(filename, "w", encoding="utf-8") as f:
for idx, subj in enumerate(subjects, start=1):
f.write(f"{idx}. {subj}\n")
print(f"\nAll subjects saved to {filename}")
def main():
print("=== POP3 Email Subject Extractor ===")
server = input(f"POP server [{POP_SERVER}]: ").strip() or POP_SERVER
email_addr = input("Email address: ").strip()
pwd = getpass.getpass("Password (or app‑specific password): ")
subjects = fetch_subjects(server, email_addr, pwd)
if subjects:
save_to_file(subjects, OUTPUT_FILE)
else:
print("No subjects retrieved.")
if __name__ == "__main__":
main()
How it works
| Step | What the script does | Why it matters |
|---|---|---|
| Connect | Uses poplib.POP3_SSL with the server/port you provide. |
Guarantees encryption (TLS) and works with most providers (Gmail, Outlook, Yahoo, etc.)6 |
| Login | Reads username and password via input/getpass. |
Avoids hard‑coding credentials; passwords are not echoed to the console. |
| List messages | pop_conn.list() returns the count of messages. |
Lets us loop over every email. |
| Retrieve each message | pop_conn.retr(i) fetches the raw bytes of the i‑th mail. |
POP3 delivers the full email content. |
| Parse | BytesParser (with policy.default) builds an EmailMessage object. |
The modern email API handles MIME parts and headers robustly10. |
| Decode subject | decode_header iterates over all encoded parts, converting them to Unicode. |
Handles subjects encoded in UTF‑8, ISO‑8859‑1, etc., and avoids garbled text. |
| Write to file | Writes each subject on its own line (prefixed with a line number). | Produces a clean, searchable email_subjects.txt. |
Customisation tips
- Change output filename: modify
OUTPUT_FILEor pass a different name tosave_to_file(). - Filter subjects: add an
ifstatement in the loop to keep only subjects that contain a keyword. - Skip SSL: replace
POP3_SSLwithpoplib.POP3if you need a non‑TLS connection (not recommended)2. - Credential handling: store
EMAILandPASSWORDin environment variables (os.getenv) for automated runs.
Security notes
- Use app‑specific passwords for Gmail/Outlook when two‑factor authentication is enabled (see Gmail’s App Passwords page).
- Never commit passwords to version control.
- SSL/TLS is essential; POP3 without encryption exposes credentials in cleartext.
Troubleshooting
- Authentication errors – Verify POP3 is enabled in your email account settings and that you’re using the correct server/port.
- Empty subjects – Some messages legitimately have no Subject header; the script records “[No Subject]”.
- Unicode errors – The
errors="replace"argument ensures any unknown bytes are safely replaced.
With this script you can quickly audit the subjects in any POP3 mailbox and keep a tidy log for further processing or archiving. Happy scripting!
AI can make mistakes. Verify important information.