使用Python和imaplib在GMail中移动电子邮件 [英] Move an email in GMail with Python and imaplib
本文介绍了使用Python和imaplib在GMail中移动电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够使用Python将GMail中的电子邮件从收件箱移动到另一个文件夹。
I want to be able to move an email in GMail from the inbox to another folder using Python. I am using imaplib and can't figure out how to do it.
推荐答案
IMAP没有明确的移动命令。您必须执行 COPY
,然后执行 STORE
(带有合适的标志来指示删除),最后执行抹去
。下面给出的例子适用于将消息从一个标签移动到另一个标签。虽然您可能希望添加更多的错误检查。
There is no explicit move command for IMAP. You will have to execute a COPY
followed by a STORE
(with suitable flag to indicate deletion) and finally expunge
. The example given below worked for moving messages from one label to the other. You'll probably want to add more error checking though.
import imaplib, getpass, re
pattern_uid = re.compile('\d+ \(UID (?P<uid>\d+)\)')
def connect(email):
imap = imaplib.IMAP4_SSL("imap.gmail.com")
password = getpass.getpass("Enter your password: ")
imap.login(email, password)
return imap
def disconnect(imap):
imap.logout()
def parse_uid(data):
match = pattern_uid.match(data)
return match.group('uid')
if __name__ == '__main__':
imap = connect('<your mail id>')
imap.select(mailbox = '<source folder>', readonly = False)
resp, items = imap.search(None, 'All')
email_ids = items[0].split()
latest_email_id = email_ids[-1] # Assuming that you are moving the latest email.
resp, data = imap.fetch(latest_email_id, "(UID)")
msg_uid = parse_uid(data[0])
result = imap.uid('COPY', msg_uid, '<destination folder>')
if result[0] == 'OK':
mov, data = imap.uid('STORE', msg_uid , '+FLAGS', '(\Deleted)')
imap.expunge()
disconnect(imap)
这篇关于使用Python和imaplib在GMail中移动电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文