分类: Python/Ruby
2013-03-19 14:07:42
| 01 | #!/usr/bin/env python |
| 02 | #-*-coding = UTF-8-*- |
| 03 | #POP_email.py |
| 04 | #auth@:xfk |
| 05 | #date@:2012-04-30 |
| 06 | ################################################################ |
| 07 | # WARNING: This program deletes mail from the specified mailbox. |
| 08 | # Do Not point it to any mailbox you are care about! |
| 09 | ################################################################ |
| 10 |
| 11 | import getpass |
| 12 | import sys |
| 13 | import poplib |
| 14 | import email |
| 15 |
| 16 | if len(sys.argv) < 4: |
| 17 | print "[*]usage:%s server fromaddr toaddr " % sys.argv[0] |
| 18 | sys.exit(1) |
| 19 |
| 20 | (host,user,dest) = sys.argv[1:] |
| 21 | passwd = getpass.getpass() |
| 22 | destfd = open(dest,"at") |
| 23 |
| 24 | p = poplib.POP3(host) #如果服务器支持和需要APOP认证,APOP使用加密保护密码被窃取 |
| 25 | try: |
| 26 | print "Attempting APOP authentication..." |
| 27 | print "Logging on..." |
| 28 | p.apop(user,passwd) |
| 29 | print "Success.\n" |
| 30 | except poplib.error_proto: |
| 31 | print "Attempting standard authentication..." |
| 32 | try: |
| 33 | print "Logging on..." |
| 34 | p.user(user) |
| 35 | p.pass_(passwd) |
| 36 | print "Success.\n" |
| 37 | except poplib.error_proto,e: |
| 38 | print "Login fialed:",e |
| 39 | sys.exit(1) |
| 40 | print "*****Scanning INBOX...*****" #扫描服务器邮箱的邮件 |
| 41 | mail_box_list = p.list()[1] |
| 42 | print "There is %d messages.\n" % len(mail_box_list) |
| 43 |
| 44 | delelist = [] #要进行删除的又见队列 |
| 45 |
| 46 | for item in mail_box_list: |
| 47 | number,octets = item.split(' ') #每一个元素之间有空格隔开 |
| 48 | print "Downloading message %s (%s bytes)..." % (number,octets) |
| 49 | lines = p.retr(number)[1] #下载邮件 |
| 50 | msg = email.message_from_string("\n".join(lines)) #建立一个对象接受邮件内容 |
| 51 | destfd.write(msg.as_string(unixfrom = 1)) #讲邮件内容写进目标文件 |
| 52 | destfd.write("\n") |
| 53 | delelist.append(number) |
| 54 | print "Done !\n" |
| 55 | destfd.close() |
| 56 |
| 57 | counter = 0 |
| 58 | for number in delelist: |
| 59 | counter = counter + 1 |
| 60 | print "Deleting message %d of %d \r" % (counter,len(delelist)) |
| 61 | p.dele(number) #删除邮件 |
| 62 |
| 63 | if counter > 0: |
| 64 | print "Successfully deleted %d message from server.\n" % counter |
| 65 | else: |
| 66 | print "No messages present to download.\n" |
| 67 |
| 68 | print "Closing connection..." |
| 69 |
| 70 | p.quit() #断开连接 |
| 71 | print "Done !\n" |