pythonimap-tools

Imap-tools. Mark as 'seen' only messages with attachments


I am using imap-tools to download attachments from unread emails. I need mark as seen only those messages that contain attachments and have been downloaded. The code below works, but marks all unread messages as seen.

import ssl
from imap_tools import MailBox, AND
from datetime import date
context = ssl.create_default_context()
today = date.today()
with MailBox('imap.gmail.com', ssl_context=context).login('email', 'password', 'INBOX') as mailbox:
    for msg in mailbox.fetch(AND(seen=False), mark_seen = True, bulk = True):
        for att in msg.attachments:
            print(att.filename, today)
            if att.filename.lower().endswith('.xlsx'):
                with open('D:/pp/nf/mail/1.txt', 'a') as f:
                    print(att.filename, today, file=f)
                with open('D:/pp/nf/mail/{}'.format(att.filename), 'wb') as f:
                    f.write(att.payload)

Solution

  •     seen_msgs = []
        for msg in mailbox.fetch(AND(seen=False), mark_seen = False, bulk = True):
            for att in msg.attachments:
                print(att.filename, today)
                if att.filename.lower().endswith('.xlsx'):
                    with open('D:/pp/nf/mail/1.txt', 'a') as f:
                        print(att.filename, today, file=f)
                    with open('D:/pp/nf/mail/{}'.format(att.filename), 'wb') as f:
                        f.write(att.payload)
                    seen_msgs.append(msg.uid)
        mailbox.flag(seen_msgs, [imap_tools.MailMessageFlags.SEEN], True)