Advertisement
Guest User

Untitled

a guest
Sep 18th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. #! /usr/bin/python
  2.  
  3. import socket
  4. import sys
  5. import time
  6.  
  7. def readline(fd):
  8.     line = fd.readline()
  9.     if line == None:
  10.         raise EOFError()
  11.     #sys.stdout.write(line)
  12.     return line.rstrip() #remove trailing CRLF
  13.  
  14. def checkOK(fd):
  15.     line = readline(fd)
  16.     if line[0] == '-':
  17.         raise RuntimeError("server errored")
  18.  
  19. whitespace = " \t"
  20.  
  21. pop3_host = "pop3.shellmix.com"
  22. pop3_port = 110
  23. pop3_user = ""
  24. pop3_pass = ""
  25.  
  26. sock_fd = None
  27. fd = None
  28. try:
  29.     sock_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  30.     sock_fd.connect((pop3_host, pop3_port))
  31.     fd = sock_fd.makefile()
  32.     print("connected")
  33.     checkOK(fd)
  34.  
  35.     sock_fd.send("USER " + pop3_user + "\r\n")
  36.     checkOK(fd)
  37.  
  38.     sock_fd.send("PASS " + pop3_pass + "\r\n")
  39.     checkOK(fd)
  40.  
  41.     sock_fd.send("LIST\r\n")
  42.     checkOK(fd)
  43.     message_list = []
  44.     while True:
  45.         line = readline(fd)
  46.         if len(line) == 1 and line[0] == ".":
  47.             break
  48.         message_list.append(line.split(" ")[0])
  49.  
  50.     finished = False
  51.     for msg in message_list:
  52.         sock_fd.send("RETR " + msg + "\r\n")
  53.         checkOK(fd)
  54.         email_finished = False
  55.         #loop for email headers
  56.         while True:
  57.             line = readline(fd)
  58.             if len(line) == 1 and line[0] == ".":
  59.                 email_finished = True
  60.                 break
  61.             if len(line) == 0: #end of headers
  62.                 break
  63.             if whitespace.find(line[0]) != -1: #the first character is whitespace
  64.                 print("-> " + line.strip())
  65.             else:
  66.                 keyval = line.split(":")
  67.                 keyval[0] = keyval[0].strip()
  68.                 keyval[1] = keyval[1].strip()
  69.                 print("key=\"" + keyval[0] + "\" val=\"" + keyval[1] + "\"")
  70.  
  71.         #loop for email body
  72.         while not email_finished:
  73.             line = readline(fd)
  74.             if len(line) == 1 and line[0] == ".":
  75.                 break
  76.            
  77.  
  78.     sock_fd.send("QUIT\r\n")
  79.     checkOK(fd)
  80. finally:
  81.     time.sleep(1)
  82.     print("cleaning up")
  83.     if fd != None:
  84.         fd.close()
  85.         fd = None
  86.     if sock_fd != None:
  87.         sock_fd.shutdown(socket.SHUT_RDWR)
  88.         sock_fd.close()
  89.         sock_fd = None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement