本文介绍了Python-从邮件中以纯文本形式提取正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想提取一条消息的正文并返回.我可以过滤字段并显示摘要,但不能显示正文.

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_id, msg_id):
    try:
            message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
            print 'Message snippet: %s' % message['snippet']
            msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
            mime_msg = email.message_from_string(msg_str)
            return mime_msg
    except errors.HttpError, error:
            print 'An error occurred: %s' % error

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

推荐答案

谢谢.因此,经过一些修改后,这里是解决方案:

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

这篇关于Python-从邮件中以纯文本形式提取正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 21:12