Python - Extract the body from a mail in plain text

前端 未结 3 1764
挽巷
挽巷 2021-02-08 02:12

I want to extract only the body of a message and return it. I can filter on the fields and display the snippet but not the body.

def GetMimeMessage(service, user         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-08 02:38

    Thanks. So after some modifications, here the solution:

    def GetMessageBody(service, user_id, msg_id):
        try:
                message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
                msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
                mime_msg = email.message_from_string(msg_str)
                messageMainType = mime_msg.get_content_maintype()
                if messageMainType == 'multipart':
                        for part in mime_msg.get_payload():
                                if part.get_content_maintype() == 'text':
                                        return part.get_payload()
                        return ""
                elif messageMainType == 'text':
                        return mime_msg.get_payload()
        except errors.HttpError, error:
                print 'An error occurred: %s' % error
    

提交回复
热议问题