2016-10-04 2 views
0

좋아, 특정 계정으로 특정 계정으로 보낸 PDF 첨부 파일을 특정 네트워크 폴더에 저장하려고하는데, 첨부 파일 부분에 붙어 있습니다. 보이지 않는 메시지를 가져 오는 다음 코드가 있지만 "부품"을 그대로 유지하는 방법을 모르겠습니다. 전자 메일 메시지를 완벽하게 유지하는 방법을 파악할 수 있다면 이것을 이해할 수있을 것 같습니다. 나는 결코 그것을 과거의 "걸음을 만든다"는 결과로 만들지 않습니다. 이 계정의 모든 테스트 전자 메일에는 pdf 첨부 파일이 포함됩니다. 미리 감사드립니다. IMAP 계정에서 PDF 첨부 파일 추출하기 - 파이썬 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

문자열로 변환하지 않고 부분으로 메시지를 실행할 수 있습니까? 그게 내 문제가 어디에있을 것 같아요 : 메시지의 메시지에 대한 : 0 :. 슬픈() : 일반, 데이터 = server.fetch (메시지, '(RFC822)') 메시지 = 이메일 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 바이트. – jerry

관련 문제