I’m trying to get all labels from my mails but it seems like I can’t get the label I have currently selected, and by that, I can’t delete it when I want to move the mail form one label to another.
Here’s an example of what I’m tyring to do:
I have a label called ‘POTATO’ with sub-labels ‘POTATO/Done’ and ‘POTATO/Error’.
I also have a second label that I made to try some things called ‘POTATO2’.
Here’s an example of my code:
import imaplib
imap_name = "[email protected]"
imap_pass = "mypassword"
M = imaplib.IMAP4_SSL('imap.gmail.com', 993)
M.login(imap_name, imap_pass)
M.select("POTATO")
resp, data = M.uid('search', None, 'ALL')
if resp == 'OK':
uids = data[0].split()
for uid in uids:
resp, data = M.uid('fetch', uid, 'X-GM-LABELS')
if resp == 'OK':
raw_data = data[0]
if isinstance(raw_data, bytes):
raw_data = raw_data.decode('utf-8')
# Parsing the labels to read them easier
if 'X-GM-LABELS' in raw_data:
labels_start = raw_data.find('(') + 1
labels_end = raw_data.rfind(')')
labels_raw = raw_data[labels_start:labels_end].strip()
cleaned_labels = labels_raw.replace('"', '').replace('\', '').split()
print(f"Labels for UID {uid.decode('utf-8')}: {cleaned_labels[1]}")
else:
print(f"No labels found for UID {uid.decode('utf-8')}")
else:
print(f"Error: expected bytes but got {type(raw_data)} for UID {uid.decode('utf-8')}")
And the output:
Labels for UID 31: ['X-GM-LABELS', '(Important', 'POTATO/Done)', 'UID', '31']
Labels for UID 32: ['X-GM-LABELS', '(POTATO2)', 'UID', '32']
Both mails also have the ‘POTATO’ label added, but it’s not showing there, so I can’t simply remove it. What am I missing? Is there no way to get the label form the one you have selected? Because if I select the ‘POTATO2’ label, the second mail will only have the “POTATO” label.
I’ve tried to create multiple labels to check if it was something related to the first label, but it seems like it doesn’t have anything to do. I also tried with a different library (IMAPClient) but at the end I get the same results.
RubenC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.