问题
So sometimes the text/plain is in the top level "parts" array of a GmailAPI recovered email and other times it is nested down in the JSON if there are attachments or inline emails then it is nested down deeper.
How should I approach always being able to retuurn the text/plain version of body.
Thanks
回答1:
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'])
回答2:
Testing different kind of emails directly in "Try this API" Gmail.messages.get [1], you can check the different kind of results. The results I got:
1) Plain text message: directly from "payload"(text/plain) attribute.
2) Html message: "payload"(multipart/alternative)->Parts[0](First object of the array).
3) Plain text message with file attached: "payload"(multipart/mixed)->Parts[0]"text/plain".
4) Html message with file attached: "payload"(multipart/mixed)->Parts[0]"multipart/alternative"->Parts[0]"text/plain".
[1] https://developers.google.com/gmail/api/v1/reference/users/messages/get
来源:https://stackoverflow.com/questions/59603771/how-to-get-the-text-plain-part-of-a-gmail-api-message