I actually had this issue as well, hoping to find an awnser here. I'm by no means a python expert and above that im a stackoverflow beginner :-). but let me share with you my solution and my train of thoughts.
The problem we have is that the messagePart is nested x number of times. Therefore we dont know exactly how deep and where the content is stored that we want to retreive. We also know that if there are no parts object inside the object that is passed, that we are at the lowest level and that we can stop looking.
Python luckely accepts function recursion, which means a defined function, can call itself.
The only thing that is missing is to look for your content on the top level (in the body that is in the [payload]). In this example I look for the email in text/plain or text/html.
I hope this gives you a hand on how to go trough all the parts by using function recursion.
client = MongoClient()
db = client['gmail']
message_full =service.users().messages().get(userId='me', id='175dff5c51f1f7ab', format='full').execute()
def message_full_recursion(m):
for i in m:
mimeType = (i['mimeType'])
print(mimeType)
if (i['mimeType']) in ('text/plain','text/html'):
print('found')
elif 'parts' in i:
print('recursing')
message_full_recursion(i['parts'])
message_full_recursion(message_full['payload']['parts'])