Created
March 3, 2025 19:44
-
-
Save radupotop/fd31ae82b5816951b668b1bd3ddf0485 to your computer and use it in GitHub Desktop.
Rename email files to timestamp-subject-sender
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 argparse | |
from email import policy | |
from email.parser import BytesParser | |
from email.utils import parsedate_to_datetime | |
from pathlib import Path | |
from typing import Iterable | |
from zoneinfo import ZoneInfo | |
TZ = ZoneInfo('Europe/London') | |
def process_eml_file(eml_file: Path): | |
try: | |
# Read the .eml file in binary mode | |
msg_bytes = eml_file.read_bytes() | |
# Parse the email content | |
msg = BytesParser(policy=policy.default).parsebytes(msg_bytes, headersonly=True) | |
# Extract the Date header | |
date_header = msg.get('Date') | |
subject = msg.get('Subject') | |
from_ = msg.get('From') | |
if date_header and subject: | |
# Parse the date header into a datetime object | |
date_object = parsedate_to_datetime(date_header) | |
# Format the date for the filename | |
formatted_date = date_object.astimezone(TZ).strftime('%Y-%m-%d_%H%M') | |
clean_subject = subject.replace('/', '_') | |
# Create new filename | |
new_filename = f"{formatted_date} {clean_subject} - {from_}{eml_file.suffix}" | |
print(f"Rename\t{eml_file}\nTo\t{new_filename}") | |
# Rename the original file to the new filename | |
eml_file.rename(new_filename) | |
else: | |
print(f"No headers found in {eml_file}") | |
except Exception as e: | |
print(f"Error processing {eml_file}: {e}") | |
def runall(email_files: Iterable[Path]): | |
for eml in email_files: | |
process_eml_file(eml) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('email_files', type=str, nargs='+') | |
args = parser.parse_args() | |
runall(map(Path, args.email_files)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment