python开发_email_读取邮件头信息

python中的类库中,python自带了email模块。

email模块中,我们可以email类库实现对邮件的读取,和邮件的发送等功能。

本文先来谈谈在python中,利用email模块读取邮件头.....

先来看看一封百度云发给我的邮件:

下面是邮件的具体信息:

Date: Tue, 30 Jul 2013 16:53:17 +0800
Received: from db-sysnoc-mailrelay3.db01.baidu (unknown [123.125.66.194])
    by newmx38.qq.com (NewMx) with SMTP id 
    for <hongtenzone@foxmail.com>; Tue, 30 Jul 2013 16:53:16 +0800
X-QQ-SSF: 00500000010000010rF000C1040000r
X-QQ-mid: mx38t1375174396thkz17254
Received: from mail-out.sys.baidu.com (cq01-passport-mis00.cq01.baidu.com [10.46.78.11])
    by db-sysnoc-mailrelay3.db01.baidu.com (Postfix) with SMTP id 515EF798060
    for <hongtenzone@foxmail.com>; Tue, 30 Jul 2013 16:53:16 +0800 (CST)
From: =?UTF-8?B?YmFpZHU=?=<passport@baidu.com>
To: =?UTF-8?B?aG9uZ3RlbnpvbmVAZm94bWFpbC5jb20=?=<hongtenzone@foxmail.com>
Subject: =?UTF-8?B?55m+5bqm5LqR6YCB5L2gMTAwR+WtmOWCqOepuumXtOmAmuefpQ==?=
MIME-Version: 1.0
Content-Type: text/html;
    charset="UTF-8"
Content-Transfer-Encoding: base64

PFA+PEEgaHJlZj0iaHR0cDovL3l1bi5iYWlkdS5jb20vMTAwPz1tYWlsMiI+PElNRyBzdHlsZT0i
RElTUExBWTogYmxvY2s7IE1BUkdJTi1MRUZUOiBhdXRvOyBNQVJHSU4tUklHSFQ6IGF1dG8iIHNy
Yz0iaHR0cDovL3Bhbi5iYWlkdS5jb20vcmVzL3N0YXRpYy9pbWFnZXMvY21zL3dvcmxkLTEwMC5q
cGciPjwvQT48Rk9OVCBmYWNlPeW5vOWchj48Rk9OVCBjb2xvcj0jZmYwMDAwIHNpemU9Mz48Rk9O
VCBjb2xvcj0jMDAwMDAwPkhvbmdfdGVuX3pvbmXvvIzmgqjnmoTnmb7luqbkupHlrrnph488Rk9O
VCBjb2xvcj0jZmYwMDAwPjxTVFJPTkc+5Y2z5bCG5Yiw5pyfPC9TVFJPTkc+PC9GT05UPu+8jOiv
t+WwveW/q+e7reacn++8jOS7peWFjeW9seWTjeaCqOWkh+S7veWunei0teaVsOaNruOAgjxTVFJP
Tkc+PEZPTlQgY29sb3I9I2ZmMDAwMD4xMDBH57ut5pyf5Y+q6ZyAMC4y5YWD77yM5Y+y5LiK5pyA
5L2O5Lu3PC9GT05UPjwvU1RST05HPu+8jOa0u+WKqOWcsOWdgO+8mjwvRk9OVD48L0ZPTlQ+PEZP
TlQgY29sb3I9I2ZmMDAwMCBzaXplPTM+PEEgaHJlZj0iaHR0cDovL3l1bi5iYWlkdS5jb20vMTAw
Pz1tYWlsMiI+aHR0cDovL3l1bi5iYWlkdS5jb20vMTAwPC9BPjwvQT48L0ZPTlQ+PC9GT05UPjxG
T05UIHNpemU9Mz48Rk9OVCBjb2xvcj0jZmYwMDAwPiA8L0ZPTlQ+PC9GT05UPjwvUD4NPGJyPjxQ
PjxGT05UIHNpemU9Mj48Rk9OVCBzdHlsZT0iQkFDS0dST1VORC1DT0xPUjogI2ZmZmYwMCIgY29s
b3I9I2ZmMDAwMCBmYWNlPeWui+S9kz7vvIjmnKzkvJjmg6Dnu63mnJ/kuLrmgqjkuJPkuqvnibnm
nYPvvIzor7fli7/ovazlj5HjgIHlpJbms4TvvIzosKLosKLmlK/mjIHvvIHvvIk8L0ZPTlQ+PC9G
T05UPjwvUD4=

下面是我做的demo:

运行效果:

===========================================

代码部分:

===========================================

  1 #python mail
  2 
  3 import os
  4 import email
  5 
  6 #邮件文件的存放位置
  7 PATH = ''
  8 
  9 #读取文件
 10 def read_mail(path):
 11     if os.path.exists(path):
 12         with open(path) as fp:
 13             for line in fp:
 14                 print(line)
 15     else:
 16         not_find_file()
 17 
 18 #打开一个文件   
 19 def open_file(path):
 20     if os.path.exists(path):
 21         return open(path, 'r')
 22     else:
 23         not_find_file()
 24 
 25 #创建消息对象
 26 def get_message(path):
 27     if os.path.exists(path):
 28         fp = open_file(path)
 29         return email.message_from_file(fp)
 30     else:
 31        not_find_file()
 32 
 33 #获取subject对象
 34 def get_subject(path):
 35     if os.path.exists(path):
 36         message = get_message(path)
 37         return message.get('subject')
 38     else:
 39         not_find_file()
 40 
 41 #解析subject对象
 42 def parse_subject(msg):
 43     if msg != None:
 44         subject = msg.get('subject')
 45         #header = email.Header.Header(subject)
 46         #decode_h = email.Header.decode_header(header)
 47         #return decode_h[0][0]
 48     else:
 49         empty_obj()
 50 
 51 #获取发件人邮箱   
 52 def get_from(msg):
 53     if msg != None:
 54         return email.utils.parseaddr(msg.get("from"))[1]
 55     else:
 56         empty_obj()
 57 
 58 #获取收件人邮箱
 59 def get_to(msg):
 60     if msg != None:
 61         return email.utils.parseaddr(msg.get('to'))[1]
 62     else:
 63         empty_obj()
 64 
 65 
 66 #获取邮件的生成时间
 67 def get_date(msg):
 68     if msg != None:
 69         return email.utils.parseaddr(msg.get('date'))[1]
 70     else:
 71         empty_obj()
 72 
 73 #获取邮件的生成版本
 74 def get_mime_version(msg):
 75     if msg != None:
 76         return email.utils.parseaddr(msg.get('mime-version'))[1]
 77     else:
 78         empty_obj()
 79 
 80 #获取邮件的文本类型
 81 def get_content_type(msg):
 82     if msg != None:
 83         return email.utils.parseaddr(msg.get('content-type'))[1]
 84     else:
 85         empty_obj()
 86 
 87 #获取邮件的邮件的id
 88 def get_message_id(msg):
 89     if msg != None:
 90         return email.utils.parseaddr(msg.get('message-id'))[1]
 91     else:
 92         empty_obj()
 93 
 94 
 95 #文件不存在
 96 def not_find_file():
 97     print('文件不存在!')
 98 
 99 #msg is empty
100 def empty_obj():
101     print('msg is empty!')
102     
103 def main():
104     global PATH
105     PATH = 'E:\\test_mail.eml'
106     print(PATH)
107     msg = get_message(PATH)
108     #print(msg)
109     print('#' * 50)
110     print('subject:{}'.format(get_subject(PATH)))
111     print('#' * 50)
112     print(parse_subject(msg))
113     print('#' * 50)
114     print('from:{}'.format(get_from(msg)))
115     print('to:{}'.format(get_to(msg)))
116     print('date:{}'.format(get_date(msg)))
117     print('mime-version:{}'.format(get_mime_version(msg)))
118     print('content-type:{}'.format(get_content_type(msg)))
119     print('message-id:{}'.format(get_message_id(msg)))
120 
121 if __name__ == '__main__':
122     main()
123     

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏跟着阿笨一起玩NET

【译】在ASP.Net和IIS中删除不必要的HTTP响应头

   每次当浏览器向Web服务器发起一个请求的时,都会伴随着一些HTTP头的发送.而这些HTTP头是用于给Web服务器提供一些额外信息以便于处理请求。比如说吧。...

1751
来自专栏我的小碗汤

Web应用测试最佳工具Burp Suite

Burp Suite是Web应用程序测试的最佳工具之一,可以对请求的数据包进行拦截和修改,扫描常见的web安全漏洞,暴力破解登录表单、遍历数据等等。

1162
来自专栏V站

VIM不正常退出产生的swp文件将泄漏敏感信息

原理可参考此文章:https://blog.csdn.net/pwiling/article/details/51830781

3322
来自专栏喵了个咪的博客空间

原 荐 EMQ百万级MQTT消息服务(小技巧)

附上: 喵了个咪的博客:w-blog.cn EMQ官方地址:http://emqtt.com/ EMQ中文文档:http://emqtt.com/docs/v2...

4614
来自专栏禅林阆苑

利用NextCloud配置私有云 【原创】

利用NextCloud配置私有云 Write By CS逍遥剑仙 我的主页: www.csxiaoyao.com GitHub: github...

2K8
来自专栏小李刀刀的专栏

再战子域共享Cookie问题

昨天贾宁旨光临寒舍,吃过晚饭回来后就跟他聊天,后来又玩了一会儿《Black Hawk Down》对战,到了大概晚上11点多,开始继续尝试用 Response.C...

4845
来自专栏IT技术精选文摘

EMQ百万级MQTT消息服务

5114
来自专栏恰童鞋骚年

.NET Core微服务之基于Consul实现服务治理(续)

上一篇发布之后,很多人点赞和评论,不胜惶恐,这一篇把上一篇没有弄到的东西补一下,也算是给各位前来询问的朋友的一些回复吧。

1605
来自专栏张高兴的博客

张高兴的 UWP 开发笔记:应用内启动应用 (UWP Launch UWP)

3589
来自专栏安全领域

物联网 MQTT 服务质量级别

原文地址:https://dzone.com/articles/internet-things-mqtt-quality

6397

扫码关注云+社区

领取腾讯云代金券