【问题标题】:Transferring emails in gmail from one label to another in python using IMAP使用 IMAP 将 gmail 中的电子邮件从一个标签转移到 python 中的另一个标签
【发布时间】:2019-08-02 05:03:28
【问题描述】:

我的电子邮件将被 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 收件箱中没有任何变化。

【问题讨论】:

  • 可能是个愚蠢的问题,但是您是否重新加载了 gmail web ui? IMAP 更改需要一些时间才能传播到 webui,并且 web ui 也会缓存信息。
  • @Max 是的,我尝试了几种代码变体,并多次重新加载了 gmail 网页。只是为了仔细检查我刚刚做到了。
  • 这个扩展没有合适的规范,但我注意到the guide 使用了括号... con.uid('STORE', uid, '+X-GM-LABELS', '(Checked)') 也许?
  • @arnt 我试过了,但仍然没有变化 con.uid('STORE', uid, '+X-GM-LABELS', '(Checked)') con.uid('STORE', uid, '-X-GM-LABELS', '(测试)')

标签: python gmail imap


【解决方案1】:

终于想出了解决办法。

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

【讨论】:

  • 我怀疑你的问题是 MSN/UID 混淆,真的。 .store() 函数不将 UID 作为参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多