如何在 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 在变量 (message) 中。
你能帮帮我吗?
您遍历所有消息,然后删除最后一条消息(这是 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!')
我正在寻找一封特定的邮件,找到后,我想将其从收件箱中删除。就这一个。 我的代码:
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) 中。 你能帮帮我吗?
您遍历所有消息,然后删除最后一条消息(这是 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!')