import imaplib
import email
import os

# IMAP szerver és hitelesítés
IMAP_SERVER = "aps-exch01.aps.local"
IMAP_PORT = 993
USERNAME = "i.meszely@aps-hh.de"
PASSWORD = "virgI6774#Maci"
DOWNLOAD_DIR = r"C:\Downloads"

if not os.path.exists(DOWNLOAD_DIR):
    os.makedirs(DOWNLOAD_DIR)

# Kapcsolódás IMAP SSL-lel
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
mail.login(USERNAME, PASSWORD)

# Beérkezett üzenetek mappa kiválasztása
mail.select("INBOX")

# Csak olvasatlan levelek keresése
status, messages = mail.search(None, '(UNSEEN)')

if status == "OK":
    for num in messages[0].split():
        status, data = mail.fetch(num, "(RFC822)")
        if status != "OK":
            continue

        msg = email.message_from_bytes(data[0][1])

        for part in msg.walk():
            if part.get_content_type() == "application/pdf":
                filename = part.get_filename()
                if filename:
                    filepath = os.path.join(DOWNLOAD_DIR, filename)
                    with open(filepath, "wb") as f:
                        f.write(part.get_payload(decode=True))
                    print(f"Letöltve: {filepath}")

# Kapcsolat bontása
mail.close()
mail.logout()
