2012-09-14 6 views
1

IMAP에서 읽지 않은 메시지를 가져 오려고합니다. 이메일 내용을 구문 분석하려고 할 때 len(email_message.keys()) == 0이됩니다. 그래서 나는 결코 From, To 그리고 Subject을 얻지 못합니다.메시지를 보낸 사람,받는 사람,받는 사람

인쇄 이메일 (email.message_from_string(email_str)) : 여기

From nobody Fri Sep 14 13:42:50 2012 

1 (RFC822 {1015} 
Return-Path: <[email protected]> 
X-Original-To: [email protected] 
Delivered-To: [email protected] 
Received: from ec2.....amazonaws.com (unknown [IP]) 
    (Authenticated sender: [email protected]) 
    by domain.com (Postfix) with ESMTPA id EACD436CF 
    for <[email protected]>; Fri, 14 Sep 2012 12:47:54 +0000 (UTC) 
DKIM-Signature: .... 
Content-Type: text/plain; charset="us-ascii" 
MIME-Version: 1.0 
Content-Transfer-Encoding: 7bit 
From: [email protected] 
To: [email protected] 
Subject: welcome 

Dear recipient, 

Welcome. 

Best, 
Robot 

그리고 코드입니다 :

def fetch_new_emails(host, port, user, password): 
    conn = imaplib.IMAP4(host=host, port=port) 

    try: 
    (retcode, capabilities) = conn.login(user, password) 
    conn.select(readonly=1) # Select inbox or default namespace 
    (retcode, messages) = conn.search(None, '(UNSEEN)') 
    results = [] 
    if retcode == 'OK': 
     for message in messages[0].split(' '): 
     (ret, raw_email) = conn.fetch(message, '(RFC822)') 
     if ret == 'OK': 
      print raw_email[0] 
      email_str = string.join(raw_email[0], "\n") 
      email_message = email.message_from_string(email_str) 
      email_from = email_message['From'] 
      to = email_message['To'] 
      subject = email_message['Subject'] 
      results.append({ 
      'from': email_from, 
      'to': to, 
      'subject': subject}) 
    except: 
    print sys.exc_info()[1] 
    sys.exit(1) 
    finally: 
    conn.close() 
    return results 

문제 :

print email_message['From'] 
>>None  
print email_message['To'] 
>>None 
print email_message['Subject'] 
>>None 
+0

raw_email 응답 만 출력 할 수 있습니까? – Max

답변

2

From nobody... 줄 뒤에 이상한 빈 줄이있다. 기술적으로 빈 줄은 헤더의 끝이고, 그 이후의 모든 것은 본문이므로 메시지에는 실제로 이러한 헤더가 없습니다.

어쨌든 IMAP 메시지에는 From 행이 없어야합니다. (이것은 IMAP 서버가 거의 사용하지 않는 Berkeley mbox 형식의 전형이며 사용자의 경우에도 저장소 구현에 대한 IMAP 클라이언트에 표시되지 않아야 함) .

이상한 1 (RFC822 {1015} 줄도 포함되지 않습니다. 그것은 실제 메시지의 일부가 아니라 IMAP 프로토콜 응답의 일부처럼 막연하게 보인다. 이 특별한 경우에는 메시지 본문이 Return-Path: 헤더로 시작됩니다.

IMAP 서버 및/또는 클라이언트 코드가 프로덕션 버전이 아닌가요?

+1

사실, 이것은 IMAP 프로토콜의 일부입니다 : "1 (RFC822 {1015}".) 실제로 imaplib가 FETCH로 줄 것입니다. 메시지 시퀀스 번호 1, RFC822 응답, 다음 1015 바이트. 다음 부분 응답의 실제 메시지입니다. – Max

관련 문제