import imaplib
import email
import os
# generated by CHATGPT, not tested

# Configuration
IMAP_SERVER = "imap.example.com"  # Replace with your IMAP server
USERNAME = "your_username"  # Replace with your username
PASSWORD = "your_password"  # Replace with your password
DOWNLOAD_PATH = "./emails"  # Directory to save downloaded emails

# Create the download directory if it doesn't exist
if not os.path.exists(DOWNLOAD_PATH):
    os.makedirs(DOWNLOAD_PATH)

def list_and_download_emails():
    try:
        # Connect to the server
        mail = imaplib.IMAP4_SSL(IMAP_SERVER, 993)
        mail.login(USERNAME, PASSWORD)

        # Select the INBOX folder
        mail.select("INBOX")

        # Search for all emails in the inbox
        result, data = mail.search(None, "ALL")
        if result != "OK":
            print("No messages found!")
            return

        # Fetch the email IDs
        email_ids = data[0].split()
        print(f"Found {len(email_ids)} messages in INBOX.")

        # Display and optionally download the first 10 emails
        for i, email_id in enumerate(email_ids[:10]):
            result, msg_data = mail.fetch(email_id, "(RFC822)")
            if result != "OK":
                print(f"Failed to fetch email ID {email_id}")
                continue

            # Parse the email
            for response_part in msg_data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_bytes(response_part[1])
                    subject = msg["subject"]
                    print(f"Email {i + 1}: {subject}")

                    # Save email to file
                    with open(os.path.join(DOWNLOAD_PATH, f"email_{i + 1}.eml"), "wb") as f:
                        f.write(response_part[1])

        # Logout
        mail.logout()

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    list_and_download_emails()

