The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Make a CLI email search tool

Here’s a basic CLI (Command-Line Interface) email search tool written in Python. This script searches for specific keywords in a set of .eml files or plain text files stored in a directory. It displays matching emails along with subject lines and file names.


Features:

  • Searches all files in a given directory

  • Supports keyword matching in subject/body

  • Works with .eml and plain .txt files

  • CLI arguments for keyword and folder path


Code: email_search_cli.py

python
import os import argparse from email import policy from email.parser import BytesParser def parse_email(file_path): try: with open(file_path, 'rb') as f: msg = BytesParser(policy=policy.default).parse(f) subject = msg['subject'] or "(No Subject)" body = msg.get_body(preferencelist=('plain')) if body: body_content = body.get_content() else: body_content = msg.get_payload() return subject, body_content except Exception as e: return None, f"Failed to parse {file_path}: {str(e)}" def search_emails(directory, keyword): print(f"nSearching for keyword: '{keyword}' in directory: {directory}n") for root, _, files in os.walk(directory): for file in files: if file.endswith(('.eml', '.txt')): file_path = os.path.join(root, file) subject, content = parse_email(file_path) if content and keyword.lower() in content.lower(): print(f"[MATCH] {file}") print(f"Subject: {subject}") print(f"Path: {file_path}n") def main(): parser = argparse.ArgumentParser(description='Search emails in a directory by keyword.') parser.add_argument('keyword', type=str, help='Keyword to search for') parser.add_argument('directory', type=str, help='Directory containing email files (.eml or .txt)') args = parser.parse_args() if not os.path.isdir(args.directory): print(f"Error: Directory '{args.directory}' does not exist.") return search_emails(args.directory, args.keyword) if __name__ == "__main__": main()

How to Use

  1. Save the file as email_search_cli.py

  2. Run it from your terminal:

    bash
    python email_search_cli.py "invoice" /path/to/email/folder

This will scan all .eml or .txt files in the specified folder for the keyword “invoice”.

Let me know if you need enhancements like date filtering, sender-based search, or exporting results.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About