106 lines
3.8 KiB
Python
106 lines
3.8 KiB
Python
import win32com.client
|
|
from datetime import datetime, timedelta
|
|
from tqdm import tqdm
|
|
import time
|
|
|
|
# --- CONFIGURAZIONE ---
|
|
ARCHIVE_NAME = "Archivio online - alessandro.battilani@intesasanpaolo.com"
|
|
MONTHS_LIMIT = 3
|
|
# ----------------------
|
|
|
|
def mostra_cartelle(folder_object, indent=""):
|
|
for folder in folder_object.Folders:
|
|
print(f"{indent}{folder.Name}")
|
|
# Richiama se stessa per cercare sottocartelle
|
|
mostra_cartelle(folder, indent + " ")
|
|
|
|
def main():
|
|
print("Connessione a Outlook in corso...")
|
|
try:
|
|
outlook = win32com.client.Dispatch("Outlook.Application")
|
|
namespace = outlook.GetNamespace("MAPI")
|
|
|
|
# Partendo dalla radice dell'account predefinito
|
|
# root = namespace.GetDefaultFolder(6).Parent
|
|
# mostra_cartelle(root)
|
|
email_sent = namespace.GetDefaultFolder()
|
|
inbox = namespace.GetDefaultFolder(6)
|
|
archive_root = namespace.Folders.Item(ARCHIVE_NAME)
|
|
except Exception as e:
|
|
print(f"Errore di connessione: {e}")
|
|
return
|
|
|
|
cutoff_date = datetime.now() - timedelta(days=MONTHS_LIMIT * 30)
|
|
filter_date_str = cutoff_date.strftime("%d/%m/%Y %H:%M")
|
|
|
|
|
|
|
|
filter_str = f"[ReceivedTime] < '{filter_date_str}'"
|
|
|
|
items = inbox.Items.Restrict(filter_str)
|
|
items.Sort("[ReceivedTime]", True)
|
|
|
|
total_items = items.Count
|
|
if total_items == 0:
|
|
print("Nessuna email da archiviare.")
|
|
return
|
|
|
|
print(f"Trovate {total_items} email vecchie. Inizio archiviazione...")
|
|
|
|
archived_count = 0
|
|
mesi_it = {1: "Gennaio", 2: "Febbraio", 3: "Marzo", 4: "Aprile", 5: "Maggio", 6: "Giugno",
|
|
7: "Luglio", 8: "Agosto", 9: "Settembre", 10: "Ottobre", 11: "Novembre", 12: "Dicembre"}
|
|
|
|
with tqdm(total=total_items, desc="Archiviazione", unit="mail", colour='green') as pbar:
|
|
for i in range(total_items, 0, -1):
|
|
try:
|
|
item = items.Item(i)
|
|
pbar.update(1)
|
|
|
|
if not hasattr(item, 'ReceivedTime'):
|
|
continue
|
|
|
|
rt = item.ReceivedTime
|
|
received_time = datetime(rt.year, rt.month, rt.day, rt.hour, rt.minute)
|
|
anno_str = str(received_time.year)
|
|
nome_mese = mesi_it[received_time.month]
|
|
pbar.set_description(f"Mese: {nome_mese} {anno_str}")
|
|
|
|
# Cartelle
|
|
month_folder_name = f"{received_time.month:02d}-{nome_mese}"
|
|
try:
|
|
y_f = archive_root.Folders.Item(anno_str)
|
|
except: # noqa: E722
|
|
y_f = archive_root.Folders.Add(anno_str)
|
|
try:
|
|
target_folder = y_f.Folders.Item(month_folder_name)
|
|
except: # noqa: E722
|
|
target_folder = y_f.Folders.Add(month_folder_name)
|
|
|
|
# --- TENTA LO SPOSTAMENTO CON RETRY ---
|
|
archived_item = None
|
|
for tentativo in range(3):
|
|
try:
|
|
archived_item = item.Move(target_folder)
|
|
if archived_item:
|
|
archived_item.Save()
|
|
time.sleep(0.5) # Pausa vitale per il server
|
|
break
|
|
except: # noqa: E722
|
|
time.sleep(1) # Aspetta se il server è occupato
|
|
|
|
if not archived_item:
|
|
pbar.set_postfix(error="Move fallito")
|
|
continue
|
|
|
|
archived_count += 1
|
|
pbar.set_postfix(archiviate=archived_count)
|
|
|
|
except Exception as e:
|
|
pbar.set_postfix(last_err=str(e)[:15])
|
|
continue
|
|
|
|
print(f"\nCompletato. Archiviate: {archived_count}")
|
|
|
|
if __name__ == "__main__":
|
|
main() |