【问题标题】:How to get the text/plain part of a Gmail API message如何获取 Gmail API 消息的文本/纯文本部分
【发布时间】:2020-04-23 12:07:20
【问题描述】:

因此,有时 text/plain 位于 GmailAPI 恢复电子邮件的顶级“部分”数组中,有时它嵌套在 JSON 中,如果有附件或内联电子邮件,则嵌套更深。

我应该如何处理始终能够返回正文的文本/纯文本版本。

谢谢

【问题讨论】:

    标签: python gmail gmail-api


    【解决方案1】:

    其实我也有这个问题,希望能在这里找到一个遮阳篷。我绝不是 python 专家,更重要的是我是 stackoverflow 初学者:-)。但让我与您分享我的解决方案和我的思路。

    我们遇到的问题是 messagePart 嵌套了 x 次。因此,我们不知道我们想要检索的内容存储的深度和位置。我们也知道,如果传递的对象内部没有parts对象,那么我们就处于最低级别,可以停止查找。

    Python 幸运地接受函数递归,这意味着定义的函数可以调用自己。

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

    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】:

      直接在“Try this API”Gmail.messages.get [1] 中测试不同类型的电子邮件,您可以查看不同类型的结果。我得到的结果:

      1) 纯文本消息:直接来自“payload”(text/plain) 属性。

      2) Html 消息:“payload”(multipart/alternative)->Parts[0](数组的第一个对象)。

      3) 带有附加文件的纯文本消息:“payload”(multipart/mixed)->Parts[0]“text/plain”。

      4) 附加文件的 Html 消息:“payload”(multipart/mixed)->Parts[0]"multipart/alternative"->Parts[0]"text/plain"。

      [1]https://developers.google.com/gmail/api/v1/reference/users/messages/get

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-31
        • 2011-03-11
        • 1970-01-01
        • 2015-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-06
        相关资源
        最近更新 更多