Python - Extract the body from a mail in plain text

前端 未结 3 1760
挽巷
挽巷 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:23

    Try this:

    mail param is your mime_msg variable

    def get_mpart(mail):
        maintype = mail.get_content_maintype()
        if maintype == 'multipart':
            for part in mail.get_payload():
                # This includes mail body AND text file attachments.
                if part.get_content_maintype() == 'text':
                    return part.get_payload()
            # No text at all. This is also happens
            return ""
        elif maintype == 'text':
            return mail.get_payload()
    
    
    def get_mail_body(mail):
        """
        There is no 'body' tag in mail, so separate function.
        :param mail: Message object
        :return: Body content
        """
        body = ""
        if mail.is_multipart():
            # This does not work.
            # for part in mail.get_payload():
            #    body += part.get_payload()
            body = get_mpart(mail)
        else:
            body = mail.get_payload()
        return body
    
    0 讨论(0)
  • 2021-02-08 02:38

    The base64url encoded string needs some alteration before passing into the decode function as below:

    msg_str = base64.urlsafe_b64decode(message['raw'].replace('-_', '+/').encode('ASCII'))
    

    See if this helps

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题