2016-08-16 3 views
3

は、電子メールメッセージのHTML部分を取得しようとする方法である:メッセージのMIME部分をデコードしてPython 2.7で** unicode **文字列を取得する方法は?ここ

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)によれば、魔法を行うべきです。しかし、この場合はありません。

メッセージのMIME部分をデコードして、ユニコードの文字列をPython 2.7で取得するにはどうすればよいですか?

答えて

5

残念ながら、私はバイト文字列を取得します。私はユニコード文字列を持っていたいと思います。 get_payload

decode=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') 

関連する問題