当前位置:   article > 正文

如何编写python程序把邮件提取邮件内容,Python-从邮件中以纯文本形式提取正文...

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

解决方案

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/822952
推荐阅读
相关标签
  

闽ICP备14008679号