IMAP、查看电子邮件的标签、Python 和 Gmail

IMAP, view email's labels, Python & Gmail

如何查看电子邮件的标签?

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myaccountxyz@gmail.com', mypassword)

mail.select("my-folder") # finds emails with this label
result, data = mail.uid('search', None, 'all')

for email_uid in data[0].split():
    result, data_single = mail.uid('fetch', email_uid, '(RFC822)')
    raw_email = data_single[0][1]
    email_message = email.message_from_string(raw_email)
    sender = email_message['From']

    # get list of this email's labels

我自己还没有尝试过这段代码,但根据 Google IMAP Extensions,你应该可以只获取 X-GM-LABELS 项:

typ, dat = mail.uid('fetch', email_uid, 'X-GM-LABELS')