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

/lib-python/2.7/imaplib.py

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