Python网络编程基础笔记-对MIME编码后的内容进行解码处理

1.对MIME的编码后的内容进行解码。
               
               
                # -*- coding:cp936 -*-
#!/usr/bin/env python
import sys,email
counter = 0
parts = []
def printmsg(msg,level = 0):
    global counter
    l = "| " * level
    ls = l + "*"
    l2 = l + "|"
    if msg.is_multipart():
        print (l + "Found multipart")
        for item in msg.get_payload():
            # 如果还是MIME类型,则进行递归调用
            printmsg(item,level + 1)
    else:
        disp = ["%d.Decodable part" % (counter + 1)]
        # 获取类型信息
        if "content-type" in msg:
            disp.append(msg["content-type"])
        if "content-disposition" in msg:
            disp.append(msg["content-disposition"])
        print l + ",".join(disp)
        counter += 1
        parts.append(msg)
        
fd = file("JCParseMIME.email")
msg = email.message_from_file(fd)
printmsg(msg)
while 1:
    print("Select part number to decoder or q to quit")
    part = sys.stdin.readline().strip()
    if part == "q":
        sys.exit(1)
    try:
        part = int(part)
        msg = parts[part - 1]
    except:
        print("invalid selection")
        continue
   
    print("select file to write to")
    filename = sys.stdin.readline().strip()
    try:
        fd = open(filename,"wb")
    except:
        print("invalid name")
        continue
    # 使用指定的编码写入文件
    fd.write(msg.get_payload(decode = 1))
   
        
2.测试文件
Content-Type: multipart/mixed; boundary="===============0874728357=="
MIME-Version: 1.0
--===============0874728357==
Content-Type: multipart/alternative; boundary="===============1169888608=="
MIME-Version: 1.0
--===============1169888608==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Hello,This is nested message test.
---jcodeer
--===============1169888608==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Hell,
This is bold test messsage test.
---jcodeer
--===============1169888608==--
--===============0874728357==
Content-Type: text/x-python; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attach; filename="JCNestedMIME.py"
# -*- coding:cp936 -*-
#!/usr/bin/env python
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Utils,Encoders
import mimetypes,sys
def genpart(data,contenttype):
    maintype,subtype = contenttype.split("/")
    if maintype == "text":
        retval = MIMEText(data,_subtype = subtype)
    else:
        retval = MIMEBase(maintype,subtype)
        retval.set_payload(data)
        Encoders.encode_base64(retval)
    return retval
def attachment(filename):
    fd = file(filename,"rb")
    mimetype,mimeencoding = mimetypes.guess_type(filename)
    if mimeencoding or (mimetype is None):
        mimetype = "application/octet-stream"
    retval = genpart(fd.read(),mimetype)
    retval.add_header("Content-Disposition","attach",filename = filename)
    fd.close()
    return retval
messagetext = """
Hello,This is nested message test.
---jcodeer
"""
messagehtml = """
Hell,
This is bold test messsage test.
---jcodeer
"""
msg = MIMEMultipart()
body = MIMEMultipart("alternative")
body.attach(genpart(messagetext,"text/plain"))
body.attach(genpart(messagehtml,"text/html"))
msg.attach(body)
msg.attach(attachment("JCNestedMIME.py"))
print msg.as_string()
--===============0874728357==--
3.测试结果
分别输入
1
2.txt
文本2.txt的内容如下:
Hello,This is nested message test.
---jcodeer