imap_duplicados-20170320.py (Código fuente)

#!/usr/bin/env python3

# (c) 2017 Jesús Cea Avión - jcea@jcea.es
# This code is licensed under AGPLv3.

import sys

import imapclient

imap = imapclient.IMAPClient('127.0.0.1', use_uid=True, timeout=60)
imap.login('X', 'X')
# busqueda = 'BODY.PEEK[HEADER.FIELDS (MESSSAGE-ID,DATE)]'
busqueda = 'BODY.PEEK[HEADER]'
b_busqueda = bytes(busqueda.replace('.PEEK', ''), 'utf-8')
folders = imap.list_folders()
for num, (_, _, folder) in enumerate(folders, 1):
    print(f'Procesando la carpeta "{folder}" ({num}/{len(folders)}): ', end='')
    sys.stdout.flush()
    imap.select_folder(folder)
    reply = imap.fetch('1:*', busqueda)
    already_seen = set()
    to_delete = []
    num_msgs = 0
    for uid, values in reply.items():
        num_msgs += 1
        headers = values[b_busqueda]
        if headers in already_seen:
            to_delete.append(uid)
        else:
            already_seen.add(headers)

    print(num_msgs, to_delete)
    imap.add_flags(to_delete, r'\DELETED', silent=True)
    imap.close_folder()