Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading