[英]How to copy a message from one imap server to another imap server using Python imaplib?
[英]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.