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

Question:

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)
Asked By: xiii

||

Answers:

    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)

Answered By: Adelina

Right answer:

Use fetch arg mark_seen=False

Answered By: Vladimir
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.