python解析邮件的时候编码问题

import sys
import base64
import os
import re

s1 = '"=?UTF-8?B?56mG6Zi/5rWpKOWnnOW8iyk=?=" <ahao.mah@ffff.com>, "=?UTF-8?B?56mG6Zi/5rWpKOWnnOW8iyk=?=" <ahao.mah@ffff.com>'
s2 = '"=?UTF-8?B?56mG6Zi/5rWpKOWnnOW8iyk=?=" <ahao.mah@ffff.com>'
s3 = "=?GBK?B?wfXWvrvUKLPLu8Yp?="
s4 = "hello"

def encoded_words_to_text(encoded_words):
    aa = ""
    bb = ""

    if "UTF-8" in encoded_words or "GBK" in encoded_words:
        list02 = encoded_words.split()
        for k in list02:
            if "UTF-8" in k or "GBK" in k:
                encoded_word_regex = r'=\?{1}(.+)\?{1}([B|Q])\?{1}(.+)\?{1}='
                k = k.strip("\"")
                charset, encoding, encoded_text = re.match(encoded_word_regex, k).groups()
                if encoding is 'B':
                    byte_string = base64.b64decode(encoded_text)
                elif encoding is 'Q':
                    byte_string = quopri.decodestring(encoded_text)
                aa = byte_string.decode(charset)
            else:
                bb = k

        cc = aa+' '+bb
        return cc
    else:
        return encoded_words


list01 = s4.split(",")
for i in list01:
    ff=encoded_words_to_text(i)
    print ff
posted @ 2018-01-15 16:45  苏小北1024  阅读(415)  评论(0编辑  收藏  举报