Python网络编程基础笔记-解析email
1.解析email文件
# -*- coding: cp936 -*-
"""
解析email
1.item包含头信息内容(收件人,发件人,主题,日期和信息ID)
2.get_payload得到email内容
3.获取时间
"""
import sys,email
from email import Utils
import time
fd = file("jcodeer.email")
msg = email.message_from_file(fd)
fd.close()
print "email头信息"
for header,value in msg.items():
print header + ":"
print " " + value
if msg.is_multipart():
print "This is program cannot handle MIME multipart messages;exiting."
sys.exit(1)
"""将时间戳转化为时间字符串"""
if "date" in msg:
datehdr = msg["date"].strip()
dateval = Utils.mktime_tz(Utils.parsedate_tz(datehdr))
print "信息发送时间:",time.strftime("%A,%B %d %Y at %I:%M %p",time.localtime(dateval))
print "-" * 78
if "subject" in msg:
print "主题:",msg["subject"]
print "-" * 78
print "信息内容:"
print msg.get_payload()
2.jcodeer.email文件
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
To: jcodeer@sina.com
From: Python jcodeer@126.com>
Subject: composing a email
Date: Thu, 08 Nov 2007 22:45:16 +0800
Message-ID: 20071108144516.4828.96976@wanpor>
Composing a email.
---jcodeer