簡體   English   中英

如何在Python中使用IMAP僅刪除一條特定消息

[英]How to delete only one, specific message using IMAP in Python

我正在尋找一條特定的消息,然后,在找到之后,我想從收件箱中刪除它。 就是這個。 我的代碼:

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查找和刪除一封郵件。 你能幫助我嗎?

循環遍歷所有消息,然后刪除最后一個消息(如果任何一個消息具有匹配的主題,那么這是在循環結束后最終指向的num )。 您可能希望重新編寫代碼,以便在循環內部進行檢查,並在找到所需的循環后放棄其余的循環。

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!')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM