/Lib/imaplib.py

http://unladen-swallow.googlecode.com/ · Python · 1505 lines · 1360 code · 74 blank · 71 comment · 36 complexity · 46a1e2eca5ab889305c27b35b424156a MD5 · raw file

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