如何获取Gmail API邮件的文本/纯文本部分 [英] How to get the text/plain part of a Gmail API message

查看:58
本文介绍了如何获取Gmail API邮件的文本/纯文本部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,有时文本/纯文本位于GmailAPI恢复的电子邮件的顶级部分"数组中,而有时,如果有附件或嵌入式电子邮件,则将其嵌套在JSON中,然后将其嵌套得更深.

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.

谢谢

推荐答案

我实际上也遇到了这个问题,希望在这里找到一个遮阳篷.我绝不是python专家,而且我不是stackoverflow初学者:-).但让我与您分享我的解决方案和思路.

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.

我们遇到的问题是messagePart被嵌套了x次.因此,我们不知道要检索的内容的深度和存储位置.我们还知道,如果传递的对象中没有零件对象,那么我们处于最低级别,并且我们可以停止寻找.

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很幸运地接受函数递归,这意味着已定义的函数可以调用自身.

Python luckely accepts function recursion, which means a defined function, can call itself.

唯一缺少的是在顶层(在[有效负载]的正文中)查找您的内容.在此示例中,我以text/plain或text/html查找电子邮件.我希望这可以帮助您了解如何使用函数递归来遍历所有部分.

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

这篇关于如何获取Gmail API邮件的文本/纯文本部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆