PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/imaplib.py

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