2016-10-04 34 views
0

好的,所以我試圖將發送到特定帳戶的pdf附件保存到特定的網絡文件夾,但我被困在附件部分。我有下面的代碼來拉取看不見的消息,但我不知道如何讓「零件」保持不動。我想我可以弄清楚,如果我能弄清楚如何保持電子郵件信息完整。我從來沒有讓它過去「讓它走路」輸出。此帳戶中的所有測試電子郵件都包含pdf附件。提前致謝。從IMAP帳戶提取PDF附件 - python 3.5.2

import imaplib 
import email 
import regex 
import re 

user = 'some_user' 
password = 'gimmeAllyerMoney' 

server = imaplib.IMAP4_SSL('mail.itsstillmonday.com', '993') 
server.login(user, password) 
server.select('inbox') 

msg_ids=[] 
resp, messages = server.search(None, 'UNSEEN') 
for message in messages[0].split(): 
     typ, data = server.fetch(message, '(RFC822)') 
     msg= email.message_from_string(str(data[0][1])) 
     #looking for 'Content-Type: application/pdf 
     for part in msg.walk(): 
       print("Made it to walk") 
       if part.is_multipart(): 
         print("made it to multipart") 
       if part.get_content_maintype() == 'application/pdf': 
         print("made it to content") 
+0

這些消息是多部分消息嗎? 'maintype'只是'application'的一部分,內容類型爲:application/pdf' – tripleee

+0

@tripleee'Content-Type:multipart'出現在消息頭中。我也會爲應用程序/ pdf作更新。 – AlliDeacon

回答

0

您可以使用part.get_content_type()得到充分的內容類型和part.get_payload()來獲取有效載荷如下:

for part in msg.walk(): 
    if part.get_content_type() == 'application/pdf': 
     # When decode=True, get_payload will return None if part.is_multipart() 
     # and the decoded content otherwise. 
     payload = part.get_payload(decode=True) 

     # Default filename can be passed as an argument to get_filename() 
     filename = part.get_filename() 

     # Save the file. 
     if payload and filename: 
      with open(filename, 'wb') as f: 
       f.write(payload) 

注意,作爲tripleee指出的那樣,一個內容類型爲「application/pdf」的部分:

>>> part.get_content_type() 
"application/pdf" 
>>> part.get_content_maintype() 
"application" 
>>> part.get_content_subtype() 
"pdf" 
+0

我可以在沒有將其轉換爲字符串的情況下運行消息嗎?我認爲這可能是我的問題所在:'message for message [0] .split(): typ,data = server.fetch(message,'(RFC822)') msg = email.message_from_string(str [0] [1]))'我在走消息之前是否應該做其他事情? – AlliDeacon

+0

也許你應該使用email.message_from_bytes(data [0] [1])來解析消息,如下所示:https://stackoverflow.com/questions/38739739/str-object-has-no-attribute-message-from -bytes。 – jerry