PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/poplib.py

https://bitbucket.org/kcr/pypy
Python | 417 lines | 354 code | 33 blank | 30 comment | 5 complexity | 386a471347b55897632b547eae55dfa7 MD5 | raw file
Possible License(s): Apache-2.0
  1. """A POP3 client class.
  2. Based on the J. Myers POP3 draft, Jan. 96
  3. """
  4. # Author: David Ascher <david_ascher@brown.edu>
  5. # [heavily stealing from nntplib.py]
  6. # Updated: Piers Lauder <piers@cs.su.oz.au> [Jul '97]
  7. # String method conversion and test jig improvements by ESR, February 2001.
  8. # Added the POP3_SSL class. Methods loosely based on IMAP_SSL. Hector Urtubia <urtubia@mrbook.org> Aug 2003
  9. # Example (see the test function at the end of this file)
  10. # Imports
  11. import re, socket
  12. __all__ = ["POP3","error_proto"]
  13. # Exception raised when an error or invalid response is received:
  14. class error_proto(Exception): pass
  15. # Standard Port
  16. POP3_PORT = 110
  17. # POP SSL PORT
  18. POP3_SSL_PORT = 995
  19. # Line terminators (we always output CRLF, but accept any of CRLF, LFCR, LF)
  20. CR = '\r'
  21. LF = '\n'
  22. CRLF = CR+LF
  23. class POP3:
  24. """This class supports both the minimal and optional command sets.
  25. Arguments can be strings or integers (where appropriate)
  26. (e.g.: retr(1) and retr('1') both work equally well.
  27. Minimal Command Set:
  28. USER name user(name)
  29. PASS string pass_(string)
  30. STAT stat()
  31. LIST [msg] list(msg = None)
  32. RETR msg retr(msg)
  33. DELE msg dele(msg)
  34. NOOP noop()
  35. RSET rset()
  36. QUIT quit()
  37. Optional Commands (some servers support these):
  38. RPOP name rpop(name)
  39. APOP name digest apop(name, digest)
  40. TOP msg n top(msg, n)
  41. UIDL [msg] uidl(msg = None)
  42. Raises one exception: 'error_proto'.
  43. Instantiate with:
  44. POP3(hostname, port=110)
  45. NB: the POP protocol locks the mailbox from user
  46. authorization until QUIT, so be sure to get in, suck
  47. the messages, and quit, each time you access the
  48. mailbox.
  49. POP is a line-based protocol, which means large mail
  50. messages consume lots of python cycles reading them
  51. line-by-line.
  52. If it's available on your mail server, use IMAP4
  53. instead, it doesn't suffer from the two problems
  54. above.
  55. """
  56. def __init__(self, host, port=POP3_PORT,
  57. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  58. self.host = host
  59. self.port = port
  60. self.sock = socket.create_connection((host, port), timeout)
  61. self.file = self.sock.makefile('rb')
  62. self._debugging = 0
  63. self.welcome = self._getresp()
  64. def _putline(self, line):
  65. if self._debugging > 1: print '*put*', repr(line)
  66. self.sock.sendall('%s%s' % (line, CRLF))
  67. # Internal: send one command to the server (through _putline())
  68. def _putcmd(self, line):
  69. if self._debugging: print '*cmd*', repr(line)
  70. self._putline(line)
  71. # Internal: return one line from the server, stripping CRLF.
  72. # This is where all the CPU time of this module is consumed.
  73. # Raise error_proto('-ERR EOF') if the connection is closed.
  74. def _getline(self):
  75. line = self.file.readline()
  76. if self._debugging > 1: print '*get*', repr(line)
  77. if not line: raise error_proto('-ERR EOF')
  78. octets = len(line)
  79. # server can send any combination of CR & LF
  80. # however, 'readline()' returns lines ending in LF
  81. # so only possibilities are ...LF, ...CRLF, CR...LF
  82. if line[-2:] == CRLF:
  83. return line[:-2], octets
  84. if line[0] == CR:
  85. return line[1:-1], octets
  86. return line[:-1], octets
  87. # Internal: get a response from the server.
  88. # Raise 'error_proto' if the response doesn't start with '+'.
  89. def _getresp(self):
  90. resp, o = self._getline()
  91. if self._debugging > 1: print '*resp*', repr(resp)
  92. c = resp[:1]
  93. if c != '+':
  94. raise error_proto(resp)
  95. return resp
  96. # Internal: get a response plus following text from the server.
  97. def _getlongresp(self):
  98. resp = self._getresp()
  99. list = []; octets = 0
  100. line, o = self._getline()
  101. while line != '.':
  102. if line[:2] == '..':
  103. o = o-1
  104. line = line[1:]
  105. octets = octets + o
  106. list.append(line)
  107. line, o = self._getline()
  108. return resp, list, octets
  109. # Internal: send a command and get the response
  110. def _shortcmd(self, line):
  111. self._putcmd(line)
  112. return self._getresp()
  113. # Internal: send a command and get the response plus following text
  114. def _longcmd(self, line):
  115. self._putcmd(line)
  116. return self._getlongresp()
  117. # These can be useful:
  118. def getwelcome(self):
  119. return self.welcome
  120. def set_debuglevel(self, level):
  121. self._debugging = level
  122. # Here are all the POP commands:
  123. def user(self, user):
  124. """Send user name, return response
  125. (should indicate password required).
  126. """
  127. return self._shortcmd('USER %s' % user)
  128. def pass_(self, pswd):
  129. """Send password, return response
  130. (response includes message count, mailbox size).
  131. NB: mailbox is locked by server from here to 'quit()'
  132. """
  133. return self._shortcmd('PASS %s' % pswd)
  134. def stat(self):
  135. """Get mailbox status.
  136. Result is tuple of 2 ints (message count, mailbox size)
  137. """
  138. retval = self._shortcmd('STAT')
  139. rets = retval.split()
  140. if self._debugging: print '*stat*', repr(rets)
  141. numMessages = int(rets[1])
  142. sizeMessages = int(rets[2])
  143. return (numMessages, sizeMessages)
  144. def list(self, which=None):
  145. """Request listing, return result.
  146. Result without a message number argument is in form
  147. ['response', ['mesg_num octets', ...], octets].
  148. Result when a message number argument is given is a
  149. single response: the "scan listing" for that message.
  150. """
  151. if which is not None:
  152. return self._shortcmd('LIST %s' % which)
  153. return self._longcmd('LIST')
  154. def retr(self, which):
  155. """Retrieve whole message number 'which'.
  156. Result is in form ['response', ['line', ...], octets].
  157. """
  158. return self._longcmd('RETR %s' % which)
  159. def dele(self, which):
  160. """Delete message number 'which'.
  161. Result is 'response'.
  162. """
  163. return self._shortcmd('DELE %s' % which)
  164. def noop(self):
  165. """Does nothing.
  166. One supposes the response indicates the server is alive.
  167. """
  168. return self._shortcmd('NOOP')
  169. def rset(self):
  170. """Unmark all messages marked for deletion."""
  171. return self._shortcmd('RSET')
  172. def quit(self):
  173. """Signoff: commit changes on server, unlock mailbox, close connection."""
  174. try:
  175. resp = self._shortcmd('QUIT')
  176. except error_proto, val:
  177. resp = val
  178. self.file.close()
  179. self.sock.close()
  180. del self.file, self.sock
  181. return resp
  182. #__del__ = quit
  183. # optional commands:
  184. def rpop(self, user):
  185. """Not sure what this does."""
  186. return self._shortcmd('RPOP %s' % user)
  187. timestamp = re.compile(r'\+OK.*(<[^>]+>)')
  188. def apop(self, user, secret):
  189. """Authorisation
  190. - only possible if server has supplied a timestamp in initial greeting.
  191. Args:
  192. user - mailbox user;
  193. secret - secret shared between client and server.
  194. NB: mailbox is locked by server from here to 'quit()'
  195. """
  196. m = self.timestamp.match(self.welcome)
  197. if not m:
  198. raise error_proto('-ERR APOP not supported by server')
  199. import hashlib
  200. digest = hashlib.md5(m.group(1)+secret).digest()
  201. digest = ''.join(map(lambda x:'%02x'%ord(x), digest))
  202. return self._shortcmd('APOP %s %s' % (user, digest))
  203. def top(self, which, howmuch):
  204. """Retrieve message header of message number 'which'
  205. and first 'howmuch' lines of message body.
  206. Result is in form ['response', ['line', ...], octets].
  207. """
  208. return self._longcmd('TOP %s %s' % (which, howmuch))
  209. def uidl(self, which=None):
  210. """Return message digest (unique id) list.
  211. If 'which', result contains unique id for that message
  212. in the form 'response mesgnum uid', otherwise result is
  213. the list ['response', ['mesgnum uid', ...], octets]
  214. """
  215. if which is not None:
  216. return self._shortcmd('UIDL %s' % which)
  217. return self._longcmd('UIDL')
  218. try:
  219. import ssl
  220. except ImportError:
  221. pass
  222. else:
  223. class POP3_SSL(POP3):
  224. """POP3 client class over SSL connection
  225. Instantiate with: POP3_SSL(hostname, port=995, keyfile=None, certfile=None)
  226. hostname - the hostname of the pop3 over ssl server
  227. port - port number
  228. keyfile - PEM formatted file that countains your private key
  229. certfile - PEM formatted certificate chain file
  230. See the methods of the parent class POP3 for more documentation.
  231. """
  232. def __init__(self, host, port = POP3_SSL_PORT, keyfile = None, certfile = None):
  233. self.host = host
  234. self.port = port
  235. self.keyfile = keyfile
  236. self.certfile = certfile
  237. self.buffer = ""
  238. msg = "getaddrinfo returns an empty list"
  239. self.sock = None
  240. for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
  241. af, socktype, proto, canonname, sa = res
  242. try:
  243. self.sock = socket.socket(af, socktype, proto)
  244. self.sock.connect(sa)
  245. except socket.error, msg:
  246. if self.sock:
  247. self.sock.close()
  248. self.sock = None
  249. continue
  250. break
  251. if not self.sock:
  252. raise socket.error, msg
  253. self.file = self.sock.makefile('rb')
  254. self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
  255. self._debugging = 0
  256. self.welcome = self._getresp()
  257. def _fillBuffer(self):
  258. localbuf = self.sslobj.read()
  259. if len(localbuf) == 0:
  260. raise error_proto('-ERR EOF')
  261. self.buffer += localbuf
  262. def _getline(self):
  263. line = ""
  264. renewline = re.compile(r'.*?\n')
  265. match = renewline.match(self.buffer)
  266. while not match:
  267. self._fillBuffer()
  268. match = renewline.match(self.buffer)
  269. line = match.group(0)
  270. self.buffer = renewline.sub('' ,self.buffer, 1)
  271. if self._debugging > 1: print '*get*', repr(line)
  272. octets = len(line)
  273. if line[-2:] == CRLF:
  274. return line[:-2], octets
  275. if line[0] == CR:
  276. return line[1:-1], octets
  277. return line[:-1], octets
  278. def _putline(self, line):
  279. if self._debugging > 1: print '*put*', repr(line)
  280. line += CRLF
  281. bytes = len(line)
  282. while bytes > 0:
  283. sent = self.sslobj.write(line)
  284. if sent == bytes:
  285. break # avoid copy
  286. line = line[sent:]
  287. bytes = bytes - sent
  288. def quit(self):
  289. """Signoff: commit changes on server, unlock mailbox, close connection."""
  290. try:
  291. resp = self._shortcmd('QUIT')
  292. except error_proto, val:
  293. resp = val
  294. self.sock.close()
  295. del self.sslobj, self.sock
  296. return resp
  297. __all__.append("POP3_SSL")
  298. if __name__ == "__main__":
  299. import sys
  300. a = POP3(sys.argv[1])
  301. print a.getwelcome()
  302. a.user(sys.argv[2])
  303. a.pass_(sys.argv[3])
  304. a.list()
  305. (numMsgs, totalSize) = a.stat()
  306. for i in range(1, numMsgs + 1):
  307. (header, msg, octets) = a.retr(i)
  308. print "Message %d:" % i
  309. for line in msg:
  310. print ' ' + line
  311. print '-----------------------'
  312. a.quit()