2011-12-06 3 views
0

다음 코드를 사용하여 특정 Gmail 폴더에있는 모든 이메일을 내보내고 있습니다.Python을 사용하여 Gmail 내보내기 imaplib - 줄 바꿈 문제로 맹 글링 된 텍스트

잘 작동한다는 점에서 내가 기대하는 모든 이메일을 꺼내지 만, CR (새크라멘토) 또는 줄 바꿈에 대한 인코딩을 망가 뜨리는 것으로 보입니다.

코드 :

import imaplib 
import email 
import codecs 
mail = imaplib.IMAP4_SSL('imap.gmail.com') 
mail.login('[email protected]', 'myPassword') #user/password 
mail.list() 
mail.select("myFolder") # connect to folder with matching label 

result, data = mail.uid('search', None, "ALL") # search and return uids instead 
i = len(data[0].split()) 

for x in range(i): 
    latest_email_uid = data[0].split()[x] 
    result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)') 
    raw_email = email_data[0][1] 
    email_message = email.message_from_string(raw_email) 
    save_string = str("C:\\\googlemail\\boxdump\\email_" + str(x) + ".eml") #set to save location 
    myfile = open(save_string, 'a') 
    myfile.write(email_message) 
    myfile.close() 

내 문제는 시간 나는 개체를 얻을 자사 내가 잘못 줄 바꿈 또는 캐리지 리턴 플래그를 해석하는 가정입니다 '= 0A', 흩어져.

16 진수로 [d3 03 03 0a]를 찾을 수 있지만 '문자'가 아니기 때문에 str.replace()가 부품을 꺼낼 수있는 방법을 찾을 수 없습니다. 실제로 개행 플래그를 원하지 않습니다.

나는 진수로 전체 문자열을 변환하고,이 종류/정규식 일의 교체하는 수행하지만 살인 이상처럼 보인다 수 - 문제는 소스 데이터의 인코딩/읽기에있을 때

무엇을 나는 참조 :

==== 
CAUTION: This email message and any attachments con= tain information that may be confidential and may be LEGALLY PRIVILEGED. If yo= u are not the intended recipient, any use, disclosure or copying of this messag= e or attachments is strictly prohibited. If you have received this email messa= ge in error please notify us immediately and erase all copies of the message an= d attachments. Thank you. 
==== 

내가 원하는 : 당신이보고있는 것은 Quoted Printable 인코딩입니다

==== 
CAUTION: This email message and any attachments contain information that may be confidential and may be LEGALLY PRIVILEGED. If you are not the intended recipient, any use, disclosure or copying of this message or attachments is strictly prohibited. If you have received this email message in error please notify us immediately and erase all copies of the message and attachments. Thank you. 
==== 

답변

2

.

변경해보십시오 :

email_message = email.message_from_string(raw_email) 

에 자세한 정보를 들어

email_message = str(email.message_from_string(raw_email)).decode("quoted-printable") 

파이썬 코덱 모듈에서 Standard Encodings를 참조하십시오.

+0

감사합니다,하지만 ...'역 추적 (가장 최근 통화 최종) : 파일 "gmail5.py", 라인 (17), email_message에 = email.message_from_string (raw_email) .decode는 ("인용 -printable ") AttributeError : 메시지 인스턴스에 'decode'속성이 없습니다. @David K. Hess – Jay

+0

죄송합니다. 문자열을 생성한다고 생각했습니다. str() 캐스트를 사용해보십시오. 방금 대답했습니다. –

+0

완벽합니다. 고맙습니다. 꿈처럼 일했다. :) – Jay

0

하루에이 고통을 생각한 2 개의 추가 항목 만 있습니다. 1 페이로드 레벨에서 이메일을 처리하여 메일에서 이메일 주소 등을 얻을 수 있도록하십시오.

2 문자 집합도 디코딩해야합니다. 웹 페이지에서 HTML을 복사하여 붙여 넣는 사람들과 문제가 있었고 워드 문서 등의 콘텐츠를 처리하려고하는 이메일에 붙여 넣었습니다.

if maintype == 'multipart': 
        for part in email_message.get_payload(): 
          if part.get_content_type() == 'text/plain': 
           text += part.get_payload().decode("quoted-printable").decode(part.get_content_charset()) 

희망이 있으면 도움이 될 것입니다.

데이브