Reputation: 29585
I'm trying to add a label to a subset of gmails. It's really buggy. It works, then doesn't work, then adds to the first email only...
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]', 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)
Upvotes: 2
Views: 1220
Reputation: 11000
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.
Upvotes: 4