繁体   English   中英

使用IMAP将gmail中的电子邮件从一个标签转移到python中的另一个标签

[英]Transferring emails in gmail from one label to another in python using IMAP

我有一些将由gmail设置标记的电子邮件,将其移至名为“测试”的某个标签。 我正在编写的脚本运行时会下载该标签中的所有附件,然后将所有这些电子邮件移动到另一个名为“已检查”的标签(以保持该标签清晰)。

我已经完成了下载和解析部分,但似乎无法管理移动电子邮件。

这是程序的完成部分:

import imaplib
import email
import os
import base64
#import Const

user = 'email@gmail.com'
password = 'imnottellingyou'
imap_url = 'imap.gmail.com'

def auth(user, password, imap_url):
    con = imaplib.IMAP4_SSL(imap_url)
    con.login(user, password)
    return con

con = auth(user, password, imap_url)
con.select('Test')

type, data = con.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
print(id_list)
print(mail_ids)

for num in data[0].split():
    typ, data = con.fetch(num, '(RFC822)')
    raw_email = data[0][1]
    # converts byte literal to string removing b''
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)

    for part in email_message.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()

        if bool(fileName):
            filePath = os.path.join(
                'C:/Users/User/Desktop/test', fileName)
            if not os.path.isfile(filePath):
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
for uid in id_list:
    con.uid('STORE', uid, '+X-GM-LABELS', 'Checked')
    con.uid('STORE', uid, '-X-GM-LABELS', 'Test')

这是麻烦区域。 这是我尝试过的:

#after emails in label have been checked for attachments and downloaded
#emails will be transferred to a "checked" labe

for uid in id_list:
    con.uid('STORE', uid, '+X-GM-LABELS', 'Checked')
    con.uid('STORE', uid, '-X-GM-LABELS', 'Test')

该程序执行正常,并且没有错误消息出现,但我的gmail收件箱中没有任何变化。

终于能够提出一个解决方案。

for uid in id_list:
    #adds the checked label (new label) to all emails that are in the id list
    con.store(uid, '+X-GM-LABELS', '(Checked)')
    #instead of "removing" original label it deletes the email from the label
    #since labels act like folders in gmail
    con.store(uid,'+FLAGS', '\\Deleted')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM