Search code examples
pythongmailimap

Add label to Gmail using IMAP, Python


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

Solution

  • 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.