Python网络编程基础笔记-MIME对象嵌套


               
               
                # -*- coding:cp936 -*-
#!/usr/bin/env python
"""
将一个MIME嵌套到另一个MIME中
1。先根据传入的参数类型创建相应的MIME对象;
2。调用attach方法将一个MIME追加到另一个MIME中;
"""
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Utils,Encoders
import mimetypes,sys
"""如果是text类型,则使用MIMEText;如果不是,则使用MIMEBase,并以base64进行编码"""
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
"""先使用类型判断函数进行判断,如果使用了编码或无法确定MIME类型,则使用octet-stream类型"""
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
"""
# 创建一HTML信息
messagehtml = """
Hell,
This is bold test messsage test.
---jcodeer
"""
# 创建一个MIME
msg = MIMEMultipart()
# 再创建一个MIME
body = MIMEMultipart("alternative")
body.attach(genpart(messagetext,"text/plain"))
body.attach(genpart(messagehtml,"text/html"))
# 将一个MIME(body)追加一另一个MIME(msg)
msg.attach(body)
# 再向MIME(msg)追加一个MIME。
msg.attach(attachment("JCNestedMIME.py"))
print msg.as_string()