Created
August 25, 2025 10:32
-
-
Save paul-asvb/c7b85880e49250bcb4d6efcd664aa0f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import imaplib | |
| import email | |
| from email.header import decode_header, make_header | |
| from email.utils import parseaddr | |
| from datetime import datetime | |
| # ============================== | |
| # CONFIGURATION CONSTANTS | |
| # ============================== | |
| IMAP_SERVER = "imap.xx.com" | |
| IMAP_PORT = 993 | |
| IMAP_USERNAME = "[email protected]" | |
| IMAP_PASSWORD = "xx" # ⚠️ Consider storing securely! | |
| MAILBOX = "INBOX" | |
| SINCE_DATE = "2025-08-01" # or None, format YYYY-MM-DD | |
| LIMIT_MESSAGES = 0 # 0 = no limit | |
| IMAP_DATE_FMT = "%d-%b-%Y" | |
| def to_imap_date(s: str) -> str: | |
| return datetime.strptime(s, "%Y-%m-%d").strftime(IMAP_DATE_FMT) | |
| def decode_header_str(h): | |
| if not h: | |
| return "" | |
| try: | |
| return str(make_header(decode_header(h))) | |
| except Exception: | |
| return h | |
| def main(): | |
| # Connect | |
| M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) | |
| M.login(IMAP_USERNAME, IMAP_PASSWORD) | |
| typ, _ = M.select(MAILBOX, readonly=True) | |
| if typ != "OK": | |
| raise SystemExit(f"Failed to select mailbox {MAILBOX}") | |
| # Search | |
| criteria = f"(SINCE {to_imap_date(SINCE_DATE)})" | |
| typ, data = M.search(None, criteria) | |
| if typ != "OK": | |
| raise SystemExit(f"Search failed with {criteria}") | |
| ids = data[0].split() | |
| if LIMIT_MESSAGES > 0: | |
| ids = ids[:LIMIT_MESSAGES] | |
| seen = set() | |
| for num in ids: | |
| typ, msg_data = M.fetch(num, b"BODY.PEEK[HEADER.FIELDS (FROM)]") | |
| if typ != "OK" or not msg_data: | |
| continue | |
| raw_headers = b"".join(p[1] for p in msg_data if isinstance(p, tuple)) | |
| msg = email.message_from_bytes(raw_headers) | |
| from_hdr = decode_header_str(msg.get("From", "")).strip() | |
| name, addr = parseaddr(from_hdr) | |
| display = f"{name} <{addr}>" if name else addr | |
| if addr.lower() in seen: | |
| continue | |
| seen.add(addr.lower()) | |
| print(display) | |
| M.close() | |
| M.logout() | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment