简体   繁体   English

使用 IMAP 将 label 添加到 Gmail,Python

[英]Add label to Gmail using IMAP, Python

I'm trying to add a label to a subset of gmails.我正在尝试将 label 添加到 gmail 的子集。 It's really buggy.真的很坑。 It works, then doesn't work, then adds to the first email only...它有效,然后无效,然后仅添加到第一个 email ......

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

label_to_add = "label-to-add" # previously created in Gmail

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']
    
    mail.store(email_uid, '+X-GM-LABELS', '('+label_to_add+')')
    # also tried without the parenthesis
    mail.store(email_uid, '+X-GM-LABELS', label_to_add)

If you use mail.uid('search'... you need to use mail.uid('store', ... otherwise you're mixing UIDs and MSNs (message sequence number) which don't correspond, so sometimes you get lucky and your UIDs happen to be low enough to hit an MSN.如果您使用mail.uid('search'...您需要使用mail.uid('store', ...否则您将混合不对应的 UID 和 MSN(消息序列号),所以有时您幸运的是,您的 UID 恰好足够低到可以访问 MSN。

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

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