1

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)
xiii
  • 13
  • 2
  • 1
    You have `mark_seen=True`; what do you imagine it does? – tripleee Dec 29 '22 at 11:31
  • I know what `mark_seen=True` does. But I don't know python. Yesterday I read examples of imap-tools on github and wrote this script. My knowledge was not enough for more. – xiii Dec 29 '22 at 12:09

2 Answers2

1
    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)

Adelina
  • 10,915
  • 1
  • 38
  • 46
  • Thanks It works. You just need to add import imap_tools, otherwise we get the error NameError: name 'imap_tools' is not defined. – xiii Dec 29 '22 at 12:00
0

Right answer:

Use fetch arg mark_seen=False

Vladimir
  • 6,162
  • 2
  • 32
  • 36