PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/imaplib.py

http://github.com/JetBrains/intellij-community
Python | 1499 lines | 1436 code | 26 blank | 37 comment | 14 complexity | c27ddbb3f9ffd5735efb20f4feaff131 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  1. """IMAP4 client.
  2. Based on RFC 2060.
  3. Public class: IMAP4
  4. Public variable: Debug
  5. Public functions: Internaldate2tuple
  6. Int2AP
  7. ParseFlags
  8. Time2Internaldate
  9. """
  10. # Author: Piers Lauder <piers@cs.su.oz.au> December 1997.
  11. #
  12. # Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
  13. # String method conversion by ESR, February 2001.
  14. # GET/SETACL contributed by Anthony Baxter <anthony@interlink.com.au> April 2001.
  15. # IMAP4_SSL contributed by Tino Lange <Tino.Lange@isg.de> March 2002.
  16. # GET/SETQUOTA contributed by Andreas Zeidler <az@kreativkombinat.de> June 2002.
  17. # PROXYAUTH contributed by Rick Holbert <holbert.13@osu.edu> November 2002.
  18. # GET/SETANNOTATION contributed by Tomas Lindroos <skitta@abo.fi> June 2005.
  19. __version__ = "2.58"
  20. import binascii, os, random, re, socket, sys, time
  21. __all__ = ["IMAP4", "IMAP4_SSL", "IMAP4_stream", "Internaldate2tuple",
  22. "Int2AP", "ParseFlags", "Time2Internaldate"]
  23. # Globals
  24. CRLF = '\r\n'
  25. Debug = 0
  26. IMAP4_PORT = 143
  27. IMAP4_SSL_PORT = 993
  28. AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
  29. # Commands
  30. Commands = {
  31. # name valid states
  32. 'APPEND': ('AUTH', 'SELECTED'),
  33. 'AUTHENTICATE': ('NONAUTH',),
  34. 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  35. 'CHECK': ('SELECTED',),
  36. 'CLOSE': ('SELECTED',),
  37. 'COPY': ('SELECTED',),
  38. 'CREATE': ('AUTH', 'SELECTED'),
  39. 'DELETE': ('AUTH', 'SELECTED'),
  40. 'DELETEACL': ('AUTH', 'SELECTED'),
  41. 'EXAMINE': ('AUTH', 'SELECTED'),
  42. 'EXPUNGE': ('SELECTED',),
  43. 'FETCH': ('SELECTED',),
  44. 'GETACL': ('AUTH', 'SELECTED'),
  45. 'GETANNOTATION':('AUTH', 'SELECTED'),
  46. 'GETQUOTA': ('AUTH', 'SELECTED'),
  47. 'GETQUOTAROOT': ('AUTH', 'SELECTED'),
  48. 'MYRIGHTS': ('AUTH', 'SELECTED'),
  49. 'LIST': ('AUTH', 'SELECTED'),
  50. 'LOGIN': ('NONAUTH',),
  51. 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  52. 'LSUB': ('AUTH', 'SELECTED'),
  53. 'NAMESPACE': ('AUTH', 'SELECTED'),
  54. 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  55. 'PARTIAL': ('SELECTED',), # NB: obsolete
  56. 'PROXYAUTH': ('AUTH',),
  57. 'RENAME': ('AUTH', 'SELECTED'),
  58. 'SEARCH': ('SELECTED',),
  59. 'SELECT': ('AUTH', 'SELECTED'),
  60. 'SETACL': ('AUTH', 'SELECTED'),
  61. 'SETANNOTATION':('AUTH', 'SELECTED'),
  62. 'SETQUOTA': ('AUTH', 'SELECTED'),
  63. 'SORT': ('SELECTED',),
  64. 'STATUS': ('AUTH', 'SELECTED'),
  65. 'STORE': ('SELECTED',),
  66. 'SUBSCRIBE': ('AUTH', 'SELECTED'),
  67. 'THREAD': ('SELECTED',),
  68. 'UID': ('SELECTED',),
  69. 'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
  70. }
  71. # Patterns to match server responses
  72. Continuation = re.compile(r'\+( (?P<data>.*))?')
  73. Flags = re.compile(r'.*FLAGS \((?P<flags>[^\)]*)\)')
  74. InternalDate = re.compile(r'.*INTERNALDATE "'
  75. r'(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
  76. r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
  77. r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
  78. r'"')
  79. Literal = re.compile(r'.*{(?P<size>\d+)}$')
  80. MapCRLF = re.compile(r'\r\n|\r|\n')
  81. Response_code = re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
  82. Untagged_response = re.compile(r'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
  83. Untagged_status = re.compile(r'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
  84. class IMAP4:
  85. """IMAP4 client class.
  86. Instantiate with: IMAP4([host[, port]])
  87. host - host's name (default: localhost);
  88. port - port number (default: standard IMAP4 port).
  89. All IMAP4rev1 commands are supported by methods of the same
  90. name (in lower-case).
  91. All arguments to commands are converted to strings, except for
  92. AUTHENTICATE, and the last argument to APPEND which is passed as
  93. an IMAP4 literal. If necessary (the string contains any
  94. non-printing characters or white-space and isn't enclosed with
  95. either parentheses or double quotes) each string is quoted.
  96. However, the 'password' argument to the LOGIN command is always
  97. quoted. If you want to avoid having an argument string quoted
  98. (eg: the 'flags' argument to STORE) then enclose the string in
  99. parentheses (eg: "(\Deleted)").
  100. Each command returns a tuple: (type, [data, ...]) where 'type'
  101. is usually 'OK' or 'NO', and 'data' is either the text from the
  102. tagged response, or untagged results from command. Each 'data'
  103. is either a string, or a tuple. If a tuple, then the first part
  104. is the header of the response, and the second part contains
  105. the data (ie: 'literal' value).
  106. Errors raise the exception class <instance>.error("<reason>").
  107. IMAP4 server errors raise <instance>.abort("<reason>"),
  108. which is a sub-class of 'error'. Mailbox status changes
  109. from READ-WRITE to READ-ONLY raise the exception class
  110. <instance>.readonly("<reason>"), which is a sub-class of 'abort'.
  111. "error" exceptions imply a program error.
  112. "abort" exceptions imply the connection should be reset, and
  113. the command re-tried.
  114. "readonly" exceptions imply the command should be re-tried.
  115. Note: to use this module, you must read the RFCs pertaining to the
  116. IMAP4 protocol, as the semantics of the arguments to each IMAP4
  117. command are left to the invoker, not to mention the results. Also,
  118. most IMAP servers implement a sub-set of the commands available here.
  119. """
  120. class error(Exception): pass # Logical errors - debug required
  121. class abort(error): pass # Service errors - close and retry
  122. class readonly(abort): pass # Mailbox status changed to READ-ONLY
  123. mustquote = re.compile(r"[^\w!#$%&'*+,.:;<=>?^`|~-]")
  124. def __init__(self, host = '', port = IMAP4_PORT):
  125. self.debug = Debug
  126. self.state = 'LOGOUT'
  127. self.literal = None # A literal argument to a command
  128. self.tagged_commands = {} # Tagged commands awaiting response
  129. self.untagged_responses = {} # {typ: [data, ...], ...}
  130. self.continuation_response = '' # Last continuation response
  131. self.is_readonly = False # READ-ONLY desired state
  132. self.tagnum = 0
  133. # Open socket to server.
  134. self.open(host, port)
  135. # Create unique tag for this session,
  136. # and compile tagged response matcher.
  137. self.tagpre = Int2AP(random.randint(4096, 65535))
  138. self.tagre = re.compile(r'(?P<tag>'
  139. + self.tagpre
  140. + r'\d+) (?P<type>[A-Z]+) (?P<data>.*)')
  141. # Get server welcome message,
  142. # request and store CAPABILITY response.
  143. if __debug__:
  144. self._cmd_log_len = 10
  145. self._cmd_log_idx = 0
  146. self._cmd_log = {} # Last `_cmd_log_len' interactions
  147. if self.debug >= 1:
  148. self._mesg('imaplib version %s' % __version__)
  149. self._mesg('new IMAP4 connection, tag=%s' % self.tagpre)
  150. self.welcome = self._get_response()
  151. if 'PREAUTH' in self.untagged_responses:
  152. self.state = 'AUTH'
  153. elif 'OK' in self.untagged_responses:
  154. self.state = 'NONAUTH'
  155. else:
  156. raise self.error(self.welcome)
  157. typ, dat = self.capability()
  158. if dat == [None]:
  159. raise self.error('no CAPABILITY response from server')
  160. self.capabilities = tuple(dat[-1].upper().split())
  161. if __debug__:
  162. if self.debug >= 3:
  163. self._mesg('CAPABILITIES: %r' % (self.capabilities,))
  164. for version in AllowedVersions:
  165. if not version in self.capabilities:
  166. continue
  167. self.PROTOCOL_VERSION = version
  168. return
  169. raise self.error('server not IMAP4 compliant')
  170. def __getattr__(self, attr):
  171. # Allow UPPERCASE variants of IMAP4 command methods.
  172. if attr in Commands:
  173. return getattr(self, attr.lower())
  174. raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
  175. # Overridable methods
  176. def open(self, host = '', port = IMAP4_PORT):
  177. """Setup connection to remote server on "host:port"
  178. (default: localhost:standard IMAP4 port).
  179. This connection will be used by the routines:
  180. read, readline, send, shutdown.
  181. """
  182. self.host = host
  183. self.port = port
  184. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  185. self.sock.connect((host, port))
  186. self.file = self.sock.makefile('rb')
  187. def read(self, size):
  188. """Read 'size' bytes from remote."""
  189. return self.file.read(size)
  190. def readline(self):
  191. """Read line from remote."""
  192. return self.file.readline()
  193. def send(self, data):
  194. """Send data to remote."""
  195. self.sock.sendall(data)
  196. def shutdown(self):
  197. """Close I/O established in "open"."""
  198. self.file.close()
  199. self.sock.close()
  200. def socket(self):
  201. """Return socket instance used to connect to IMAP4 server.
  202. socket = <instance>.socket()
  203. """
  204. return self.sock
  205. # Utility methods
  206. def recent(self):
  207. """Return most recent 'RECENT' responses if any exist,
  208. else prompt server for an update using the 'NOOP' command.
  209. (typ, [data]) = <instance>.recent()
  210. 'data' is None if no new messages,
  211. else list of RECENT responses, most recent last.
  212. """
  213. name = 'RECENT'
  214. typ, dat = self._untagged_response('OK', [None], name)
  215. if dat[-1]:
  216. return typ, dat
  217. typ, dat = self.noop() # Prod server for response
  218. return self._untagged_response(typ, dat, name)
  219. def response(self, code):
  220. """Return data for response 'code' if received, or None.
  221. Old value for response 'code' is cleared.
  222. (code, [data]) = <instance>.response(code)
  223. """
  224. return self._untagged_response(code, [None], code.upper())
  225. # IMAP4 commands
  226. def append(self, mailbox, flags, date_time, message):
  227. """Append message to named mailbox.
  228. (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
  229. All args except `message' can be None.
  230. """
  231. name = 'APPEND'
  232. if not mailbox:
  233. mailbox = 'INBOX'
  234. if flags:
  235. if (flags[0],flags[-1]) != ('(',')'):
  236. flags = '(%s)' % flags
  237. else:
  238. flags = None
  239. if date_time:
  240. date_time = Time2Internaldate(date_time)
  241. else:
  242. date_time = None
  243. self.literal = MapCRLF.sub(CRLF, message)
  244. return self._simple_command(name, mailbox, flags, date_time)
  245. def authenticate(self, mechanism, authobject):
  246. """Authenticate command - requires response processing.
  247. 'mechanism' specifies which authentication mechanism is to
  248. be used - it must appear in <instance>.capabilities in the
  249. form AUTH=<mechanism>.
  250. 'authobject' must be a callable object:
  251. data = authobject(response)
  252. It will be called to process server continuation responses.
  253. It should return data that will be encoded and sent to server.
  254. It should return None if the client abort response '*' should
  255. be sent instead.
  256. """
  257. mech = mechanism.upper()
  258. # XXX: shouldn't this code be removed, not commented out?
  259. #cap = 'AUTH=%s' % mech
  260. #if not cap in self.capabilities: # Let the server decide!
  261. # raise self.error("Server doesn't allow %s authentication." % mech)
  262. self.literal = _Authenticator(authobject).process
  263. typ, dat = self._simple_command('AUTHENTICATE', mech)
  264. if typ != 'OK':
  265. raise self.error(dat[-1])
  266. self.state = 'AUTH'
  267. return typ, dat
  268. def capability(self):
  269. """(typ, [data]) = <instance>.capability()
  270. Fetch capabilities list from server."""
  271. name = 'CAPABILITY'
  272. typ, dat = self._simple_command(name)
  273. return self._untagged_response(typ, dat, name)
  274. def check(self):
  275. """Checkpoint mailbox on server.
  276. (typ, [data]) = <instance>.check()
  277. """
  278. return self._simple_command('CHECK')
  279. def close(self):
  280. """Close currently selected mailbox.
  281. Deleted messages are removed from writable mailbox.
  282. This is the recommended command before 'LOGOUT'.
  283. (typ, [data]) = <instance>.close()
  284. """
  285. try:
  286. typ, dat = self._simple_command('CLOSE')
  287. finally:
  288. self.state = 'AUTH'
  289. return typ, dat
  290. def copy(self, message_set, new_mailbox):
  291. """Copy 'message_set' messages onto end of 'new_mailbox'.
  292. (typ, [data]) = <instance>.copy(message_set, new_mailbox)
  293. """
  294. return self._simple_command('COPY', message_set, new_mailbox)
  295. def create(self, mailbox):
  296. """Create new mailbox.
  297. (typ, [data]) = <instance>.create(mailbox)
  298. """
  299. return self._simple_command('CREATE', mailbox)
  300. def delete(self, mailbox):
  301. """Delete old mailbox.
  302. (typ, [data]) = <instance>.delete(mailbox)
  303. """
  304. return self._simple_command('DELETE', mailbox)
  305. def deleteacl(self, mailbox, who):
  306. """Delete the ACLs (remove any rights) set for who on mailbox.
  307. (typ, [data]) = <instance>.deleteacl(mailbox, who)
  308. """
  309. return self._simple_command('DELETEACL', mailbox, who)
  310. def expunge(self):
  311. """Permanently remove deleted items from selected mailbox.
  312. Generates 'EXPUNGE' response for each deleted message.
  313. (typ, [data]) = <instance>.expunge()
  314. 'data' is list of 'EXPUNGE'd message numbers in order received.
  315. """
  316. name = 'EXPUNGE'
  317. typ, dat = self._simple_command(name)
  318. return self._untagged_response(typ, dat, name)
  319. def fetch(self, message_set, message_parts):
  320. """Fetch (parts of) messages.
  321. (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
  322. 'message_parts' should be a string of selected parts
  323. enclosed in parentheses, eg: "(UID BODY[TEXT])".
  324. 'data' are tuples of message part envelope and data.
  325. """
  326. name = 'FETCH'
  327. typ, dat = self._simple_command(name, message_set, message_parts)
  328. return self._untagged_response(typ, dat, name)
  329. def getacl(self, mailbox):
  330. """Get the ACLs for a mailbox.
  331. (typ, [data]) = <instance>.getacl(mailbox)
  332. """
  333. typ, dat = self._simple_command('GETACL', mailbox)
  334. return self._untagged_response(typ, dat, 'ACL')
  335. def getannotation(self, mailbox, entry, attribute):
  336. """(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute)
  337. Retrieve ANNOTATIONs."""
  338. typ, dat = self._simple_command('GETANNOTATION', mailbox, entry, attribute)
  339. return self._untagged_response(typ, dat, 'ANNOTATION')
  340. def getquota(self, root):
  341. """Get the quota root's resource usage and limits.
  342. Part of the IMAP4 QUOTA extension defined in rfc2087.
  343. (typ, [data]) = <instance>.getquota(root)
  344. """
  345. typ, dat = self._simple_command('GETQUOTA', root)
  346. return self._untagged_response(typ, dat, 'QUOTA')
  347. def getquotaroot(self, mailbox):
  348. """Get the list of quota roots for the named mailbox.
  349. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
  350. """
  351. typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
  352. typ, quota = self._untagged_response(typ, dat, 'QUOTA')
  353. typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
  354. return typ, [quotaroot, quota]
  355. def list(self, directory='""', pattern='*'):
  356. """List mailbox names in directory matching pattern.
  357. (typ, [data]) = <instance>.list(directory='""', pattern='*')
  358. 'data' is list of LIST responses.
  359. """
  360. name = 'LIST'
  361. typ, dat = self._simple_command(name, directory, pattern)
  362. return self._untagged_response(typ, dat, name)
  363. def login(self, user, password):
  364. """Identify client using plaintext password.
  365. (typ, [data]) = <instance>.login(user, password)
  366. NB: 'password' will be quoted.
  367. """
  368. typ, dat = self._simple_command('LOGIN', user, self._quote(password))
  369. if typ != 'OK':
  370. raise self.error(dat[-1])
  371. self.state = 'AUTH'
  372. return typ, dat
  373. def login_cram_md5(self, user, password):
  374. """ Force use of CRAM-MD5 authentication.
  375. (typ, [data]) = <instance>.login_cram_md5(user, password)
  376. """
  377. self.user, self.password = user, password
  378. return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
  379. def _CRAM_MD5_AUTH(self, challenge):
  380. """ Authobject to use with CRAM-MD5 authentication. """
  381. import hmac
  382. return self.user + " " + hmac.HMAC(self.password, challenge).hexdigest()
  383. def logout(self):
  384. """Shutdown connection to server.
  385. (typ, [data]) = <instance>.logout()
  386. Returns server 'BYE' response.
  387. """
  388. self.state = 'LOGOUT'
  389. try: typ, dat = self._simple_command('LOGOUT')
  390. except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
  391. self.shutdown()
  392. if 'BYE' in self.untagged_responses:
  393. return 'BYE', self.untagged_responses['BYE']
  394. return typ, dat
  395. def lsub(self, directory='""', pattern='*'):
  396. """List 'subscribed' mailbox names in directory matching pattern.
  397. (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
  398. 'data' are tuples of message part envelope and data.
  399. """
  400. name = 'LSUB'
  401. typ, dat = self._simple_command(name, directory, pattern)
  402. return self._untagged_response(typ, dat, name)
  403. def myrights(self, mailbox):
  404. """Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
  405. (typ, [data]) = <instance>.myrights(mailbox)
  406. """
  407. typ,dat = self._simple_command('MYRIGHTS', mailbox)
  408. return self._untagged_response(typ, dat, 'MYRIGHTS')
  409. def namespace(self):
  410. """ Returns IMAP namespaces ala rfc2342
  411. (typ, [data, ...]) = <instance>.namespace()
  412. """
  413. name = 'NAMESPACE'
  414. typ, dat = self._simple_command(name)
  415. return self._untagged_response(typ, dat, name)
  416. def noop(self):
  417. """Send NOOP command.
  418. (typ, [data]) = <instance>.noop()
  419. """
  420. if __debug__:
  421. if self.debug >= 3:
  422. self._dump_ur(self.untagged_responses)
  423. return self._simple_command('NOOP')
  424. def partial(self, message_num, message_part, start, length):
  425. """Fetch truncated part of a message.
  426. (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
  427. 'data' is tuple of message part envelope and data.
  428. """
  429. name = 'PARTIAL'
  430. typ, dat = self._simple_command(name, message_num, message_part, start, length)
  431. return self._untagged_response(typ, dat, 'FETCH')
  432. def proxyauth(self, user):
  433. """Assume authentication as "user".
  434. Allows an authorised administrator to proxy into any user's
  435. mailbox.
  436. (typ, [data]) = <instance>.proxyauth(user)
  437. """
  438. name = 'PROXYAUTH'
  439. return self._simple_command('PROXYAUTH', user)
  440. def rename(self, oldmailbox, newmailbox):
  441. """Rename old mailbox name to new.
  442. (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
  443. """
  444. return self._simple_command('RENAME', oldmailbox, newmailbox)
  445. def search(self, charset, *criteria):
  446. """Search mailbox for matching messages.
  447. (typ, [data]) = <instance>.search(charset, criterion, ...)
  448. 'data' is space separated list of matching message numbers.
  449. """
  450. name = 'SEARCH'
  451. if charset:
  452. typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
  453. else:
  454. typ, dat = self._simple_command(name, *criteria)
  455. return self._untagged_response(typ, dat, name)
  456. def select(self, mailbox='INBOX', readonly=False):
  457. """Select a mailbox.
  458. Flush all untagged responses.
  459. (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=False)
  460. 'data' is count of messages in mailbox ('EXISTS' response).
  461. Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
  462. other responses should be obtained via <instance>.response('FLAGS') etc.
  463. """
  464. self.untagged_responses = {} # Flush old responses.
  465. self.is_readonly = readonly
  466. if readonly:
  467. name = 'EXAMINE'
  468. else:
  469. name = 'SELECT'
  470. typ, dat = self._simple_command(name, mailbox)
  471. if typ != 'OK':
  472. self.state = 'AUTH' # Might have been 'SELECTED'
  473. return typ, dat
  474. self.state = 'SELECTED'
  475. if 'READ-ONLY' in self.untagged_responses \
  476. and not readonly:
  477. if __debug__:
  478. if self.debug >= 1:
  479. self._dump_ur(self.untagged_responses)
  480. raise self.readonly('%s is not writable' % mailbox)
  481. return typ, self.untagged_responses.get('EXISTS', [None])
  482. def setacl(self, mailbox, who, what):
  483. """Set a mailbox acl.
  484. (typ, [data]) = <instance>.setacl(mailbox, who, what)
  485. """
  486. return self._simple_command('SETACL', mailbox, who, what)
  487. def setannotation(self, *args):
  488. """(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+)
  489. Set ANNOTATIONs."""
  490. typ, dat = self._simple_command('SETANNOTATION', *args)
  491. return self._untagged_response(typ, dat, 'ANNOTATION')
  492. def setquota(self, root, limits):
  493. """Set the quota root's resource limits.
  494. (typ, [data]) = <instance>.setquota(root, limits)
  495. """
  496. typ, dat = self._simple_command('SETQUOTA', root, limits)
  497. return self._untagged_response(typ, dat, 'QUOTA')
  498. def sort(self, sort_criteria, charset, *search_criteria):
  499. """IMAP4rev1 extension SORT command.
  500. (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
  501. """
  502. name = 'SORT'
  503. #if not name in self.capabilities: # Let the server decide!
  504. # raise self.error('unimplemented extension command: %s' % name)
  505. if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
  506. sort_criteria = '(%s)' % sort_criteria
  507. typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
  508. return self._untagged_response(typ, dat, name)
  509. def status(self, mailbox, names):
  510. """Request named status conditions for mailbox.
  511. (typ, [data]) = <instance>.status(mailbox, names)
  512. """
  513. name = 'STATUS'
  514. #if self.PROTOCOL_VERSION == 'IMAP4': # Let the server decide!
  515. # raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
  516. typ, dat = self._simple_command(name, mailbox, names)
  517. return self._untagged_response(typ, dat, name)
  518. def store(self, message_set, command, flags):
  519. """Alters flag dispositions for messages in mailbox.
  520. (typ, [data]) = <instance>.store(message_set, command, flags)
  521. """
  522. if (flags[0],flags[-1]) != ('(',')'):
  523. flags = '(%s)' % flags # Avoid quoting the flags
  524. typ, dat = self._simple_command('STORE', message_set, command, flags)
  525. return self._untagged_response(typ, dat, 'FETCH')
  526. def subscribe(self, mailbox):
  527. """Subscribe to new mailbox.
  528. (typ, [data]) = <instance>.subscribe(mailbox)
  529. """
  530. return self._simple_command('SUBSCRIBE', mailbox)
  531. def thread(self, threading_algorithm, charset, *search_criteria):
  532. """IMAPrev1 extension THREAD command.
  533. (type, [data]) = <instance>.thread(threading_alogrithm, charset, search_criteria, ...)
  534. """
  535. name = 'THREAD'
  536. typ, dat = self._simple_command(name, threading_algorithm, charset, *search_criteria)
  537. return self._untagged_response(typ, dat, name)
  538. def uid(self, command, *args):
  539. """Execute "command arg ..." with messages identified by UID,
  540. rather than message number.
  541. (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
  542. Returns response appropriate to 'command'.
  543. """
  544. command = command.upper()
  545. if not command in Commands:
  546. raise self.error("Unknown IMAP4 UID command: %s" % command)
  547. if self.state not in Commands[command]:
  548. raise self.error('command %s illegal in state %s'
  549. % (command, self.state))
  550. name = 'UID'
  551. typ, dat = self._simple_command(name, command, *args)
  552. if command in ('SEARCH', 'SORT'):
  553. name = command
  554. else:
  555. name = 'FETCH'
  556. return self._untagged_response(typ, dat, name)
  557. def unsubscribe(self, mailbox):
  558. """Unsubscribe from old mailbox.
  559. (typ, [data]) = <instance>.unsubscribe(mailbox)
  560. """
  561. return self._simple_command('UNSUBSCRIBE', mailbox)
  562. def xatom(self, name, *args):
  563. """Allow simple extension commands
  564. notified by server in CAPABILITY response.
  565. Assumes command is legal in current state.
  566. (typ, [data]) = <instance>.xatom(name, arg, ...)
  567. Returns response appropriate to extension command `name'.
  568. """
  569. name = name.upper()
  570. #if not name in self.capabilities: # Let the server decide!
  571. # raise self.error('unknown extension command: %s' % name)
  572. if not name in Commands:
  573. Commands[name] = (self.state,)
  574. return self._simple_command(name, *args)
  575. # Private methods
  576. def _append_untagged(self, typ, dat):
  577. if dat is None: dat = ''
  578. ur = self.untagged_responses
  579. if __debug__:
  580. if self.debug >= 5:
  581. self._mesg('untagged_responses[%s] %s += ["%s"]' %
  582. (typ, len(ur.get(typ,'')), dat))
  583. if typ in ur:
  584. ur[typ].append(dat)
  585. else:
  586. ur[typ] = [dat]
  587. def _check_bye(self):
  588. bye = self.untagged_responses.get('BYE')
  589. if bye:
  590. raise self.abort(bye[-1])
  591. def _command(self, name, *args):
  592. if self.state not in Commands[name]:
  593. self.literal = None
  594. raise self.error(
  595. 'command %s illegal in state %s' % (name, self.state))
  596. for typ in ('OK', 'NO', 'BAD'):
  597. if typ in self.untagged_responses:
  598. del self.untagged_responses[typ]
  599. if 'READ-ONLY' in self.untagged_responses \
  600. and not self.is_readonly:
  601. raise self.readonly('mailbox status changed to READ-ONLY')
  602. tag = self._new_tag()
  603. data = '%s %s' % (tag, name)
  604. for arg in args:
  605. if arg is None: continue
  606. data = '%s %s' % (data, self._checkquote(arg))
  607. literal = self.literal
  608. if literal is not None:
  609. self.literal = None
  610. if type(literal) is type(self._command):
  611. literator = literal
  612. else:
  613. literator = None
  614. data = '%s {%s}' % (data, len(literal))
  615. if __debug__:
  616. if self.debug >= 4:
  617. self._mesg('> %s' % data)
  618. else:
  619. self._log('> %s' % data)
  620. try:
  621. self.send('%s%s' % (data, CRLF))
  622. except (socket.error, OSError), val:
  623. raise self.abort('socket error: %s' % val)
  624. if literal is None:
  625. return tag
  626. while 1:
  627. # Wait for continuation response
  628. while self._get_response():
  629. if self.tagged_commands[tag]: # BAD/NO?
  630. return tag
  631. # Send literal
  632. if literator:
  633. literal = literator(self.continuation_response)
  634. if __debug__:
  635. if self.debug >= 4:
  636. self._mesg('write literal size %s' % len(literal))
  637. try:
  638. self.send(literal)
  639. self.send(CRLF)
  640. except (socket.error, OSError), val:
  641. raise self.abort('socket error: %s' % val)
  642. if not literator:
  643. break
  644. return tag
  645. def _command_complete(self, name, tag):
  646. self._check_bye()
  647. try:
  648. typ, data = self._get_tagged_response(tag)
  649. except self.abort, val:
  650. raise self.abort('command: %s => %s' % (name, val))
  651. except self.error, val:
  652. raise self.error('command: %s => %s' % (name, val))
  653. self._check_bye()
  654. if typ == 'BAD':
  655. raise self.error('%s command error: %s %s' % (name, typ, data))
  656. return typ, data
  657. def _get_response(self):
  658. # Read response and store.
  659. #
  660. # Returns None for continuation responses,
  661. # otherwise first response line received.
  662. resp = self._get_line()
  663. # Command completion response?
  664. if self._match(self.tagre, resp):
  665. tag = self.mo.group('tag')
  666. if not tag in self.tagged_commands:
  667. raise self.abort('unexpected tagged response: %s' % resp)
  668. typ = self.mo.group('type')
  669. dat = self.mo.group('data')
  670. self.tagged_commands[tag] = (typ, [dat])
  671. else:
  672. dat2 = None
  673. # '*' (untagged) responses?
  674. if not self._match(Untagged_response, resp):
  675. if self._match(Untagged_status, resp):
  676. dat2 = self.mo.group('data2')
  677. if self.mo is None:
  678. # Only other possibility is '+' (continuation) response...
  679. if self._match(Continuation, resp):
  680. self.continuation_response = self.mo.group('data')
  681. return None # NB: indicates continuation
  682. raise self.abort("unexpected response: '%s'" % resp)
  683. typ = self.mo.group('type')
  684. dat = self.mo.group('data')
  685. if dat is None: dat = '' # Null untagged response
  686. if dat2: dat = dat + ' ' + dat2
  687. # Is there a literal to come?
  688. while self._match(Literal, dat):
  689. # Read literal direct from connection.
  690. size = int(self.mo.group('size'))
  691. if __debug__:
  692. if self.debug >= 4:
  693. self._mesg('read literal size %s' % size)
  694. data = self.read(size)
  695. # Store response with literal as tuple
  696. self._append_untagged(typ, (dat, data))
  697. # Read trailer - possibly containing another literal
  698. dat = self._get_line()
  699. self._append_untagged(typ, dat)
  700. # Bracketed response information?
  701. if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
  702. self._append_untagged(self.mo.group('type'), self.mo.group('data'))
  703. if __debug__:
  704. if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
  705. self._mesg('%s response: %s' % (typ, dat))
  706. return resp
  707. def _get_tagged_response(self, tag):
  708. while 1:
  709. result = self.tagged_commands[tag]
  710. if result is not None:
  711. del self.tagged_commands[tag]
  712. return result
  713. # Some have reported "unexpected response" exceptions.
  714. # Note that ignoring them here causes loops.
  715. # Instead, send me details of the unexpected response and
  716. # I'll update the code in `_get_response()'.
  717. try:
  718. self._get_response()
  719. except self.abort, val:
  720. if __debug__:
  721. if self.debug >= 1:
  722. self.print_log()
  723. raise
  724. def _get_line(self):
  725. line = self.readline()
  726. if not line:
  727. raise self.abort('socket error: EOF')
  728. # Protocol mandates all lines terminated by CRLF
  729. line = line[:-2]
  730. if __debug__:
  731. if self.debug >= 4:
  732. self._mesg('< %s' % line)
  733. else:
  734. self._log('< %s' % line)
  735. return line
  736. def _match(self, cre, s):
  737. # Run compiled regular expression match method on 's'.
  738. # Save result, return success.
  739. self.mo = cre.match(s)
  740. if __debug__:
  741. if self.mo is not None and self.debug >= 5:
  742. self._mesg("\tmatched r'%s' => %r" % (cre.pattern, self.mo.groups()))
  743. return self.mo is not None
  744. def _new_tag(self):
  745. tag = '%s%s' % (self.tagpre, self.tagnum)
  746. self.tagnum = self.tagnum + 1
  747. self.tagged_commands[tag] = None
  748. return tag
  749. def _checkquote(self, arg):
  750. # Must quote command args if non-alphanumeric chars present,
  751. # and not already quoted.
  752. if type(arg) is not type(''):
  753. return arg
  754. if len(arg) >= 2 and (arg[0],arg[-1]) in (('(',')'),('"','"')):
  755. return arg
  756. if arg and self.mustquote.search(arg) is None:
  757. return arg
  758. return self._quote(arg)
  759. def _quote(self, arg):
  760. arg = arg.replace('\\', '\\\\')
  761. arg = arg.replace('"', '\\"')
  762. return '"%s"' % arg
  763. def _simple_command(self, name, *args):
  764. return self._command_complete(name, self._command(name, *args))
  765. def _untagged_response(self, typ, dat, name):
  766. if typ == 'NO':
  767. return typ, dat
  768. if not name in self.untagged_responses:
  769. return typ, [None]
  770. data = self.untagged_responses.pop(name)
  771. if __debug__:
  772. if self.debug >= 5:
  773. self._mesg('untagged_responses[%s] => %s' % (name, data))
  774. return typ, data
  775. if __debug__:
  776. def _mesg(self, s, secs=None):
  777. if secs is None:
  778. secs = time.time()
  779. tm = time.strftime('%M:%S', time.localtime(secs))
  780. sys.stderr.write(' %s.%02d %s\n' % (tm, (secs*100)%100, s))
  781. sys.stderr.flush()
  782. def _dump_ur(self, dict):
  783. # Dump untagged responses (in `dict').
  784. l = dict.items()
  785. if not l: return
  786. t = '\n\t\t'
  787. l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l)
  788. self._mesg('untagged responses dump:%s%s' % (t, t.join(l)))
  789. def _log(self, line):
  790. # Keep log of last `_cmd_log_len' interactions for debugging.
  791. self._cmd_log[self._cmd_log_idx] = (line, time.time())
  792. self._cmd_log_idx += 1
  793. if self._cmd_log_idx >= self._cmd_log_len:
  794. self._cmd_log_idx = 0
  795. def print_log(self):
  796. self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log))
  797. i, n = self._cmd_log_idx, self._cmd_log_len
  798. while n:
  799. try:
  800. self._mesg(*self._cmd_log[i])
  801. except:
  802. pass
  803. i += 1
  804. if i >= self._cmd_log_len:
  805. i = 0
  806. n -= 1
  807. class IMAP4_SSL(IMAP4):
  808. """IMAP4 client class over SSL connection
  809. Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
  810. host - host's name (default: localhost);
  811. port - port number (default: standard IMAP4 SSL port).
  812. keyfile - PEM formatted file that contains your private key (default: None);
  813. certfile - PEM formatted certificate chain file (default: None);
  814. for more documentation see the docstring of the parent class IMAP4.
  815. """
  816. def __init__(self, host = '', port = IMAP4_SSL_PORT, keyfile = None, certfile = None):
  817. self.keyfile = keyfile
  818. self.certfile = certfile
  819. IMAP4.__init__(self, host, port)
  820. def open(self, host = '', port = IMAP4_SSL_PORT):
  821. """Setup connection to remote server on "host:port".
  822. (default: localhost:standard IMAP4 SSL port).
  823. This connection will be used by the routines:
  824. read, readline, send, shutdown.
  825. """
  826. self.host = host
  827. self.port = port
  828. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  829. self.sock.connect((host, port))
  830. self.sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
  831. def read(self, size):
  832. """Read 'size' bytes from remote."""
  833. # sslobj.read() sometimes returns < size bytes
  834. chunks = []
  835. read = 0
  836. while read < size:
  837. data = self.sslobj.read(min(size-read, 16384))
  838. read += len(data)
  839. chunks.append(data)
  840. return ''.join(chunks)
  841. def readline(self):
  842. """Read line from remote."""
  843. # NB: socket.ssl needs a "readline" method, or perhaps a "makefile" method.
  844. line = []
  845. while 1:
  846. char = self.sslobj.read(1)
  847. line.append(char)
  848. if char == "\n": return ''.join(line)
  849. def send(self, data):
  850. """Send data to remote."""
  851. # NB: socket.ssl needs a "sendall" method to match socket objects.
  852. bytes = len(data)
  853. while bytes > 0:
  854. sent = self.sslobj.write(data)
  855. if sent == bytes:
  856. break # avoid copy
  857. data = data[sent:]
  858. bytes = bytes - sent
  859. def shutdown(self):
  860. """Close I/O established in "open"."""
  861. self.sock.close()
  862. def socket(self):
  863. """Return socket instance used to connect to IMAP4 server.
  864. socket = <instance>.socket()
  865. """
  866. return self.sock
  867. def ssl(self):
  868. """Return SSLObject instance used to communicate with the IMAP4 server.
  869. ssl = <instance>.socket.ssl()
  870. """
  871. return self.sslobj
  872. class IMAP4_stream(IMAP4):
  873. """IMAP4 client class over a stream
  874. Instantiate with: IMAP4_stream(command)
  875. where "command" is a string that can be passed to os.popen2()
  876. for more documentation see the docstring of the parent class IMAP4.
  877. """
  878. def __init__(self, command):
  879. self.command = command
  880. IMAP4.__init__(self)
  881. def open(self, host = None, port = None):
  882. """Setup a stream connection.
  883. This connection will be used by the routines:
  884. read, readline, send, shutdown.
  885. """
  886. self.host = None # For compatibility with parent class
  887. self.port = None
  888. self.sock = None
  889. self.file = None
  890. self.writefile, self.readfile = os.popen2(self.command)
  891. def read(self, size):
  892. """Read 'size' bytes from remote."""
  893. return self.readfile.read(size)
  894. def readline(self):
  895. """Read line from remote."""
  896. return self.readfile.readline()
  897. def send(self, data):
  898. """Send data to remote."""
  899. self.writefile.write(data)
  900. self.writefile.flush()
  901. def shutdown(self):
  902. """Close I/O established in "open"."""
  903. self.readfile.close()
  904. self.writefile.close()
  905. class _Authenticator:
  906. """Private class to provide en/decoding
  907. for base64-based authentication conversation.
  908. """
  909. def __init__(self, mechinst):
  910. self.mech = mechinst # Callable object to provide/process data
  911. def process(self, data):
  912. ret = self.mech(self.decode(data))
  913. if ret is None:
  914. return '*' # Abort conversation
  915. return self.encode(ret)
  916. def encode(self, inp):
  917. #
  918. # Invoke binascii.b2a_base64 iteratively with
  919. # short even length buffers, strip the trailing
  920. # line feed from the result and append. "Even"
  921. # means a number that factors to both 6 and 8,
  922. # so when it gets to the end of the 8-bit input
  923. # there's no partial 6-bit output.
  924. #
  925. oup = ''
  926. while inp:
  927. if len(inp) > 48:
  928. t = inp[:48]
  929. inp = inp[48:]
  930. else:
  931. t = inp
  932. inp = ''
  933. e = binascii.b2a_base64(t)
  934. if e:
  935. oup = oup + e[:-1]
  936. return oup
  937. def decode(self, inp):
  938. if not inp:
  939. return ''
  940. return binascii.a2b_base64(inp)
  941. Mon2num = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
  942. 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
  943. def Internaldate2tuple(resp):
  944. """Convert IMAP4 INTERNALDATE to UT.
  945. Returns Python time module tuple.
  946. """
  947. mo = InternalDate.match(resp)
  948. if not mo:
  949. return None
  950. mon = Mon2num[mo.group('mon')]
  951. zonen = mo.group('zonen')
  952. day = int(mo.group('day'))
  953. year = int(mo.group('year'))
  954. hour = int(mo.group('hour'))
  955. min = int(mo.group('min'))
  956. sec = int(mo.group('sec'))
  957. zoneh = int(mo.group('zoneh'))
  958. zonem = int(mo.group('zonem'))
  959. # INTERNALDATE timezone must be subtracted to get UT
  960. zone = (zoneh*60 + zonem)*60
  961. if zonen == '-':
  962. zone = -zone
  963. tt = (year, mon, day, hour, min, sec, -1, -1, -1)
  964. utc = time.mktime(tt)
  965. # Following is necessary because the time module has no 'mkgmtime'.
  966. # 'mktime' assumes arg in local timezone, so adds timezone/altzone.
  967. lt = time.localtime(utc)
  968. if time.daylight and lt[-1]:
  969. zone = zone + time.altzone
  970. else:
  971. zone = zone + time.timezone
  972. return time.localtime(utc - zone)
  973. def Int2AP(num):
  974. """Convert integer to A-P string representation."""
  975. val = ''; AP = 'ABCDEFGHIJKLMNOP'
  976. num = int(abs(num))
  977. while num:
  978. num, mod = divmod(num, 16)
  979. val = AP[mod] + val
  980. return val
  981. def ParseFlags(resp):
  982. """Convert IMAP4 flags response to python tuple."""
  983. mo = Flags.match(resp)
  984. if not mo:
  985. return ()
  986. return tuple(mo.group('flags').split())
  987. def Time2Internaldate(date_time):
  988. """Convert 'date_time' to IMAP4 INTERNALDATE representation.
  989. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
  990. """
  991. if isinstance(date_time, (int, float)):
  992. tt = time.localtime(date_time)
  993. elif isinstance(date_time, (tuple, time.struct_time)):
  994. tt = date_time
  995. elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
  996. return date_time # Assume in correct format
  997. else:
  998. raise ValueError("date_time not of a known type")
  999. dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
  1000. if dt[0] == '0':
  1001. dt = ' ' + dt[1:]
  1002. if time.daylight and tt[-1]:
  1003. zone = -time.altzone
  1004. else:
  1005. zone = -time.timezone
  1006. return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"'
  1007. if __name__ == '__main__':
  1008. # To test: invoke either as 'python imaplib.py [IMAP4_server_hostname]'
  1009. # or 'python imaplib.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
  1010. # to test the IMAP4_stream class
  1011. import getopt, getpass
  1012. try:
  1013. optlist, args = getopt.getopt(sys.argv[1:], 'd:s:')
  1014. except getopt.error, val:
  1015. optlist, args = (), ()
  1016. stream_command = None
  1017. for opt,val in optlist:
  1018. if opt == '-d':
  1019. Debug = int(val)
  1020. elif opt == '-s':
  1021. stream_command = val
  1022. if not args: args = (stream_command,)
  1023. if not args: args = ('',)
  1024. host = args[0]
  1025. USER = getpass.getuser()
  1026. PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost"))
  1027. test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':'\n'}
  1028. test_seq1 = (
  1029. ('login', (USER, PASSWD)),
  1030. ('create', ('/tmp/xxx 1',)),
  1031. ('rename', ('/tmp/xxx 1', '/tmp/yyy')),
  1032. ('CREATE', ('/tmp/yyz 2',)),
  1033. ('append', ('/tmp/yyz 2', None, None, test_mesg)),
  1034. ('list', ('/tmp', 'yy*')),
  1035. ('select', ('/tmp/yyz 2',)),
  1036. ('search', (None, 'SUBJECT', 'test')),
  1037. ('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')),
  1038. ('store', ('1', 'FLAGS', '(\Deleted)')),
  1039. ('namespace', ()),
  1040. ('expunge', ()),
  1041. ('recent', ()),
  1042. ('close', ()),
  1043. )
  1044. test_seq2 = (
  1045. ('select', ()),
  1046. ('response',('UIDVALIDITY',)),
  1047. ('uid', ('SEARCH', 'ALL')),
  1048. ('response', ('EXISTS',)),
  1049. ('append', (None, None, None, test_mesg)),
  1050. ('recent', ()),
  1051. ('logout', ()),
  1052. )
  1053. def run(cmd, args):
  1054. M._mesg('%s %s' % (cmd, args))
  1055. typ, dat = getattr(M, cmd)(*args)
  1056. M._mesg('%s => %s %s' % (cmd, typ, dat))
  1057. if typ == 'NO': raise dat[0]
  1058. return dat
  1059. try:
  1060. if stream_command:
  1061. M = IMAP4_stream(stream_command)
  1062. else:
  1063. M = IMAP4(host)
  1064. if M.state == 'AUTH':
  1065. test_seq1 = test_seq1[1:] # Login not needed
  1066. M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
  1067. M._mesg('CAPABILITIES = %r' % (M.capabilities,))
  1068. for cmd,args in test_seq1:
  1069. run(cmd, args)
  1070. for ml in run('list', ('/tmp/', 'yy%')):
  1071. mo = re.match(r'.*"([^"]+)"$', ml)
  1072. if mo: path = mo.group(1)
  1073. else: path = ml.split()[-1]
  1074. run('delete', (path,))
  1075. for cmd,args in test_seq2:
  1076. dat = run(cmd, args)
  1077. if (cmd,args) != ('uid', ('SEARCH', 'ALL')):
  1078. continue
  1079. uid = dat[-1].split()
  1080. if not uid: continue
  1081. run('uid', ('FETCH', '%s' % uid[-1],
  1082. '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
  1083. print '\nAll tests OK.'
  1084. except:
  1085. print '\nTests failed.'
  1086. if not Debug:
  1087. print '''
  1088. If you would like to see debugging output,
  1089. try: %s -d5
  1090. ''' % sys.argv[0]
  1091. raise