文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Python网络编程基础笔记-信息头编码与解码

Python网络编程基础笔记-信息头编码与解码

时间:2007-11-14  来源:jcodeer

1.对信息头进行编码和解码

# -*- coding:cp936 -*-
#!/usr/bin/env python
"""
对信息头进行编码和解码操作
"""
import sys,email,codecs
from email import Header

msg = email.message_from_file(file("JCParseMIME.email"))
for header,value in msg.items():
    headerparts = Header.decode_header(value)
    headval = []
    for part in headerparts:
        data,charset = part
    if charset is None:
        charset = "ascii"
    dec = codecs.getdecoder(charset)
    enc = codecs.getencoder("iso-8859-1")
    data = enc(dec(data)[0])[0]
    headval.append(data)
    print("%s:%s"%(header,"".join(headval)))

2.email内容
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,<P>
This is <B>bold</B> test messsage test.
<P>
---<I>jcodeer</I>

--===============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,<P>
This is <B>bold</B> test messsage test.
<P>
---<I>jcodeer</I>
"""

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==--
相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载