I think you should use label['id']
rather than label['name']
. Sometimes, these two have the same value; sometimes, they don't.
Ref: https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages/list#http-request
for label in labels:
if label['type'] == 'user':
label_id = label['id'] # Use the label ID, not the name
results = service.users().messages().list(
userId='me',
labelIds=[label_id], # This works!
maxResults=2
).execute()
# Do something with results here
print(f"Messages with label {label['name']}:", results.get('messages', []))
break # Remove break if you want to process all labels