python之POP详解

fmms 12年前

这段代码的功能:

  1. 解析邮件
  2. 下载邮件
  3. 扫描邮件服务器
  4. 查看邮件服务器是否支持APOP传输,对传输数据进行加密
  5. 下载邮件到本地并删除

#!/usr/bin/env python  #-*-coding = UTF-8-*-  #POP_email.py  #auth@:xfk  #date@:2012-04-30  ################################################################  # WARNING: This program deletes mail from the specified mailbox.  #           Do Not point it to any mailbox you are care about!  ################################################################    import getpass  import sys  import poplib  import email    if len(sys.argv) < 4:      print "[*]usage:%s server fromaddr toaddr " % sys.argv[0]      sys.exit(1)    (host,user,dest) = sys.argv[1:]  passwd = getpass.getpass()  destfd = open(dest,"at")        p = poplib.POP3(host)           #如果服务器支持和需要APOP认证,APOP使用加密保护密码被窃取  try:      print "Attempting APOP authentication..."      print "Logging on..."      p.apop(user,passwd)      print "Success.\n"  except poplib.error_proto:      print "Attempting standard authentication..."      try:          print "Logging on..."          p.user(user)          p.pass_(passwd)          print "Success.\n"      except poplib.error_proto,e:          print "Login fialed:",e          sys.exit(1)  print "*****Scanning INBOX...*****"         #扫描服务器邮箱的邮件  mail_box_list = p.list()[1]  print "There is %d messages.\n" % len(mail_box_list)    delelist = []           #要进行删除的又见队列    for item in mail_box_list:      number,octets = item.split(' ')         #每一个元素之间有空格隔开      print "Downloading message %s (%s bytes)..." % (number,octets)      lines = p.retr(number)[1]           #下载邮件      msg = email.message_from_string("\n".join(lines))           #建立一个对象接受邮件内容      destfd.write(msg.as_string(unixfrom = 1))           #讲邮件内容写进目标文件      destfd.write("\n")      delelist.append(number)      print "Done !\n"  destfd.close()    counter = 0  for number in delelist:      counter = counter + 1      print "Deleting message %d of %d \r" % (counter,len(delelist))      p.dele(number)          #删除邮件    if counter > 0:      print "Successfully deleted %d message from server.\n" % counter  else:      print "No messages present to download.\n"    print "Closing connection..."    p.quit()            #断开连接  print "Done !\n"