2016-08-16 1 views
3

다음은 이메일 메시지의 HTML 부분을 얻기 위해 시도하는 방법입니다 :파이썬 2.7에서 메시지의 마임 부분을 디코딩하고 ** 유니 코드 ** 문자열을 얻는 방법은 무엇입니까?

from __future__ import absolute_import, division, unicode_literals, print_function 

import email 

html_mail_quoted_printable=b'''Subject: =?ISO-8859-1?Q?WG=3A_Wasenstra=DFe_84_in_32052_Hold_Stau?= 
MIME-Version: 1.0 
Content-type: multipart/mixed; 
Boundary="0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253" 

--0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253 
Content-type: multipart/alternative; 
Boundary="1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253" 

--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253 
Content-type: text/plain; charset=ISO-8859-1 
Content-transfer-encoding: quoted-printable 

Freundliche Gr=FC=DFe 

--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253 
Content-type: text/html; charset=ISO-8859-1 
Content-Disposition: inline 
Content-transfer-encoding: quoted-printable 

<html><body> 
Freundliche Gr=FC=DFe 
</body></html> 
--1__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253-- 

--0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253-- 

''' 
def get_html_part(msg): 
    for part in msg.walk(): 
     if part.get_content_type() == 'text/html': 
      return part.get_payload(decode=True) 

msg=email.message_from_string(html_mail_quoted_printable) 
html=get_html_part(msg) 
print(type(html)) 
print(html) 

출력 :

<type 'str'> 
<html><body> 
Freundliche Gr��e 
</body></html> 

불행하게도 내가 바이트 문자열을 얻을. 유니 코드 문자열을 갖고 싶습니다.

this answermsg.get_payload(decode=True)에 따르면 마술을해야합니다. 그러나이 경우에는 그렇지 않습니다.

메시지의 마임 부분을 디코딩하고 유니 코드 문자열을 파이썬 2.7로 가져 오는 방법은 무엇입니까?

답변

5

불행히도 나는 바이트 문자열을 얻습니다. 유니 코드 문자열을 갖고 싶습니다.

get_payloaddecode=True 매개 변수는 Content-Transfer-Encoding 랩퍼,이 메시지의 = -encoding를 디코딩한다. 거기에서 문자를 얻으려면 당신이 자신을 수행 email 패키지를 만드는 많은 것들 중 하나입니다 : (. iso-8859-1 메시지가 어떤 인코딩을 지정하는 경우에 대체되는)

bytes = part.get_payload(decode=True) 
charset = part.get_content_charset('iso-8859-1') 
chars = bytes.decode(charset, 'replace') 

관련 문제