2016-02-26 80 views
0

我有一個看起來有點像的電子郵件正文。Python解析郵件正文和截斷MIME頭文件

現在我想刪除它的所有標題,只是有對話的電子郵件文本。我怎麼能在Python中做到這一點?

我試過email.parser模塊,但是這並沒有給我我想要的結果。

請找到下面的代碼以獲取更多信息。

import email 
a="""--c66f5985-233d-4e89-b598-6398b60cbe00 
Content-Type: multipart/alternative; 
    differences="Content-Type"; 
    boundary="d5eff9f8-76b3-4320-adfb-1e51add8fa8f" 

--d5eff9f8-76b3-4320-adfb-1e51add8fa8f 
Content-Type: text/plain; charset=us-ascii 
Content-Transfer-Encoding: quoted-printable 

THis is a demo email body 

Thanks And Regards, 
Ana 
""" 



b = email.message_from_string(a) 
if b.is_multipart(): 
    for payload in b.get_payload(): 
     # if payload.is_multipart(): ... 
     print (payload.get_payload()) 
else: 
    print (b.get_payload()) 

回答

0
import imaplib,email 

hst = "your.host.adresse.com" 
usr = "login" 
pwd = "password" 

imap = imaplib.IMAP4(hst) 

try: 
    imap.login(usr, pwd) 
except Exception as e: 
    raise IOError(e) 

try: 
    imap.select("Inbox") # Tell Imap where to go 
    result, data = imap.uid('search', None, "ALL") 
    latest = data[0].split()[-1] 
    result, data = imap.uid('fetch', latest, '(RFC822)') 
    a = data[0][1] # This contains the Mail Data 


except Exception as e: 
    raise IOError(e) 

b = email.message_from_string(a) 
if b.is_multipart(): 
    for payload in b.get_payload(): 
     b = (payload.get_payload()) 
else: 
    b = (b.get_payload()) 

print b 

這將刪除所有來自你不希望出現在最終文本中的郵件的東西。我已經用你的代碼測試過了。你沒有顯示你如何導入郵件(你的a),所以我想這就是你從哪裏解碼的問題。

如果你有HTML郵件有任何問題:

from bs4 import BeautifulSoup 
soup = BeautifulSoup(b, 'html.parser') 
soup = soup.get_text() 
print soup 

這應該現在做的工作,但我建議你改變默認的Python解析器限於lxml或html5lib。

+0

如果我的電子郵件包含很多電子郵件線索,那該怎麼辦 – sangeet

+0

而我只是如上所示爲emailbody提供便利,沒有主機名和其他憑證...... – sangeet