poplib.py 13 KB

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