2014-11-18 1 views
4

python imaplib을 사용하여 전자 메일의 첨부 파일을 다운로드하고 저장합니다. 하지만 첨부 파일이있는 이메일이 다른 이메일 인 경우 x.get_payload()는 Nonetype입니다. 나는이 유형의 메일이 일부 이메일 클라이언트를 사용하여 전송된다고 생각한다. 파일 이름이 없기 때문에 헤더에서 'Content-Disposition'이라는 파일 이름을 변경해 보았습니다. 이름이 바뀐 파일이 열리 며이 파일에 쓸 때python smtplib을 사용하여 다른 이메일에 첨부 된 이메일을 저장하는 방법은 무엇입니까?

fp.write(part.get_payload(decode=True)) 

문자열이 나 버퍼가 예상되지만 유형이 없습니다.

>>>x.get_payload() 
[<email.message.Message instance at 0x7f834eefa0e0>] 
>>>type(part.get_payload()) 
<type 'list'> 
>>>type(part.get_payload(decode=True)) 
<type 'NoneType'> 

나는 = 진정한 디코드를 제거하고 난 첨부 파일로 볼 경우 이메일에 파일 이름을 편집하려 객체

x.get_payload()[0] 
<email.message.Message instance at 0x7f834eefa0e0> 

의 목록을 얻었다.

if part.get('Content-Disposition'): 
    attachment = str(part.get_filename()) #get filename 
    if attachment == 'None': 
     attachment = 'somename.mail' 
     attachment = self.autorename(attachment)#append (no: of occurences) to filename eg:filename(1) in case file exists 
     x.add_header('Content-Disposition', 'attachment', filename=attachment) 
     attachedmail = 1 

if attachedmail == 1: 
    fp.write(str(x.get_payload())) 
else: 
    fp.write(x.get_payload(decode=True)) #write contents to the opened file 

및 파일은 개체 이름의 파일 내용이

[ < email.message.Message instance at 0x7fe5e09aa248 > ] 

가 어떻게 파일이 첨부 된 이메일의 내용을 쓸 수 있습니다 아래에 주어진 포함?

답변

3

직접 해결했습니다. [< email.message.Message instance at 0x7fe5e09aa248]은 email.message.Message 인스턴스의 목록이며 각 인스턴스에는 .as_string() 메소드가 있습니다. 필자의 경우 파일에 .as_string()의 내용을 쓰면 파일에 포함 된 첨부 파일을 포함한 전체 헤더 데이터를 추출하는 데 도움이되었습니다. 그런 다음 파일을 한 줄씩 검사하고 인코딩 및 파일 형식에 따라 내용을 저장했습니다. 은 imaplib 이미 캡처 인라인 나타내는

for x in file_as_list: 
    if 'Content-Transfer-Encoding: quoted-printable' in x: 
     print 'qp encoded data found!' 
    if 'Content-Transfer-Encoding: base64' in x: 
     print 'base64 encoded data found!' 

부호화 데이터 파일

각 선 검사

>>>x.get_payload() 
[<email.message.Message instance at 0x7f834eefa0e0>] 
>>>fp=open('header','wb') 
>>>fp.write(x.get_payload()[0].as_string()) 
>>>fp.close() 
>>>file_as_list = [] 
>>>fp=open('header','rb') 
>>>file_as_list = fp.readlines() 
>>>fp.close() 

그리고는 (포함)의 첨부는 생략 될 수있다.

관련 문제