2011-09-22 74 views
0

拉回来纯文本正文我一直在这一点,我缺少的标志。Python从消息从IMAP帐户

我能够连接,并通过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 

但我需要做的就是这条消息是纯文本的身体,我认为,随着电子邮件分析器的作品,但我有得到它的工作的问题。

有没有人有一个完整的例子我可以看看?

谢谢,

回答

1

下面是从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() 

在这种情况下,数据[0] [1]包含消息体。

+1

感谢。它给了我信息。有没有办法让身体而不是附件? – TheMadAdmin

+0

试试这个:进口电子邮件,味精= email.message_from_string(数据[0] [1]) –

8

为了让我做这样的事情电子邮件的正文的纯文本版本....

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 
+0

+1散步()..帮助了我很多! – Spaceghost

+1

,如果它不是'multipart'? – eLRuLL