首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Python中使用IMAP仅删除一条特定消息

如何在Python中使用IMAP仅删除一条特定消息
EN

Stack Overflow用户
提问于 2019-06-05 21:09:00
回答 1查看 77关注 0票数 0

我正在寻找一条特定的邮件,然后,在找到后,我想从收件箱中删除它。就这一个。我的代码:

代码语言:javascript
运行
复制
import email
import imaplib

def check_email(self, user, password, imap, port, message):
    M = imaplib.IMAP4_SSL(imap, port)
    M.login(user, password)
    M.select()
    type, message_numbers = M.search(None, '(ALL)')

    subjects = []

    for num in message_numbers[0].split():
        type, data = M.fetch(num, '(RFC822)')
        msg = email.message_from_bytes(data[0][1])
        subjects.append(msg['Subject'])

    if message in subjects:
        M.store(num, '+FLAGS', '\\Deleted')
    else:
        raise FileNotFoundError('Ooops!')

    M.close()
    M.logout()

我只想按标题查找并删除一个邮件,gven在变量(message)中。你能帮帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-06 15:48:12

循环遍历所有消息,如果其中任何一条消息有匹配的主题,则删除最后一条消息(这是num在循环结束后最终指向的消息)。您可能希望重新压缩代码,以便在循环中进行检查,并可能在找到所需的代码后放弃循环的其余部分。

代码语言:javascript
运行
复制
def check_email(self, user, password, imap, port, message):
    M = imaplib.IMAP4_SSL(imap, port)
    M.login(user, password)
    M.select()
    type, message_numbers = M.search(None, '(ALL)')

    found = False

    for num in message_numbers[0].split():
        type, data = M.fetch(num, '(RFC822)')
        msg = email.message_from_bytes(data[0][1])
        # No need to collect all the subjects in a list
        # Just examine the current one, then forget this message if it doesn't match
        if message in msg['Subject']:
            M.store(num, '+FLAGS', '\\Deleted')
            found = True
            break

    # Don't raise an exception before cleaning up
    M.close()
    M.logout()

    # Now finally
    if not Found:
        raise FileNotFoundError('Ooops!')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56461167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档