PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/imaplib.py

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