2016-10-04 14 views
0

特定のアカウントに送信されたPDF添付ファイルを特定のネットワークフォルダに保存しようとしていますが、添付ファイルが残っています。見えないメッセージを引き出すために次のコードがありますが、 "パーツ"を元のままにする方法がわかりません。私は、もし私が電子メールメッセージを完成させ続ける方法を見つけ出すことができれば、これを理解できるかもしれないと思う。私はそれを過去にすることはありません "歩くために作られた"出力。このアカウントのすべてのテスト電子メールには、pdf添付ファイルが含まれています。前もって感謝します。 IMAPアカウントからのPDF添付ファイルの抽出 - python 3.5.2

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とするために、指摘されていること:

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'は、' Content-type:application/pdf'のための 'application'です。 – tripleee

+0

@tripleee' Content-Type:multipart'がメッセージヘッダに現れます。私はアプリケーション/ pdfの部分も更新します。 – AlliDeacon

答えて

0

次のようにペイロードを取得するために完全なコンテンツタイプとpart.get_payloadを()を取得するpart.get_content_typeを()を使用することができますコンテンツタイプが「application/pdf」の部品:

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

文字列に変換せずにメッセージを部分に実行できますか?私の問題がどこにあるのだろうと思っています: 'message in messages [0] .split(): typ、data = server.fetch(message、 '(RFC822)') msg = email.message_from_string(str(data [0] [1])) '私はメッセージを歩く前に何か他のことをしていますか? – AlliDeacon

+0

メールを解析するのにemail.message_from_bytes(data [0] [1])を使うべきでしょう。https://stackoverflow.com/questions/38739739/str-object-has-no-attribute-message-fromバイト。 – jerry

関連する問題