[英]How to extract the body of an multipart email and save the attachments using python IMAP?
[英]python imap: how to parse multipart mail content
郵件可以包含不同的塊,如:
--0016e68deb06b58acf04897c624e
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
content_1
...
--0016e68deb06b58acf04897c624e
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
content_2
... and so on
如何使用python獲取每個塊的內容?
還有如何獲得每個塊的屬性? (內容類型等)
http://docs.python.org/library/email.html
一個非常簡單的例子(msg_as_str包含從imap服務器獲得的原始字節):
import email
msg = email.message_from_string(msg_as_str)
print msg["Subject"]
我寫了這段代碼。 如果您喜歡它,可以使用它來解析多部分內容:
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')
如果你想用純文本取出然后將body轉換為html2text.HTML2Text()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.