Imap-工具。仅将带有附件的邮件标记为“已看过”

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

提问人:xiii 提问时间:12/29/2022 更新时间:1/9/2023 访问量:261

问:

我正在使用 imap 工具从未读电子邮件中下载附件。 我需要仅将那些包含附件且已下载的邮件标记为已查看。 下面的代码有效,但将所有未读消息标记为已查看。

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)
python imap-tools

评论

1赞 tripleee 12/29/2022
你有;你想象它有什么作用?mark_seen=True
0赞 xiii 12/29/2022
我知道什么。但我不知道python。昨天我在 github 上阅读了 imap-tools 的示例并编写了这个脚本。我的知识还不够。mark_seen=True

答:

2赞 Adelina 12/29/2022 #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)

评论

0赞 xiii 12/29/2022
谢谢 它有效。您只需要添加导入imap_tools,否则我们会收到错误 NameError: name 'imap_tools' is not defined。
0赞 Vladimir 1/9/2023 #2

正确答案:

使用 fetch arg mark_seen=False