[ACCEPTED]-python imap: how to parse multipart mail content-imap
Accepted answer
For parsing emails I have used Message.walk()
method like 3 this:
if msg.is_multipart():
for part in msg.walk():
...
For content you can try: part.get_payload()
. For content-type 2 there is: part.get_content_type()
You will find documetation here: http://docs.python.org/library/email.message.html
You 1 can also try email
module with its iterators.
http://docs.python.org/library/email.html
A very simple example (msg_as_str contains 1 the raw bytes you got from the imap server):
import email
msg = email.message_from_string(msg_as_str)
print msg["Subject"]
I have wrote this code. You can use it if 3 you like it for parsing multipart content:
if mime_msg.is_multipart():
for part in mime_msg.walk():
if part.is_multipart():
for subpart in part.get_payload():
if subpart.is_multipart():
for subsubpart in subpart.get_payload():
body = body + str(subsubpart.get_payload(decode=True)) + '\n'
else:
body = body + str(subpart.get_payload(decode=True)) + '\n'
else:
body = body + str(part.get_payload(decode=True)) + '\n'
else:
body = body + str(mime_msg.get_payload(decode=True)) + '\n'
body = bytes(body,'utf-8').decode('unicode-escape')
And 2 if you want to take out in plain text then 1 convert body into html2text.HTML2Text()
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.