Python pull back plain text body from message from IMAP account

拜拜、爱过 提交于 2020-01-30 12:45:35

问题


I have been working on this and am missing the mark.

I am able to connect and get the mail via imaplib.

msrv = imaplib.IMAP4(server)
msrv.login(username,password)

# Get mail

msrv.select()

#msrv.search(None, 'ALL')

typ, data = msrv.search(None, 'ALL')

# iterate through messages
for num in data[0].split():
    typ, msg_itm = msrv.fetch(num, '(RFC822)')
    print msg_itm
    print num 

But what I need to do is get the body of the message as plain text and I think that works with the email parser but I am having problems getting it working.

Does anyone have a complete example I can look at?

Thanks,


回答1:


To get the plain text version of the body of the email I did something like this....

xxx= data[0][1] #puts message from list into string


xyz=email.message_from_string(xxx)# converts string to instance of message xyz is an email message so multipart and walk work on it.

#Finds the plain text version of the body of the message.

if xyz.get_content_maintype() == 'multipart': #If message is multi part we only want the text version of the body, this walks the message and gets the body.
    for part in xyz.walk():       
        if part.get_content_type() == "text/plain":
            body = part.get_payload(decode=True)
        else:
                    continue



回答2:


Here is a minimal example from the docs:

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

In this case, data[0][1] contains the message body.



来源:https://stackoverflow.com/questions/7519964/python-pull-back-plain-text-body-from-message-from-imap-account

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!