poplib.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 errno
  12. import re
  13. import socket
  14. try:
  15. import ssl
  16. HAVE_SSL = True
  17. except ImportError:
  18. HAVE_SSL = False
  19. __all__ = ["POP3","error_proto"]
  20. # Exception raised when an error or invalid response is received:
  21. class error_proto(Exception): pass
  22. # Standard Port
  23. POP3_PORT = 110
  24. # POP SSL PORT
  25. POP3_SSL_PORT = 995
  26. # Line terminators (we always output CRLF, but accept any of CRLF, LFCR, LF)
  27. CR = b'\r'
  28. LF = b'\n'
  29. CRLF = CR+LF
  30. # maximal line length when calling readline(). This is to prevent
  31. # reading arbitrary length lines. RFC 1939 limits POP3 line length to
  32. # 512 characters, including CRLF. We have selected 2048 just to be on
  33. # the safe side.
  34. _MAXLINE = 2048
  35. class POP3:
  36. """This class supports both the minimal and optional command sets.
  37. Arguments can be strings or integers (where appropriate)
  38. (e.g.: retr(1) and retr('1') both work equally well.
  39. Minimal Command Set:
  40. USER name user(name)
  41. PASS string pass_(string)
  42. STAT stat()
  43. LIST [msg] list(msg = None)
  44. RETR msg retr(msg)
  45. DELE msg dele(msg)
  46. NOOP noop()
  47. RSET rset()
  48. QUIT quit()
  49. Optional Commands (some servers support these):
  50. RPOP name rpop(name)
  51. APOP name digest apop(name, digest)
  52. TOP msg n top(msg, n)
  53. UIDL [msg] uidl(msg = None)
  54. CAPA capa()
  55. STLS stls()
  56. UTF8 utf8()
  57. Raises one exception: 'error_proto'.
  58. Instantiate with:
  59. POP3(hostname, port=110)
  60. NB: the POP protocol locks the mailbox from user
  61. authorization until QUIT, so be sure to get in, suck
  62. the messages, and quit, each time you access the
  63. mailbox.
  64. POP is a line-based protocol, which means large mail
  65. messages consume lots of python cycles reading them
  66. line-by-line.
  67. If it's available on your mail server, use IMAP4
  68. instead, it doesn't suffer from the two problems
  69. above.
  70. """
  71. encoding = 'UTF-8'
  72. def __init__(self, host, port=POP3_PORT,
  73. timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  74. self.host = host
  75. self.port = port
  76. self._tls_established = False
  77. self.sock = self._create_socket(timeout)
  78. self.file = self.sock.makefile('rb')
  79. self._debugging = 0
  80. self.welcome = self._getresp()
  81. def _create_socket(self, timeout):
  82. return socket.create_connection((self.host, self.port), timeout)
  83. def _putline(self, line):
  84. if self._debugging > 1: print('*put*', repr(line))
  85. self.sock.sendall(line + CRLF)
  86. # Internal: send one command to the server (through _putline())
  87. def _putcmd(self, line):
  88. if self._debugging: print('*cmd*', repr(line))
  89. line = bytes(line, self.encoding)
  90. self._putline(line)
  91. # Internal: return one line from the server, stripping CRLF.
  92. # This is where all the CPU time of this module is consumed.
  93. # Raise error_proto('-ERR EOF') if the connection is closed.
  94. def _getline(self):
  95. line = self.file.readline(_MAXLINE + 1)
  96. if len(line) > _MAXLINE:
  97. raise error_proto('line too long')
  98. if self._debugging > 1: print('*get*', repr(line))
  99. if not line: raise error_proto('-ERR EOF')
  100. octets = len(line)
  101. # server can send any combination of CR & LF
  102. # however, 'readline()' returns lines ending in LF
  103. # so only possibilities are ...LF, ...CRLF, CR...LF
  104. if line[-2:] == CRLF:
  105. return line[:-2], octets
  106. if line[:1] == CR:
  107. return line[1:-1], octets
  108. return line[:-1], octets
  109. # Internal: get a response from the server.
  110. # Raise 'error_proto' if the response doesn't start with '+'.
  111. def _getresp(self):
  112. resp, o = self._getline()
  113. if self._debugging > 1: print('*resp*', repr(resp))
  114. if not resp.startswith(b'+'):
  115. raise error_proto(resp)
  116. return resp
  117. # Internal: get a response plus following text from the server.
  118. def _getlongresp(self):
  119. resp = self._getresp()
  120. list = []; octets = 0
  121. line, o = self._getline()
  122. while line != b'.':
  123. if line.startswith(b'..'):
  124. o = o-1
  125. line = line[1:]
  126. octets = octets + o
  127. list.append(line)
  128. line, o = self._getline()
  129. return resp, list, octets
  130. # Internal: send a command and get the response
  131. def _shortcmd(self, line):
  132. self._putcmd(line)
  133. return self._getresp()
  134. # Internal: send a command and get the response plus following text
  135. def _longcmd(self, line):
  136. self._putcmd(line)
  137. return self._getlongresp()
  138. # These can be useful:
  139. def getwelcome(self):
  140. return self.welcome
  141. def set_debuglevel(self, level):
  142. self._debugging = level
  143. # Here are all the POP commands:
  144. def user(self, user):
  145. """Send user name, return response
  146. (should indicate password required).
  147. """
  148. return self._shortcmd('USER %s' % user)
  149. def pass_(self, pswd):
  150. """Send password, return response
  151. (response includes message count, mailbox size).
  152. NB: mailbox is locked by server from here to 'quit()'
  153. """
  154. return self._shortcmd('PASS %s' % pswd)
  155. def stat(self):
  156. """Get mailbox status.
  157. Result is tuple of 2 ints (message count, mailbox size)
  158. """
  159. retval = self._shortcmd('STAT')
  160. rets = retval.split()
  161. if self._debugging: print('*stat*', repr(rets))
  162. numMessages = int(rets[1])
  163. sizeMessages = int(rets[2])
  164. return (numMessages, sizeMessages)
  165. def list(self, which=None):
  166. """Request listing, return result.
  167. Result without a message number argument is in form
  168. ['response', ['mesg_num octets', ...], octets].
  169. Result when a message number argument is given is a
  170. single response: the "scan listing" for that message.
  171. """
  172. if which is not None:
  173. return self._shortcmd('LIST %s' % which)
  174. return self._longcmd('LIST')
  175. def retr(self, which):
  176. """Retrieve whole message number 'which'.
  177. Result is in form ['response', ['line', ...], octets].
  178. """
  179. return self._longcmd('RETR %s' % which)
  180. def dele(self, which):
  181. """Delete message number 'which'.
  182. Result is 'response'.
  183. """
  184. return self._shortcmd('DELE %s' % which)
  185. def noop(self):
  186. """Does nothing.
  187. One supposes the response indicates the server is alive.
  188. """
  189. return self._shortcmd('NOOP')
  190. def rset(self):
  191. """Unmark all messages marked for deletion."""
  192. return self._shortcmd('RSET')
  193. def quit(self):
  194. """Signoff: commit changes on server, unlock mailbox, close connection."""
  195. resp = self._shortcmd('QUIT')
  196. self.close()
  197. return resp
  198. def close(self):
  199. """Close the connection without assuming anything about it."""
  200. try:
  201. file = self.file
  202. self.file = None
  203. if file is not None:
  204. file.close()
  205. finally:
  206. sock = self.sock
  207. self.sock = None
  208. if sock is not None:
  209. try:
  210. sock.shutdown(socket.SHUT_RDWR)
  211. except OSError as e:
  212. # The server might already have closed the connection
  213. if e.errno != errno.ENOTCONN:
  214. raise
  215. finally:
  216. sock.close()
  217. #__del__ = quit
  218. # optional commands:
  219. def rpop(self, user):
  220. """Not sure what this does."""
  221. return self._shortcmd('RPOP %s' % user)
  222. timestamp = re.compile(br'\+OK.*(<[^>]+>)')
  223. def apop(self, user, password):
  224. """Authorisation
  225. - only possible if server has supplied a timestamp in initial greeting.
  226. Args:
  227. user - mailbox user;
  228. password - mailbox password.
  229. NB: mailbox is locked by server from here to 'quit()'
  230. """
  231. secret = bytes(password, self.encoding)
  232. m = self.timestamp.match(self.welcome)
  233. if not m:
  234. raise error_proto('-ERR APOP not supported by server')
  235. import hashlib
  236. digest = m.group(1)+secret
  237. digest = hashlib.md5(digest).hexdigest()
  238. return self._shortcmd('APOP %s %s' % (user, digest))
  239. def top(self, which, howmuch):
  240. """Retrieve message header of message number 'which'
  241. and first 'howmuch' lines of message body.
  242. Result is in form ['response', ['line', ...], octets].
  243. """
  244. return self._longcmd('TOP %s %s' % (which, howmuch))
  245. def uidl(self, which=None):
  246. """Return message digest (unique id) list.
  247. If 'which', result contains unique id for that message
  248. in the form 'response mesgnum uid', otherwise result is
  249. the list ['response', ['mesgnum uid', ...], octets]
  250. """
  251. if which is not None:
  252. return self._shortcmd('UIDL %s' % which)
  253. return self._longcmd('UIDL')
  254. def utf8(self):
  255. """Try to enter UTF-8 mode (see RFC 6856). Returns server response.
  256. """
  257. return self._shortcmd('UTF8')
  258. def capa(self):
  259. """Return server capabilities (RFC 2449) as a dictionary
  260. >>> c=poplib.POP3('localhost')
  261. >>> c.capa()
  262. {'IMPLEMENTATION': ['Cyrus', 'POP3', 'server', 'v2.2.12'],
  263. 'TOP': [], 'LOGIN-DELAY': ['0'], 'AUTH-RESP-CODE': [],
  264. 'EXPIRE': ['NEVER'], 'USER': [], 'STLS': [], 'PIPELINING': [],
  265. 'UIDL': [], 'RESP-CODES': []}
  266. >>>
  267. Really, according to RFC 2449, the cyrus folks should avoid
  268. having the implementation split into multiple arguments...
  269. """
  270. def _parsecap(line):
  271. lst = line.decode('ascii').split()
  272. return lst[0], lst[1:]
  273. caps = {}
  274. try:
  275. resp = self._longcmd('CAPA')
  276. rawcaps = resp[1]
  277. for capline in rawcaps:
  278. capnm, capargs = _parsecap(capline)
  279. caps[capnm] = capargs
  280. except error_proto as _err:
  281. raise error_proto('-ERR CAPA not supported by server')
  282. return caps
  283. def stls(self, context=None):
  284. """Start a TLS session on the active connection as specified in RFC 2595.
  285. context - a ssl.SSLContext
  286. """
  287. if not HAVE_SSL:
  288. raise error_proto('-ERR TLS support missing')
  289. if self._tls_established:
  290. raise error_proto('-ERR TLS session already established')
  291. caps = self.capa()
  292. if not 'STLS' in caps:
  293. raise error_proto('-ERR STLS not supported by server')
  294. if context is None:
  295. context = ssl._create_stdlib_context()
  296. resp = self._shortcmd('STLS')
  297. self.sock = context.wrap_socket(self.sock,
  298. server_hostname=self.host)
  299. self.file = self.sock.makefile('rb')
  300. self._tls_established = True
  301. return resp
  302. if HAVE_SSL:
  303. class POP3_SSL(POP3):
  304. """POP3 client class over SSL connection
  305. Instantiate with: POP3_SSL(hostname, port=995, keyfile=None, certfile=None,
  306. context=None)
  307. hostname - the hostname of the pop3 over ssl server
  308. port - port number
  309. keyfile - PEM formatted file that contains your private key
  310. certfile - PEM formatted certificate chain file
  311. context - a ssl.SSLContext
  312. See the methods of the parent class POP3 for more documentation.
  313. """
  314. def __init__(self, host, port=POP3_SSL_PORT, keyfile=None, certfile=None,
  315. timeout=socket._GLOBAL_DEFAULT_TIMEOUT, context=None):
  316. if context is not None and keyfile is not None:
  317. raise ValueError("context and keyfile arguments are mutually "
  318. "exclusive")
  319. if context is not None and certfile is not None:
  320. raise ValueError("context and certfile arguments are mutually "
  321. "exclusive")
  322. self.keyfile = keyfile
  323. self.certfile = certfile
  324. if context is None:
  325. context = ssl._create_stdlib_context(certfile=certfile,
  326. keyfile=keyfile)
  327. self.context = context
  328. POP3.__init__(self, host, port, timeout)
  329. def _create_socket(self, timeout):
  330. sock = POP3._create_socket(self, timeout)
  331. sock = self.context.wrap_socket(sock,
  332. server_hostname=self.host)
  333. return sock
  334. def stls(self, keyfile=None, certfile=None, context=None):
  335. """The method unconditionally raises an exception since the
  336. STLS command doesn't make any sense on an already established
  337. SSL/TLS session.
  338. """
  339. raise error_proto('-ERR TLS session already established')
  340. __all__.append("POP3_SSL")
  341. if __name__ == "__main__":
  342. import sys
  343. a = POP3(sys.argv[1])
  344. print(a.getwelcome())
  345. a.user(sys.argv[2])
  346. a.pass_(sys.argv[3])
  347. a.list()
  348. (numMsgs, totalSize) = a.stat()
  349. for i in range(1, numMsgs + 1):
  350. (header, msg, octets) = a.retr(i)
  351. print("Message %d:" % i)
  352. for line in msg:
  353. print(' ' + line)
  354. print('-----------------------')
  355. a.quit()