利用python进行unix管理一书中有一个登陆下载邮箱的脚本,实练了下还不错,对于邮箱备份来说还是比较快捷的,但是其命名方式是以编号和 文件大小来命名的,不方便阅读,于是进行了改进修改为发件人邮件地址命名,可能由于跨度时间较长,邮件排版有改变,有些邮件获取发件人的时候不能正确匹配。
1、命名方式是以编号和 文件大小来命名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/usr/bin/env python #-*- coding: utf-8 -*- #filename:receive_pop3_email_download.py import poplib username = 'dxx_study' passwd = 'xxxxxxxx' mail_server = 'pop.163.com' p = poplib.pop3(mail_server) p.user(username) p.pass_(passwd) for msg_id in p. list ()[ 1 ]: print msg_id outf = open ( '%s.eml' % msg_id, 'w' ) outf.write( '\n' .join(p.retr(msg_id)[ 1 ])) outf.close() p.quit() |
输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
>>> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = restart = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = >>> 1 6189 2 14284 3 1712 4 24912 5 129052 6 1399 7 23298 8 47902 9 2334 10 48887 11 1081 12 34930 13 2098 14 26316 15 32381 16 1822 |
2、发件人邮件地址命名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
#!/usr/bin/env python #-*- coding: utf-8 -*- #filename:receive_pop3_email.py import poplib, re username = 'dxx_study' passwd = 'xuxxxxxu' mail_server = 'pop.163.com' p = poplib.pop3(mail_server) #p.set_debuglevel(2)#设置调试信息打印级别 #s = p.getwelcome()#打印欢迎信息 p.user(username) p.pass_(passwd) p.stat() #p.list()#返回收件箱邮件数目,邮件大小,与p.list()[0]相同 #p.retr(42)#提取对应邮件的内容 #print p.top(42,42)#提取对应邮件,可以对内容按行数提取 #p.uidl()#return message digest (unique id) list #p.list()[1]#依次返回每个邮件大小,如['1 6189', '2 14284', '3 1712',....] #p.retr(2)[0]#返回第二封个邮件14284 octets大小 def file_name(text): #这个匹配效率比较低,值得改进 pattern = u "sender: (.*)" file_name = re.search(pattern, text, re.i) if file_name = = none: exit else : return file_name.group( 1 ) def download_mail(): for msg_id in p. list ()[ 1 ]: retr = p.retr(msg_id)[ 1 ] for i in range ( 0 , len (retr)): name = file_name(retr[i]) #利用filename进行正则匹配获取发件人 if name = = none: exit else : outf = open ( '%s.eml' % name, 'w' ) outf.write( '\n' .join(retr)) outf.close() download_mail() p.quit() |
以上功能对于备份邮件还是比较有用的,因为附件也下载下来了。由于pop3邮件服务比较过时了,服务也不够稳定,目前采用imap的比较流行,后面有空再写个支持后者的,能支持用户自己输入选择,提取各个邮件客户端的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/julius_lee/article/details/14003365