poplib.py 14 KB

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