PageRenderTime 64ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/mailbox.py

https://bitbucket.org/evelyn559/pypy
Python | 2171 lines | 2151 code | 9 blank | 11 comment | 6 complexity | 896aae70532e4c1349682b26172b1383 MD5 | raw file
  1. #! /usr/bin/env python
  2. """Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes."""
  3. # Notes for authors of new mailbox subclasses:
  4. #
  5. # Remember to fsync() changes to disk before closing a modified file
  6. # or returning from a flush() method. See functions _sync_flush() and
  7. # _sync_close().
  8. import sys
  9. import os
  10. import time
  11. import calendar
  12. import socket
  13. import errno
  14. import copy
  15. import email
  16. import email.message
  17. import email.generator
  18. import StringIO
  19. try:
  20. if sys.platform == 'os2emx':
  21. # OS/2 EMX fcntl() not adequate
  22. raise ImportError
  23. import fcntl
  24. except ImportError:
  25. fcntl = None
  26. import warnings
  27. with warnings.catch_warnings():
  28. if sys.py3kwarning:
  29. warnings.filterwarnings("ignore", ".*rfc822 has been removed",
  30. DeprecationWarning)
  31. import rfc822
  32. __all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',
  33. 'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
  34. 'BabylMessage', 'MMDFMessage', 'UnixMailbox',
  35. 'PortableUnixMailbox', 'MmdfMailbox', 'MHMailbox', 'BabylMailbox' ]
  36. class Mailbox:
  37. """A group of messages in a particular place."""
  38. def __init__(self, path, factory=None, create=True):
  39. """Initialize a Mailbox instance."""
  40. self._path = os.path.abspath(os.path.expanduser(path))
  41. self._factory = factory
  42. def add(self, message):
  43. """Add message and return assigned key."""
  44. raise NotImplementedError('Method must be implemented by subclass')
  45. def remove(self, key):
  46. """Remove the keyed message; raise KeyError if it doesn't exist."""
  47. raise NotImplementedError('Method must be implemented by subclass')
  48. def __delitem__(self, key):
  49. self.remove(key)
  50. def discard(self, key):
  51. """If the keyed message exists, remove it."""
  52. try:
  53. self.remove(key)
  54. except KeyError:
  55. pass
  56. def __setitem__(self, key, message):
  57. """Replace the keyed message; raise KeyError if it doesn't exist."""
  58. raise NotImplementedError('Method must be implemented by subclass')
  59. def get(self, key, default=None):
  60. """Return the keyed message, or default if it doesn't exist."""
  61. try:
  62. return self.__getitem__(key)
  63. except KeyError:
  64. return default
  65. def __getitem__(self, key):
  66. """Return the keyed message; raise KeyError if it doesn't exist."""
  67. if not self._factory:
  68. return self.get_message(key)
  69. else:
  70. return self._factory(self.get_file(key))
  71. def get_message(self, key):
  72. """Return a Message representation or raise a KeyError."""
  73. raise NotImplementedError('Method must be implemented by subclass')
  74. def get_string(self, key):
  75. """Return a string representation or raise a KeyError."""
  76. raise NotImplementedError('Method must be implemented by subclass')
  77. def get_file(self, key):
  78. """Return a file-like representation or raise a KeyError."""
  79. raise NotImplementedError('Method must be implemented by subclass')
  80. def iterkeys(self):
  81. """Return an iterator over keys."""
  82. raise NotImplementedError('Method must be implemented by subclass')
  83. def keys(self):
  84. """Return a list of keys."""
  85. return list(self.iterkeys())
  86. def itervalues(self):
  87. """Return an iterator over all messages."""
  88. for key in self.iterkeys():
  89. try:
  90. value = self[key]
  91. except KeyError:
  92. continue
  93. yield value
  94. def __iter__(self):
  95. return self.itervalues()
  96. def values(self):
  97. """Return a list of messages. Memory intensive."""
  98. return list(self.itervalues())
  99. def iteritems(self):
  100. """Return an iterator over (key, message) tuples."""
  101. for key in self.iterkeys():
  102. try:
  103. value = self[key]
  104. except KeyError:
  105. continue
  106. yield (key, value)
  107. def items(self):
  108. """Return a list of (key, message) tuples. Memory intensive."""
  109. return list(self.iteritems())
  110. def has_key(self, key):
  111. """Return True if the keyed message exists, False otherwise."""
  112. raise NotImplementedError('Method must be implemented by subclass')
  113. def __contains__(self, key):
  114. return self.has_key(key)
  115. def __len__(self):
  116. """Return a count of messages in the mailbox."""
  117. raise NotImplementedError('Method must be implemented by subclass')
  118. def clear(self):
  119. """Delete all messages."""
  120. for key in self.iterkeys():
  121. self.discard(key)
  122. def pop(self, key, default=None):
  123. """Delete the keyed message and return it, or default."""
  124. try:
  125. result = self[key]
  126. except KeyError:
  127. return default
  128. self.discard(key)
  129. return result
  130. def popitem(self):
  131. """Delete an arbitrary (key, message) pair and return it."""
  132. for key in self.iterkeys():
  133. return (key, self.pop(key)) # This is only run once.
  134. else:
  135. raise KeyError('No messages in mailbox')
  136. def update(self, arg=None):
  137. """Change the messages that correspond to certain keys."""
  138. if hasattr(arg, 'iteritems'):
  139. source = arg.iteritems()
  140. elif hasattr(arg, 'items'):
  141. source = arg.items()
  142. else:
  143. source = arg
  144. bad_key = False
  145. for key, message in source:
  146. try:
  147. self[key] = message
  148. except KeyError:
  149. bad_key = True
  150. if bad_key:
  151. raise KeyError('No message with key(s)')
  152. def flush(self):
  153. """Write any pending changes to the disk."""
  154. raise NotImplementedError('Method must be implemented by subclass')
  155. def lock(self):
  156. """Lock the mailbox."""
  157. raise NotImplementedError('Method must be implemented by subclass')
  158. def unlock(self):
  159. """Unlock the mailbox if it is locked."""
  160. raise NotImplementedError('Method must be implemented by subclass')
  161. def close(self):
  162. """Flush and close the mailbox."""
  163. raise NotImplementedError('Method must be implemented by subclass')
  164. def _dump_message(self, message, target, mangle_from_=False):
  165. # Most files are opened in binary mode to allow predictable seeking.
  166. # To get native line endings on disk, the user-friendly \n line endings
  167. # used in strings and by email.Message are translated here.
  168. """Dump message contents to target file."""
  169. if isinstance(message, email.message.Message):
  170. buffer = StringIO.StringIO()
  171. gen = email.generator.Generator(buffer, mangle_from_, 0)
  172. gen.flatten(message)
  173. buffer.seek(0)
  174. target.write(buffer.read().replace('\n', os.linesep))
  175. elif isinstance(message, str):
  176. if mangle_from_:
  177. message = message.replace('\nFrom ', '\n>From ')
  178. message = message.replace('\n', os.linesep)
  179. target.write(message)
  180. elif hasattr(message, 'read'):
  181. while True:
  182. line = message.readline()
  183. if line == '':
  184. break
  185. if mangle_from_ and line.startswith('From '):
  186. line = '>From ' + line[5:]
  187. line = line.replace('\n', os.linesep)
  188. target.write(line)
  189. else:
  190. raise TypeError('Invalid message type: %s' % type(message))
  191. class Maildir(Mailbox):
  192. """A qmail-style Maildir mailbox."""
  193. colon = ':'
  194. def __init__(self, dirname, factory=rfc822.Message, create=True):
  195. """Initialize a Maildir instance."""
  196. Mailbox.__init__(self, dirname, factory, create)
  197. self._paths = {
  198. 'tmp': os.path.join(self._path, 'tmp'),
  199. 'new': os.path.join(self._path, 'new'),
  200. 'cur': os.path.join(self._path, 'cur'),
  201. }
  202. if not os.path.exists(self._path):
  203. if create:
  204. os.mkdir(self._path, 0700)
  205. for path in self._paths.values():
  206. os.mkdir(path, 0o700)
  207. else:
  208. raise NoSuchMailboxError(self._path)
  209. self._toc = {}
  210. self._toc_mtimes = {}
  211. for subdir in ('cur', 'new'):
  212. self._toc_mtimes[subdir] = os.path.getmtime(self._paths[subdir])
  213. self._last_read = time.time() # Records last time we read cur/new
  214. self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing
  215. def add(self, message):
  216. """Add message and return assigned key."""
  217. tmp_file = self._create_tmp()
  218. try:
  219. self._dump_message(message, tmp_file)
  220. except BaseException:
  221. tmp_file.close()
  222. os.remove(tmp_file.name)
  223. raise
  224. _sync_close(tmp_file)
  225. if isinstance(message, MaildirMessage):
  226. subdir = message.get_subdir()
  227. suffix = self.colon + message.get_info()
  228. if suffix == self.colon:
  229. suffix = ''
  230. else:
  231. subdir = 'new'
  232. suffix = ''
  233. uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
  234. dest = os.path.join(self._path, subdir, uniq + suffix)
  235. try:
  236. if hasattr(os, 'link'):
  237. os.link(tmp_file.name, dest)
  238. os.remove(tmp_file.name)
  239. else:
  240. os.rename(tmp_file.name, dest)
  241. except OSError, e:
  242. os.remove(tmp_file.name)
  243. if e.errno == errno.EEXIST:
  244. raise ExternalClashError('Name clash with existing message: %s'
  245. % dest)
  246. else:
  247. raise
  248. if isinstance(message, MaildirMessage):
  249. os.utime(dest, (os.path.getatime(dest), message.get_date()))
  250. return uniq
  251. def remove(self, key):
  252. """Remove the keyed message; raise KeyError if it doesn't exist."""
  253. os.remove(os.path.join(self._path, self._lookup(key)))
  254. def discard(self, key):
  255. """If the keyed message exists, remove it."""
  256. # This overrides an inapplicable implementation in the superclass.
  257. try:
  258. self.remove(key)
  259. except KeyError:
  260. pass
  261. except OSError, e:
  262. if e.errno != errno.ENOENT:
  263. raise
  264. def __setitem__(self, key, message):
  265. """Replace the keyed message; raise KeyError if it doesn't exist."""
  266. old_subpath = self._lookup(key)
  267. temp_key = self.add(message)
  268. temp_subpath = self._lookup(temp_key)
  269. if isinstance(message, MaildirMessage):
  270. # temp's subdir and suffix were specified by message.
  271. dominant_subpath = temp_subpath
  272. else:
  273. # temp's subdir and suffix were defaults from add().
  274. dominant_subpath = old_subpath
  275. subdir = os.path.dirname(dominant_subpath)
  276. if self.colon in dominant_subpath:
  277. suffix = self.colon + dominant_subpath.split(self.colon)[-1]
  278. else:
  279. suffix = ''
  280. self.discard(key)
  281. new_path = os.path.join(self._path, subdir, key + suffix)
  282. os.rename(os.path.join(self._path, temp_subpath), new_path)
  283. if isinstance(message, MaildirMessage):
  284. os.utime(new_path, (os.path.getatime(new_path),
  285. message.get_date()))
  286. def get_message(self, key):
  287. """Return a Message representation or raise a KeyError."""
  288. subpath = self._lookup(key)
  289. f = open(os.path.join(self._path, subpath), 'r')
  290. try:
  291. if self._factory:
  292. msg = self._factory(f)
  293. else:
  294. msg = MaildirMessage(f)
  295. finally:
  296. f.close()
  297. subdir, name = os.path.split(subpath)
  298. msg.set_subdir(subdir)
  299. if self.colon in name:
  300. msg.set_info(name.split(self.colon)[-1])
  301. msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
  302. return msg
  303. def get_string(self, key):
  304. """Return a string representation or raise a KeyError."""
  305. f = open(os.path.join(self._path, self._lookup(key)), 'r')
  306. try:
  307. return f.read()
  308. finally:
  309. f.close()
  310. def get_file(self, key):
  311. """Return a file-like representation or raise a KeyError."""
  312. f = open(os.path.join(self._path, self._lookup(key)), 'rb')
  313. return _ProxyFile(f)
  314. def iterkeys(self):
  315. """Return an iterator over keys."""
  316. self._refresh()
  317. for key in self._toc:
  318. try:
  319. self._lookup(key)
  320. except KeyError:
  321. continue
  322. yield key
  323. def has_key(self, key):
  324. """Return True if the keyed message exists, False otherwise."""
  325. self._refresh()
  326. return key in self._toc
  327. def __len__(self):
  328. """Return a count of messages in the mailbox."""
  329. self._refresh()
  330. return len(self._toc)
  331. def flush(self):
  332. """Write any pending changes to disk."""
  333. # Maildir changes are always written immediately, so there's nothing
  334. # to do.
  335. pass
  336. def lock(self):
  337. """Lock the mailbox."""
  338. return
  339. def unlock(self):
  340. """Unlock the mailbox if it is locked."""
  341. return
  342. def close(self):
  343. """Flush and close the mailbox."""
  344. return
  345. def list_folders(self):
  346. """Return a list of folder names."""
  347. result = []
  348. for entry in os.listdir(self._path):
  349. if len(entry) > 1 and entry[0] == '.' and \
  350. os.path.isdir(os.path.join(self._path, entry)):
  351. result.append(entry[1:])
  352. return result
  353. def get_folder(self, folder):
  354. """Return a Maildir instance for the named folder."""
  355. return Maildir(os.path.join(self._path, '.' + folder),
  356. factory=self._factory,
  357. create=False)
  358. def add_folder(self, folder):
  359. """Create a folder and return a Maildir instance representing it."""
  360. path = os.path.join(self._path, '.' + folder)
  361. result = Maildir(path, factory=self._factory)
  362. maildirfolder_path = os.path.join(path, 'maildirfolder')
  363. if not os.path.exists(maildirfolder_path):
  364. os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY,
  365. 0666))
  366. return result
  367. def remove_folder(self, folder):
  368. """Delete the named folder, which must be empty."""
  369. path = os.path.join(self._path, '.' + folder)
  370. for entry in os.listdir(os.path.join(path, 'new')) + \
  371. os.listdir(os.path.join(path, 'cur')):
  372. if len(entry) < 1 or entry[0] != '.':
  373. raise NotEmptyError('Folder contains message(s): %s' % folder)
  374. for entry in os.listdir(path):
  375. if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
  376. os.path.isdir(os.path.join(path, entry)):
  377. raise NotEmptyError("Folder contains subdirectory '%s': %s" %
  378. (folder, entry))
  379. for root, dirs, files in os.walk(path, topdown=False):
  380. for entry in files:
  381. os.remove(os.path.join(root, entry))
  382. for entry in dirs:
  383. os.rmdir(os.path.join(root, entry))
  384. os.rmdir(path)
  385. def clean(self):
  386. """Delete old files in "tmp"."""
  387. now = time.time()
  388. for entry in os.listdir(os.path.join(self._path, 'tmp')):
  389. path = os.path.join(self._path, 'tmp', entry)
  390. if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
  391. os.remove(path)
  392. _count = 1 # This is used to generate unique file names.
  393. def _create_tmp(self):
  394. """Create a file in the tmp subdirectory and open and return it."""
  395. now = time.time()
  396. hostname = socket.gethostname()
  397. if '/' in hostname:
  398. hostname = hostname.replace('/', r'\057')
  399. if ':' in hostname:
  400. hostname = hostname.replace(':', r'\072')
  401. uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
  402. Maildir._count, hostname)
  403. path = os.path.join(self._path, 'tmp', uniq)
  404. try:
  405. os.stat(path)
  406. except OSError, e:
  407. if e.errno == errno.ENOENT:
  408. Maildir._count += 1
  409. try:
  410. return _create_carefully(path)
  411. except OSError, e:
  412. if e.errno != errno.EEXIST:
  413. raise
  414. else:
  415. raise
  416. # Fall through to here if stat succeeded or open raised EEXIST.
  417. raise ExternalClashError('Name clash prevented file creation: %s' %
  418. path)
  419. def _refresh(self):
  420. """Update table of contents mapping."""
  421. # If it has been less than two seconds since the last _refresh() call,
  422. # we have to unconditionally re-read the mailbox just in case it has
  423. # been modified, because os.path.mtime() has a 2 sec resolution in the
  424. # most common worst case (FAT) and a 1 sec resolution typically. This
  425. # results in a few unnecessary re-reads when _refresh() is called
  426. # multiple times in that interval, but once the clock ticks over, we
  427. # will only re-read as needed. Because the filesystem might be being
  428. # served by an independent system with its own clock, we record and
  429. # compare with the mtimes from the filesystem. Because the other
  430. # system's clock might be skewing relative to our clock, we add an
  431. # extra delta to our wait. The default is one tenth second, but is an
  432. # instance variable and so can be adjusted if dealing with a
  433. # particularly skewed or irregular system.
  434. if time.time() - self._last_read > 2 + self._skewfactor:
  435. refresh = False
  436. for subdir in self._toc_mtimes:
  437. mtime = os.path.getmtime(self._paths[subdir])
  438. if mtime > self._toc_mtimes[subdir]:
  439. refresh = True
  440. self._toc_mtimes[subdir] = mtime
  441. if not refresh:
  442. return
  443. # Refresh toc
  444. self._toc = {}
  445. for subdir in self._toc_mtimes:
  446. path = self._paths[subdir]
  447. for entry in os.listdir(path):
  448. p = os.path.join(path, entry)
  449. if os.path.isdir(p):
  450. continue
  451. uniq = entry.split(self.colon)[0]
  452. self._toc[uniq] = os.path.join(subdir, entry)
  453. self._last_read = time.time()
  454. def _lookup(self, key):
  455. """Use TOC to return subpath for given key, or raise a KeyError."""
  456. try:
  457. if os.path.exists(os.path.join(self._path, self._toc[key])):
  458. return self._toc[key]
  459. except KeyError:
  460. pass
  461. self._refresh()
  462. try:
  463. return self._toc[key]
  464. except KeyError:
  465. raise KeyError('No message with key: %s' % key)
  466. # This method is for backward compatibility only.
  467. def next(self):
  468. """Return the next message in a one-time iteration."""
  469. if not hasattr(self, '_onetime_keys'):
  470. self._onetime_keys = self.iterkeys()
  471. while True:
  472. try:
  473. return self[self._onetime_keys.next()]
  474. except StopIteration:
  475. return None
  476. except KeyError:
  477. continue
  478. class _singlefileMailbox(Mailbox):
  479. """A single-file mailbox."""
  480. def __init__(self, path, factory=None, create=True):
  481. """Initialize a single-file mailbox."""
  482. Mailbox.__init__(self, path, factory, create)
  483. try:
  484. f = open(self._path, 'rb+')
  485. except IOError, e:
  486. if e.errno == errno.ENOENT:
  487. if create:
  488. f = open(self._path, 'wb+')
  489. else:
  490. raise NoSuchMailboxError(self._path)
  491. elif e.errno in (errno.EACCES, errno.EROFS):
  492. f = open(self._path, 'rb')
  493. else:
  494. raise
  495. self._file = f
  496. self._toc = None
  497. self._next_key = 0
  498. self._pending = False # No changes require rewriting the file.
  499. self._locked = False
  500. self._file_length = None # Used to record mailbox size
  501. def add(self, message):
  502. """Add message and return assigned key."""
  503. self._lookup()
  504. self._toc[self._next_key] = self._append_message(message)
  505. self._next_key += 1
  506. self._pending = True
  507. return self._next_key - 1
  508. def remove(self, key):
  509. """Remove the keyed message; raise KeyError if it doesn't exist."""
  510. self._lookup(key)
  511. del self._toc[key]
  512. self._pending = True
  513. def __setitem__(self, key, message):
  514. """Replace the keyed message; raise KeyError if it doesn't exist."""
  515. self._lookup(key)
  516. self._toc[key] = self._append_message(message)
  517. self._pending = True
  518. def iterkeys(self):
  519. """Return an iterator over keys."""
  520. self._lookup()
  521. for key in self._toc.keys():
  522. yield key
  523. def has_key(self, key):
  524. """Return True if the keyed message exists, False otherwise."""
  525. self._lookup()
  526. return key in self._toc
  527. def __len__(self):
  528. """Return a count of messages in the mailbox."""
  529. self._lookup()
  530. return len(self._toc)
  531. def lock(self):
  532. """Lock the mailbox."""
  533. if not self._locked:
  534. _lock_file(self._file)
  535. self._locked = True
  536. def unlock(self):
  537. """Unlock the mailbox if it is locked."""
  538. if self._locked:
  539. _unlock_file(self._file)
  540. self._locked = False
  541. def flush(self):
  542. """Write any pending changes to disk."""
  543. if not self._pending:
  544. return
  545. # In order to be writing anything out at all, self._toc must
  546. # already have been generated (and presumably has been modified
  547. # by adding or deleting an item).
  548. assert self._toc is not None
  549. # Check length of self._file; if it's changed, some other process
  550. # has modified the mailbox since we scanned it.
  551. self._file.seek(0, 2)
  552. cur_len = self._file.tell()
  553. if cur_len != self._file_length:
  554. raise ExternalClashError('Size of mailbox file changed '
  555. '(expected %i, found %i)' %
  556. (self._file_length, cur_len))
  557. new_file = _create_temporary(self._path)
  558. try:
  559. new_toc = {}
  560. self._pre_mailbox_hook(new_file)
  561. for key in sorted(self._toc.keys()):
  562. start, stop = self._toc[key]
  563. self._file.seek(start)
  564. self._pre_message_hook(new_file)
  565. new_start = new_file.tell()
  566. while True:
  567. buffer = self._file.read(min(4096,
  568. stop - self._file.tell()))
  569. if buffer == '':
  570. break
  571. new_file.write(buffer)
  572. new_toc[key] = (new_start, new_file.tell())
  573. self._post_message_hook(new_file)
  574. except:
  575. new_file.close()
  576. os.remove(new_file.name)
  577. raise
  578. _sync_close(new_file)
  579. # self._file is about to get replaced, so no need to sync.
  580. self._file.close()
  581. try:
  582. os.rename(new_file.name, self._path)
  583. except OSError, e:
  584. if e.errno == errno.EEXIST or \
  585. (os.name == 'os2' and e.errno == errno.EACCES):
  586. os.remove(self._path)
  587. os.rename(new_file.name, self._path)
  588. else:
  589. raise
  590. self._file = open(self._path, 'rb+')
  591. self._toc = new_toc
  592. self._pending = False
  593. if self._locked:
  594. _lock_file(self._file, dotlock=False)
  595. def _pre_mailbox_hook(self, f):
  596. """Called before writing the mailbox to file f."""
  597. return
  598. def _pre_message_hook(self, f):
  599. """Called before writing each message to file f."""
  600. return
  601. def _post_message_hook(self, f):
  602. """Called after writing each message to file f."""
  603. return
  604. def close(self):
  605. """Flush and close the mailbox."""
  606. self.flush()
  607. if self._locked:
  608. self.unlock()
  609. self._file.close() # Sync has been done by self.flush() above.
  610. def _lookup(self, key=None):
  611. """Return (start, stop) or raise KeyError."""
  612. if self._toc is None:
  613. self._generate_toc()
  614. if key is not None:
  615. try:
  616. return self._toc[key]
  617. except KeyError:
  618. raise KeyError('No message with key: %s' % key)
  619. def _append_message(self, message):
  620. """Append message to mailbox and return (start, stop) offsets."""
  621. self._file.seek(0, 2)
  622. before = self._file.tell()
  623. try:
  624. self._pre_message_hook(self._file)
  625. offsets = self._install_message(message)
  626. self._post_message_hook(self._file)
  627. except BaseException:
  628. self._file.truncate(before)
  629. raise
  630. self._file.flush()
  631. self._file_length = self._file.tell() # Record current length of mailbox
  632. return offsets
  633. class _mboxMMDF(_singlefileMailbox):
  634. """An mbox or MMDF mailbox."""
  635. _mangle_from_ = True
  636. def get_message(self, key):
  637. """Return a Message representation or raise a KeyError."""
  638. start, stop = self._lookup(key)
  639. self._file.seek(start)
  640. from_line = self._file.readline().replace(os.linesep, '')
  641. string = self._file.read(stop - self._file.tell())
  642. msg = self._message_factory(string.replace(os.linesep, '\n'))
  643. msg.set_from(from_line[5:])
  644. return msg
  645. def get_string(self, key, from_=False):
  646. """Return a string representation or raise a KeyError."""
  647. start, stop = self._lookup(key)
  648. self._file.seek(start)
  649. if not from_:
  650. self._file.readline()
  651. string = self._file.read(stop - self._file.tell())
  652. return string.replace(os.linesep, '\n')
  653. def get_file(self, key, from_=False):
  654. """Return a file-like representation or raise a KeyError."""
  655. start, stop = self._lookup(key)
  656. self._file.seek(start)
  657. if not from_:
  658. self._file.readline()
  659. return _PartialFile(self._file, self._file.tell(), stop)
  660. def _install_message(self, message):
  661. """Format a message and blindly write to self._file."""
  662. from_line = None
  663. if isinstance(message, str) and message.startswith('From '):
  664. newline = message.find('\n')
  665. if newline != -1:
  666. from_line = message[:newline]
  667. message = message[newline + 1:]
  668. else:
  669. from_line = message
  670. message = ''
  671. elif isinstance(message, _mboxMMDFMessage):
  672. from_line = 'From ' + message.get_from()
  673. elif isinstance(message, email.message.Message):
  674. from_line = message.get_unixfrom() # May be None.
  675. if from_line is None:
  676. from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
  677. start = self._file.tell()
  678. self._file.write(from_line + os.linesep)
  679. self._dump_message(message, self._file, self._mangle_from_)
  680. stop = self._file.tell()
  681. return (start, stop)
  682. class mbox(_mboxMMDF):
  683. """A classic mbox mailbox."""
  684. _mangle_from_ = True
  685. def __init__(self, path, factory=None, create=True):
  686. """Initialize an mbox mailbox."""
  687. self._message_factory = mboxMessage
  688. _mboxMMDF.__init__(self, path, factory, create)
  689. def _pre_message_hook(self, f):
  690. """Called before writing each message to file f."""
  691. if f.tell() != 0:
  692. f.write(os.linesep)
  693. def _generate_toc(self):
  694. """Generate key-to-(start, stop) table of contents."""
  695. starts, stops = [], []
  696. self._file.seek(0)
  697. while True:
  698. line_pos = self._file.tell()
  699. line = self._file.readline()
  700. if line.startswith('From '):
  701. if len(stops) < len(starts):
  702. stops.append(line_pos - len(os.linesep))
  703. starts.append(line_pos)
  704. elif line == '':
  705. stops.append(line_pos)
  706. break
  707. self._toc = dict(enumerate(zip(starts, stops)))
  708. self._next_key = len(self._toc)
  709. self._file_length = self._file.tell()
  710. class MMDF(_mboxMMDF):
  711. """An MMDF mailbox."""
  712. def __init__(self, path, factory=None, create=True):
  713. """Initialize an MMDF mailbox."""
  714. self._message_factory = MMDFMessage
  715. _mboxMMDF.__init__(self, path, factory, create)
  716. def _pre_message_hook(self, f):
  717. """Called before writing each message to file f."""
  718. f.write('\001\001\001\001' + os.linesep)
  719. def _post_message_hook(self, f):
  720. """Called after writing each message to file f."""
  721. f.write(os.linesep + '\001\001\001\001' + os.linesep)
  722. def _generate_toc(self):
  723. """Generate key-to-(start, stop) table of contents."""
  724. starts, stops = [], []
  725. self._file.seek(0)
  726. next_pos = 0
  727. while True:
  728. line_pos = next_pos
  729. line = self._file.readline()
  730. next_pos = self._file.tell()
  731. if line.startswith('\001\001\001\001' + os.linesep):
  732. starts.append(next_pos)
  733. while True:
  734. line_pos = next_pos
  735. line = self._file.readline()
  736. next_pos = self._file.tell()
  737. if line == '\001\001\001\001' + os.linesep:
  738. stops.append(line_pos - len(os.linesep))
  739. break
  740. elif line == '':
  741. stops.append(line_pos)
  742. break
  743. elif line == '':
  744. break
  745. self._toc = dict(enumerate(zip(starts, stops)))
  746. self._next_key = len(self._toc)
  747. self._file.seek(0, 2)
  748. self._file_length = self._file.tell()
  749. class MH(Mailbox):
  750. """An MH mailbox."""
  751. def __init__(self, path, factory=None, create=True):
  752. """Initialize an MH instance."""
  753. Mailbox.__init__(self, path, factory, create)
  754. if not os.path.exists(self._path):
  755. if create:
  756. os.mkdir(self._path, 0700)
  757. os.close(os.open(os.path.join(self._path, '.mh_sequences'),
  758. os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600))
  759. else:
  760. raise NoSuchMailboxError(self._path)
  761. self._locked = False
  762. def add(self, message):
  763. """Add message and return assigned key."""
  764. keys = self.keys()
  765. if len(keys) == 0:
  766. new_key = 1
  767. else:
  768. new_key = max(keys) + 1
  769. new_path = os.path.join(self._path, str(new_key))
  770. f = _create_carefully(new_path)
  771. closed = False
  772. try:
  773. if self._locked:
  774. _lock_file(f)
  775. try:
  776. try:
  777. self._dump_message(message, f)
  778. except BaseException:
  779. # Unlock and close so it can be deleted on Windows
  780. if self._locked:
  781. _unlock_file(f)
  782. _sync_close(f)
  783. closed = True
  784. os.remove(new_path)
  785. raise
  786. if isinstance(message, MHMessage):
  787. self._dump_sequences(message, new_key)
  788. finally:
  789. if self._locked:
  790. _unlock_file(f)
  791. finally:
  792. if not closed:
  793. _sync_close(f)
  794. return new_key
  795. def remove(self, key):
  796. """Remove the keyed message; raise KeyError if it doesn't exist."""
  797. path = os.path.join(self._path, str(key))
  798. try:
  799. f = open(path, 'rb+')
  800. except IOError, e:
  801. if e.errno == errno.ENOENT:
  802. raise KeyError('No message with key: %s' % key)
  803. else:
  804. raise
  805. else:
  806. f.close()
  807. os.remove(path)
  808. def __setitem__(self, key, message):
  809. """Replace the keyed message; raise KeyError if it doesn't exist."""
  810. path = os.path.join(self._path, str(key))
  811. try:
  812. f = open(path, 'rb+')
  813. except IOError, e:
  814. if e.errno == errno.ENOENT:
  815. raise KeyError('No message with key: %s' % key)
  816. else:
  817. raise
  818. try:
  819. if self._locked:
  820. _lock_file(f)
  821. try:
  822. os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
  823. self._dump_message(message, f)
  824. if isinstance(message, MHMessage):
  825. self._dump_sequences(message, key)
  826. finally:
  827. if self._locked:
  828. _unlock_file(f)
  829. finally:
  830. _sync_close(f)
  831. def get_message(self, key):
  832. """Return a Message representation or raise a KeyError."""
  833. try:
  834. if self._locked:
  835. f = open(os.path.join(self._path, str(key)), 'r+')
  836. else:
  837. f = open(os.path.join(self._path, str(key)), 'r')
  838. except IOError, e:
  839. if e.errno == errno.ENOENT:
  840. raise KeyError('No message with key: %s' % key)
  841. else:
  842. raise
  843. try:
  844. if self._locked:
  845. _lock_file(f)
  846. try:
  847. msg = MHMessage(f)
  848. finally:
  849. if self._locked:
  850. _unlock_file(f)
  851. finally:
  852. f.close()
  853. for name, key_list in self.get_sequences().iteritems():
  854. if key in key_list:
  855. msg.add_sequence(name)
  856. return msg
  857. def get_string(self, key):
  858. """Return a string representation or raise a KeyError."""
  859. try:
  860. if self._locked:
  861. f = open(os.path.join(self._path, str(key)), 'r+')
  862. else:
  863. f = open(os.path.join(self._path, str(key)), 'r')
  864. except IOError, e:
  865. if e.errno == errno.ENOENT:
  866. raise KeyError('No message with key: %s' % key)
  867. else:
  868. raise
  869. try:
  870. if self._locked:
  871. _lock_file(f)
  872. try:
  873. return f.read()
  874. finally:
  875. if self._locked:
  876. _unlock_file(f)
  877. finally:
  878. f.close()
  879. def get_file(self, key):
  880. """Return a file-like representation or raise a KeyError."""
  881. try:
  882. f = open(os.path.join(self._path, str(key)), 'rb')
  883. except IOError, e:
  884. if e.errno == errno.ENOENT:
  885. raise KeyError('No message with key: %s' % key)
  886. else:
  887. raise
  888. return _ProxyFile(f)
  889. def iterkeys(self):
  890. """Return an iterator over keys."""
  891. return iter(sorted(int(entry) for entry in os.listdir(self._path)
  892. if entry.isdigit()))
  893. def has_key(self, key):
  894. """Return True if the keyed message exists, False otherwise."""
  895. return os.path.exists(os.path.join(self._path, str(key)))
  896. def __len__(self):
  897. """Return a count of messages in the mailbox."""
  898. return len(list(self.iterkeys()))
  899. def lock(self):
  900. """Lock the mailbox."""
  901. if not self._locked:
  902. self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
  903. _lock_file(self._file)
  904. self._locked = True
  905. def unlock(self):
  906. """Unlock the mailbox if it is locked."""
  907. if self._locked:
  908. _unlock_file(self._file)
  909. _sync_close(self._file)
  910. del self._file
  911. self._locked = False
  912. def flush(self):
  913. """Write any pending changes to the disk."""
  914. return
  915. def close(self):
  916. """Flush and close the mailbox."""
  917. if self._locked:
  918. self.unlock()
  919. def list_folders(self):
  920. """Return a list of folder names."""
  921. result = []
  922. for entry in os.listdir(self._path):
  923. if os.path.isdir(os.path.join(self._path, entry)):
  924. result.append(entry)
  925. return result
  926. def get_folder(self, folder):
  927. """Return an MH instance for the named folder."""
  928. return MH(os.path.join(self._path, folder),
  929. factory=self._factory, create=False)
  930. def add_folder(self, folder):
  931. """Create a folder and return an MH instance representing it."""
  932. return MH(os.path.join(self._path, folder),
  933. factory=self._factory)
  934. def remove_folder(self, folder):
  935. """Delete the named folder, which must be empty."""
  936. path = os.path.join(self._path, folder)
  937. entries = os.listdir(path)
  938. if entries == ['.mh_sequences']:
  939. os.remove(os.path.join(path, '.mh_sequences'))
  940. elif entries == []:
  941. pass
  942. else:
  943. raise NotEmptyError('Folder not empty: %s' % self._path)
  944. os.rmdir(path)
  945. def get_sequences(self):
  946. """Return a name-to-key-list dictionary to define each sequence."""
  947. results = {}
  948. f = open(os.path.join(self._path, '.mh_sequences'), 'r')
  949. try:
  950. all_keys = set(self.keys())
  951. for line in f:
  952. try:
  953. name, contents = line.split(':')
  954. keys = set()
  955. for spec in contents.split():
  956. if spec.isdigit():
  957. keys.add(int(spec))
  958. else:
  959. start, stop = (int(x) for x in spec.split('-'))
  960. keys.update(range(start, stop + 1))
  961. results[name] = [key for key in sorted(keys) \
  962. if key in all_keys]
  963. if len(results[name]) == 0:
  964. del results[name]
  965. except ValueError:
  966. raise FormatError('Invalid sequence specification: %s' %
  967. line.rstrip())
  968. finally:
  969. f.close()
  970. return results
  971. def set_sequences(self, sequences):
  972. """Set sequences using the given name-to-key-list dictionary."""
  973. f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
  974. try:
  975. os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
  976. for name, keys in sequences.iteritems():
  977. if len(keys) == 0:
  978. continue
  979. f.write('%s:' % name)
  980. prev = None
  981. completing = False
  982. for key in sorted(set(keys)):
  983. if key - 1 == prev:
  984. if not completing:
  985. completing = True
  986. f.write('-')
  987. elif completing:
  988. completing = False
  989. f.write('%s %s' % (prev, key))
  990. else:
  991. f.write(' %s' % key)
  992. prev = key
  993. if completing:
  994. f.write(str(prev) + '\n')
  995. else:
  996. f.write('\n')
  997. finally:
  998. _sync_close(f)
  999. def pack(self):
  1000. """Re-name messages to eliminate numbering gaps. Invalidates keys."""
  1001. sequences = self.get_sequences()
  1002. prev = 0
  1003. changes = []
  1004. for key in self.iterkeys():
  1005. if key - 1 != prev:
  1006. changes.append((key, prev + 1))
  1007. if hasattr(os, 'link'):
  1008. os.link(os.path.join(self._path, str(key)),
  1009. os.path.join(self._path, str(prev + 1)))
  1010. os.unlink(os.path.join(self._path, str(key)))
  1011. else:
  1012. os.rename(os.path.join(self._path, str(key)),
  1013. os.path.join(self._path, str(prev + 1)))
  1014. prev += 1
  1015. self._next_key = prev + 1
  1016. if len(changes) == 0:
  1017. return
  1018. for name, key_list in sequences.items():
  1019. for old, new in changes:
  1020. if old in key_list:
  1021. key_list[key_list.index(old)] = new
  1022. self.set_sequences(sequences)
  1023. def _dump_sequences(self, message, key):
  1024. """Inspect a new MHMessage and update sequences appropriately."""
  1025. pending_sequences = message.get_sequences()
  1026. all_sequences = self.get_sequences()
  1027. for name, key_list in all_sequences.iteritems():
  1028. if name in pending_sequences:
  1029. key_list.append(key)
  1030. elif key in key_list:
  1031. del key_list[key_list.index(key)]
  1032. for sequence in pending_sequences:
  1033. if sequence not in all_sequences:
  1034. all_sequences[sequence] = [key]
  1035. self.set_sequences(all_sequences)
  1036. class Babyl(_singlefileMailbox):
  1037. """An Rmail-style Babyl mailbox."""
  1038. _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
  1039. 'forwarded', 'edited', 'resent'))
  1040. def __init__(self, path, factory=None, create=True):
  1041. """Initialize a Babyl mailbox."""
  1042. _singlefileMailbox.__init__(self, path, factory, create)
  1043. self._labels = {}
  1044. def add(self, message):
  1045. """Add message and return assigned key."""
  1046. key = _singlefileMailbox.add(self, message)
  1047. if isinstance(message, BabylMessage):
  1048. self._labels[key] = message.get_labels()
  1049. return key
  1050. def remove(self, key):
  1051. """Remove the keyed message; raise KeyError if it doesn't exist."""
  1052. _singlefileMailbox.remove(self, key)
  1053. if key in self._labels:
  1054. del self._labels[key]
  1055. def __setitem__(self, key, message):
  1056. """Replace the keyed message; raise KeyError if it doesn't exist."""
  1057. _singlefileMailbox.__setitem__(self, key, message)
  1058. if isinstance(message, BabylMessage):
  1059. self._labels[key] = message.get_labels()
  1060. def get_message(self, key):
  1061. """Return a Message representation or raise a KeyError."""
  1062. start, stop = self._lookup(key)
  1063. self._file.seek(start)
  1064. self._file.readline() # Skip '1,' line specifying labels.
  1065. original_headers = StringIO.StringIO()
  1066. while True:
  1067. line = self._file.readline()
  1068. if line == '*** EOOH ***' + os.linesep or line == '':
  1069. break
  1070. original_headers.write(line.replace(os.linesep, '\n'))
  1071. visible_headers = StringIO.StringIO()
  1072. while True:
  1073. line = self._file.readline()
  1074. if line == os.linesep or line == '':
  1075. break
  1076. visible_headers.write(line.replace(os.linesep, '\n'))
  1077. body = self._file.read(stop - self._file.tell()).replace(os.linesep,
  1078. '\n')
  1079. msg = BabylMessage(original_headers.getvalue() + body)
  1080. msg.set_visible(visible_headers.getvalue())
  1081. if key in self._labels:
  1082. msg.set_labels(self._labels[key])
  1083. return msg
  1084. def get_string(self, key):
  1085. """Return a string representation or raise a KeyError."""
  1086. start, stop = self._lookup(key)
  1087. self._file.seek(start)
  1088. self._file.readline() # Skip '1,' line specifying labels.
  1089. original_headers = StringIO.StringIO()
  1090. while True:
  1091. line = self._file.readline()
  1092. if line == '*** EOOH ***' + os.linesep or line == '':
  1093. break
  1094. original_headers.write(line.replace(os.linesep, '\n'))
  1095. while True:
  1096. line = self._file.readline()
  1097. if line == os.linesep or line == '':
  1098. break
  1099. return original_headers.getvalue() + \
  1100. self._file.read(stop - self._file.tell()).replace(os.linesep,
  1101. '\n')
  1102. def get_file(self, key):
  1103. """Return a file-like representation or raise a KeyError."""
  1104. return StringIO.StringIO(self.get_string(key).replace('\n',
  1105. os.linesep))
  1106. def get_labels(self):
  1107. """Return a list of user-defined labels in the mailbox."""
  1108. self._lookup()
  1109. labels = set()
  1110. for label_list in self._labels.values():
  1111. labels.update(label_list)
  1112. labels.difference_update(self._special_labels)
  1113. return list(labels)
  1114. def _generate_toc(self):
  1115. """Generate key-to-(start, stop) table of contents."""
  1116. starts, stops = [], []
  1117. self._file.seek(0)
  1118. next_pos = 0
  1119. label_lists = []
  1120. while True:
  1121. line_pos = next_pos
  1122. line = self._file.readline()
  1123. next_pos = self._file.tell()
  1124. if line == '\037\014' + os.linesep:
  1125. if len(stops) < len(starts):
  1126. stops.append(line_pos - len(os.linesep))
  1127. starts.append(next_pos)
  1128. labels = [label.strip() for label
  1129. in self._file.readline()[1:].split(',')
  1130. if label.strip() != '']
  1131. label_lists.append(labels)
  1132. elif line == '\037' or line == '\037' + os.linesep:
  1133. if len(stops) < len(starts):
  1134. stops.append(line_pos - len(os.linesep))
  1135. elif line == '':
  1136. stops.append(line_pos - len(os.linesep))
  1137. break
  1138. self._toc = dict(enumerate(zip(starts, stops)))
  1139. self._labels = dict(enumerate(label_lists))
  1140. self._next_key = len(self._toc)
  1141. self._file.seek(0, 2)
  1142. self._file_length = self._file.tell()
  1143. def _pre_mailbox_hook(self, f):
  1144. """Called before writing the mailbox to file f."""
  1145. f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' %
  1146. (os.linesep, os.linesep, ','.join(self.get_labels()),
  1147. os.linesep))
  1148. def _pre_message_hook(self, f):
  1149. """Called before writing each message to file f."""
  1150. f.write('\014' + os.linesep)
  1151. def _post_message_hook(self, f):
  1152. """Called after writing each message to file f."""
  1153. f.write(os.linesep + '\037')
  1154. def _install_message(self, message):
  1155. """Write message contents and return (start, stop)."""
  1156. start = self._file.tell()
  1157. if isinstance(message, BabylMessage):
  1158. special_labels = []
  1159. labels = []
  1160. for label in message.get_labels():
  1161. if label in self._special_labels:
  1162. special_labels.append(label)
  1163. else:
  1164. labels.append(label)
  1165. self._file.write('1')
  1166. for label in special_labels:
  1167. self._file.write(', ' + label)
  1168. self._file.write(',,')
  1169. for label in labels:
  1170. self._file.write(' ' + label + ',')
  1171. self._file.write(os.linesep)
  1172. else:
  1173. self._file.write('1,,' + os.linesep)
  1174. if isinstance(message, email.message.Message):
  1175. orig_buffer = StringIO.StringIO()
  1176. orig_generator = email.generator.Generator(orig_buffer, False, 0)
  1177. orig_generator.flatten(message)
  1178. orig_buffer.seek(0)
  1179. while True:
  1180. line = orig_buffer.readline()
  1181. self._file.write(line.replace('\n', os.linesep))
  1182. if line == '\n' or line == '':
  1183. break
  1184. self._file.write('*** EOOH ***' + os.linesep)
  1185. if isinstance(message, BabylMessage):
  1186. vis_buffer = StringIO.StringIO()
  1187. vis_generator = email.generator.Generator(vis_buffer, False, 0)
  1188. vis_generator.flatten(message.get_visible())
  1189. while True:
  1190. line = vis_buffer.readline()
  1191. self._file.write(line.replace('\n', os.linesep))
  1192. if line == '\n' or line == '':
  1193. break
  1194. else:
  1195. orig_buffer.seek(0)
  1196. while True:
  1197. line = orig_buffer.readline()
  1198. self._file.write(line.replace('\n', os.linesep))
  1199. if line == '\n' or line == '':
  1200. break
  1201. while True:
  1202. buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
  1203. if buffer == '':
  1204. break
  1205. self._file.write(buffer.replace('\n', os.linesep))
  1206. elif isinstance(message, str):
  1207. body_start = message.find('\n\n') + 2
  1208. if body_start - 2 != -1:
  1209. self._file.write(message[:body_start].replace('\n',
  1210. os.linesep))
  1211. self._file.write('*** EOOH ***' + os.linesep)
  1212. self._file.write(message[:body_start].replace('\n',
  1213. os.linesep))
  1214. self._file.write(message[body_start:].replace('\n',
  1215. os.linesep))
  1216. else:
  1217. self._file.write('*** EOOH ***' + os.linesep + os.linesep)
  1218. self._file.write(message.replace('\n', os.linesep))
  1219. elif hasattr(message, 'readline'):
  1220. original_pos = message.tell()
  1221. first_pass = True
  1222. while True:
  1223. line = message.readline()
  1224. self._file.write(line.replace('\n', os.linesep))
  1225. if line == '\n' or line == '':
  1226. self._file.write('*** EOOH ***' + os.linesep)
  1227. if first_pass:
  1228. first_pass = False
  1229. message.seek(original_pos)
  1230. else:
  1231. break
  1232. while True:
  1233. buffer = message.read(4096) # Buffer size is arbitrary.
  1234. if buffer == '':
  1235. break
  1236. self._file.write(buffer.replace('\n', os.linesep))
  1237. else:
  1238. raise TypeError('Invalid message type: %s' % type(message))
  1239. stop = self._file.tell()
  1240. return (start, stop)
  1241. class Message(email.message.Message):
  1242. """Message with mailbox-format-specific properties."""
  1243. def __init__(self, message=None):
  1244. """Initialize a Message instance."""
  1245. if isinstance(message, email.message.Message):
  1246. self._become_message(copy.deepcopy(message))
  1247. if isinstance(message, Message):
  1248. message._explain_to(self)
  1249. elif isinstance(message, str):
  1250. self._become_message(email.message_from_string(message))
  1251. elif hasattr(message, "read"):
  1252. self._become_message(email.message_from_file(message))
  1253. elif message is None:
  1254. email.message.Message.__init__(self)
  1255. else:
  1256. raise TypeError('Invalid message type: %s' % type(message))
  1257. def _become_message(self, message):
  1258. """Assume the non-format-specific state of message."""
  1259. for name in ('_headers', '_unixfrom', '_payload', '_charset',
  1260. 'preamble', 'epilogue', 'defects', '_default_type'):
  1261. self.__dict__[name] = message.__dict__[name]
  1262. def _explain_to(self, message):
  1263. """Copy format-specific state to message insofar as possible."""
  1264. if isinstance(message, Message):
  1265. return # There's nothing format-specific to explain.
  1266. else:
  1267. raise TypeError('Cannot convert to specified type')
  1268. class MaildirMessage(Message):
  1269. """Message with Maildir-specific properties."""
  1270. def __init__(self, message=None):
  1271. """Initialize a MaildirMessage instance."""
  1272. self._subdir = 'new'
  1273. self._info = ''
  1274. self._date = time.time()
  1275. Message.__init__(self, message)
  1276. def get_subdir(self):
  1277. """Return 'new' or 'cur'."""
  1278. return self._subdir
  1279. def set_subdir(self, subdir):
  1280. """Set subdir to 'new' or 'cur'."""
  1281. if subdir == 'new' or subdir == 'cur':
  1282. self._subdir = subdir
  1283. else:
  1284. raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
  1285. def get_flags(self):
  1286. """Return as a string the flags that are set."""
  1287. if self._info.startswith('2,'):
  1288. return self._info[2:]
  1289. else:
  1290. return ''
  1291. def set_flags(self, flags):
  1292. """Set the given flags and unset all others."""
  1293. self._info = '2,' + ''.join(sorted(flags))
  1294. def add_flag(self, flag):
  1295. """Set the given flag(s) without changing others."""
  1296. self.set_flags(''.join(set(self.get_flags()) | set(flag)))
  1297. def remove_flag(self, flag):
  1298. """Unset the given string flag(s) without changing others."""
  1299. if self.get_flags() != '':
  1300. self.set_flags(''.join(set(self.get_flags()) - set(flag)))
  1301. def get_date(self):
  1302. """Return delivery date of message, in seconds since the epoch."""
  1303. return self._date
  1304. def set_date(self, date):
  1305. """Set delivery date of message, in seconds since the epoch."""
  1306. try:
  1307. self._date = float(date)
  1308. except ValueError:
  1309. raise TypeError("can't convert to float: %s" % date)
  1310. def get_info(self):
  1311. """Get the message's "info" as a string."""
  1312. return self._info
  1313. def set_info(self, info):
  1314. """Set the message's "info" string."""
  1315. if isinstance(info, str):
  1316. self._info = info
  1317. else:
  1318. raise TypeError('info must be a string: %s' % type(info))
  1319. def _explain_to(self, message):
  1320. """Copy Maildir-specific state to message insofar as possible."""
  1321. if isinstance(message, MaildirMessage):
  1322. message.set_flags(self.get_flags())
  1323. message.set_subdir(self.get_subdir())
  1324. message.set_date(self.get_date())
  1325. elif isinstance(message, _mboxMMDFMessage):
  1326. flags = set(self.get_flags())
  1327. if 'S' in flags:
  1328. message.add_flag('R')
  1329. if self.get_subdir() == 'cur':
  1330. message.add_flag('O')
  1331. if 'T' in flags:
  1332. message.add_flag('D')
  1333. if 'F' in flags:
  1334. message.add_flag('F')
  1335. if 'R' in flags:
  1336. message.add_flag('A')
  1337. message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
  1338. elif isinstance(message, MHMessage):
  1339. flags = set(self.get_flags())
  1340. if 'S' not in flags:
  1341. message.add_sequence('unseen')
  1342. if 'R' in flags:
  1343. message.add_sequence('replied')
  1344. if 'F' in flags:
  1345. message.add_sequence('flagged')
  1346. elif isinstance(message, BabylMessage):
  1347. flags = set(self.get_flags())
  1348. if 'S' not in flags:
  1349. message.add_label('unseen')
  1350. if 'T' in flags:
  1351. message.add_label('deleted')
  1352. if 'R' in flags:
  1353. message.add_label('answered')
  1354. if 'P' in flags:
  1355. message.add_label('forwarded')
  1356. elif isinstance(message, Message):
  1357. pass
  1358. else:
  1359. raise TypeError('Cannot convert to specified type: %s' %
  1360. type(message))
  1361. class _mboxMMDFMessage(Message):
  1362. """Message with mbox- or MMDF-specific properties."""
  1363. def __init__(self, message=None):
  1364. """Initialize an mboxMMDFMessage instance."""
  1365. self.set_from('MAILER-DAEMON', True)
  1366. if isinstance(message, email.message.Message):
  1367. unixfrom = message.get_unixfrom()
  1368. if unixfrom is not None and unixfrom.startswith('From '):
  1369. self.set_from(unixfrom[5:])
  1370. Message.__init__(self, message)
  1371. def get_from(self):
  1372. """Return contents of "From " line."""
  1373. return self._from
  1374. def set_from(self, from_, time_=None):
  1375. """Set "From " line, formatting and appending time_ if specified."""
  1376. if time_ is not None:
  1377. if time_ is True:
  1378. time_ = time.gmtime()
  1379. from_ += ' ' + time.asctime(time_)
  1380. self._from = from_
  1381. def get_flags(self):
  1382. """Return as a string the flags that are set."""
  1383. return self.get('Status', '') + self.get('X-Status', '')
  1384. def set_flags(self, flags):
  1385. """Set the given flags and unset all others."""
  1386. flags = set(flags)
  1387. status_flags, xstatus_flags = '', ''
  1388. for flag in ('R', 'O'):
  1389. if flag in flags:
  1390. status_flags += flag
  1391. flags.remove(flag)
  1392. for flag in ('D', 'F', 'A'):
  1393. if flag in flags:
  1394. xstatus_flags += flag
  1395. flags.remove(flag)
  1396. xstatus_flags += ''.join(sorted(flags))
  1397. try:
  1398. self.replace_header('Status', status_flags)
  1399. except KeyError:
  1400. self.add_header('Status', status_flags)
  1401. try:
  1402. self.replace_header('X-Status', xstatus_flags)
  1403. except KeyError:
  1404. self.add_header('X-Status', xstatus_flags)
  1405. def add_flag(self, flag):
  1406. """Set the given flag(s) without changing others."""
  1407. self.set_flags(''.join(set(self.get_flags()) | set(flag)))
  1408. def remove_flag(self, flag):
  1409. """Unset the given string flag(s) without changing others."""
  1410. if 'Status' in self or 'X-Status' in self:
  1411. self.set_flags(''.join(set(self.get_flags()) - set(flag)))
  1412. def _explain_to(self, message):
  1413. """Copy mbox- or MMDF-specific state to message insofar as possible."""
  1414. if isinstance(message, MaildirMessage):
  1415. flags = set(self.get_flags())
  1416. if 'O' in flags:
  1417. message.set_subdir('cur')
  1418. if 'F' in flags:
  1419. message.add_flag('F')
  1420. if 'A' in flags:
  1421. message.add_flag('R')
  1422. if 'R' in flags:
  1423. message.add_flag('S')
  1424. if 'D' in flags:
  1425. message.add_flag('T')
  1426. del message['status']
  1427. del message['x-status']
  1428. maybe_date = ' '.join(self.get_from().split()[-5:])
  1429. try:
  1430. message.set_date(calendar.timegm(time.strptime(maybe_date,
  1431. '%a %b %d %H:%M:%S %Y')))
  1432. except (ValueError, OverflowError):
  1433. pass
  1434. elif isinstance(message, _mboxMMDFMessage):
  1435. message.set_flags(self.get_flags())
  1436. message.set_from(self.get_from())
  1437. elif isinstance(message, MHMessage):
  1438. flags = set(self.get_flags())
  1439. if 'R' not in flags:
  1440. message.add_sequence('unseen')
  1441. if 'A' in flags:
  1442. message.add_sequence('replied')
  1443. if 'F' in flags:
  1444. message.add_sequence('flagged')
  1445. del message['status']
  1446. del message['x-status']
  1447. elif isinstance(message, BabylMessage):
  1448. flags = set(self.get_flags())
  1449. if 'R' not in flags:
  1450. message.add_label('unseen')
  1451. if 'D' in flags:
  1452. message.add_label('deleted')
  1453. if 'A' in flags:
  1454. message.add_label('answered')
  1455. del message['status']
  1456. del message['x-status']
  1457. elif isinstance(message, Message):
  1458. pass
  1459. else:
  1460. raise TypeError('Cannot convert to specified type: %s' %
  1461. type(message))
  1462. class mboxMessage(_mboxMMDFMessage):
  1463. """Message with mbox-specific properties."""
  1464. class MHMessage(Message):
  1465. """Message with MH-specific properties."""
  1466. def __init__(self, message=None):
  1467. """Initialize an MHMessage instance."""
  1468. self._sequences = []
  1469. Message.__init__(self, message)
  1470. def get_sequences(self):
  1471. """Return a list of sequences that include the message."""
  1472. return self._sequences[:]
  1473. def set_sequences(self, sequences):
  1474. """Set the list of sequences that include the message."""
  1475. self._sequences = list(sequences)
  1476. def add_sequence(self, sequence):
  1477. """Add sequence to list of sequences including the message."""
  1478. if isinstance(sequence, str):
  1479. if not sequence in self._sequences:
  1480. self._sequences.append(sequence)
  1481. else:
  1482. raise TypeError('sequence must be a string: %s' % type(sequence))
  1483. def remove_sequence(self, sequence):
  1484. """Remove sequence from the list of sequences including the message."""
  1485. try:
  1486. self._sequences.remove(sequence)
  1487. except ValueError:
  1488. pass
  1489. def _explain_to(self, message):
  1490. """Copy MH-specific state to message insofar as possible."""
  1491. if isinstance(message, MaildirMessage):
  1492. sequences = set(self.get_sequences())
  1493. if 'unseen' in sequences:
  1494. message.set_subdir('cur')
  1495. else:
  1496. message.set_subdir('cur')
  1497. message.add_flag('S')
  1498. if 'flagged' in sequences:
  1499. message.add_flag('F')
  1500. if 'replied' in sequences:
  1501. message.add_flag('R')
  1502. elif isinstance(message, _mboxMMDFMessage):
  1503. sequences = set(self.get_sequences())
  1504. if 'unseen' not in sequences:
  1505. message.add_flag('RO')
  1506. else:
  1507. message.add_flag('O')
  1508. if 'flagged' in sequences:
  1509. message.add_flag('F')
  1510. if 'replied' in sequences:
  1511. message.add_flag('A')
  1512. elif isinstance(message, MHMessage):
  1513. for sequence in self.get_sequences():
  1514. message.add_sequence(sequence)
  1515. elif isinstance(message, BabylMessage):
  1516. sequences = set(self.get_sequences())
  1517. if 'unseen' in sequences:
  1518. message.add_label('unseen')
  1519. if 'replied' in sequences:
  1520. message.add_label('answered')
  1521. elif isinstance(message, Message):
  1522. pass
  1523. else:
  1524. raise TypeError('Cannot convert to specified type: %s' %
  1525. type(message))
  1526. class BabylMessage(Message):
  1527. """Message with Babyl-specific properties."""
  1528. def __init__(self, message=None):
  1529. """Initialize an BabylMessage instance."""
  1530. self._labels = []
  1531. self._visible = Message()
  1532. Message.__init__(self, message)
  1533. def get_labels(self):
  1534. """Return a list of labels on the message."""
  1535. return self._labels[:]
  1536. def set_labels(self, labels):
  1537. """Set the list of labels on the message."""
  1538. self._labels = list(labels)
  1539. def add_label(self, label):
  1540. """Add label to list of labels on the message."""
  1541. if isinstance(label, str):
  1542. if label not in self._labels:
  1543. self._labels.append(label)
  1544. else:
  1545. raise TypeError('label must be a string: %s' % type(label))
  1546. def remove_label(self, label):
  1547. """Remove label from the list of labels on the message."""
  1548. try:
  1549. self._labels.remove(label)
  1550. except ValueError:
  1551. pass
  1552. def get_visible(self):
  1553. """Return a Message representation of visible headers."""
  1554. return Message(self._visible)
  1555. def set_visible(self, visible):
  1556. """Set the Message representation of visible headers."""
  1557. self._visible = Message(visible)
  1558. def update_visible(self):
  1559. """Update and/or sensibly generate a set of visible headers."""
  1560. for header in self._visible.keys():
  1561. if header in self:
  1562. self._visible.replace_header(header, self[header])
  1563. else:
  1564. del self._visible[header]
  1565. for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
  1566. if header in self and header not in self._visible:
  1567. self._visible[header] = self[header]
  1568. def _explain_to(self, message):
  1569. """Copy Babyl-specific state to message insofar as possible."""
  1570. if isinstance(message, MaildirMessage):
  1571. labels = set(self.get_labels())
  1572. if 'unseen' in labels:
  1573. message.set_subdir('cur')
  1574. else:
  1575. message.set_subdir('cur')
  1576. message.add_flag('S')
  1577. if 'forwarded' in labels or 'resent' in labels:
  1578. message.add_flag('P')
  1579. if 'answered' in labels:
  1580. message.add_flag('R')
  1581. if 'deleted' in labels:
  1582. message.add_flag('T')
  1583. elif isinstance(message, _mboxMMDFMessage):
  1584. labels = set(self.get_labels())
  1585. if 'unseen' not in labels:
  1586. message.add_flag('RO')
  1587. else:
  1588. message.add_flag('O')
  1589. if 'deleted' in labels:
  1590. message.add_flag('D')
  1591. if 'answered' in labels:
  1592. message.add_flag('A')
  1593. elif isinstance(message, MHMessage):
  1594. labels = set(self.get_labels())
  1595. if 'unseen' in labels:
  1596. message.add_sequence('unseen')
  1597. if 'answered' in labels:
  1598. message.add_sequence('replied')
  1599. elif isinstance(message, BabylMessage):
  1600. message.set_visible(self.get_visible())
  1601. for label in self.get_labels():
  1602. message.add_label(label)
  1603. elif isinstance(message, Message):
  1604. pass
  1605. else:
  1606. raise TypeError('Cannot convert to specified type: %s' %
  1607. type(message))
  1608. class MMDFMessage(_mboxMMDFMessage):
  1609. """Message with MMDF-specific properties."""
  1610. class _ProxyFile:
  1611. """A read-only wrapper of a file."""
  1612. def __init__(self, f, pos=None):
  1613. """Initialize a _ProxyFile."""
  1614. self._file = f
  1615. if pos is None:
  1616. self._pos = f.tell()
  1617. else:
  1618. self._pos = pos
  1619. def read(self, size=None):
  1620. """Read bytes."""
  1621. return self._read(size, self._file.read)
  1622. def readline(self, size=None):
  1623. """Read a line."""
  1624. return self._read(size, self._file.readline)
  1625. def readlines(self, sizehint=None):
  1626. """Read multiple lines."""
  1627. result = []
  1628. for line in self:
  1629. result.append(line)
  1630. if sizehint is not None:
  1631. sizehint -= len(line)
  1632. if sizehint <= 0:
  1633. break
  1634. return result
  1635. def __iter__(self):
  1636. """Iterate over lines."""
  1637. return iter(self.readline, "")
  1638. def tell(self):
  1639. """Return the position."""
  1640. return self._pos
  1641. def seek(self, offset, whence=0):
  1642. """Change position."""
  1643. if whence == 1:
  1644. self._file.seek(self._pos)
  1645. self._file.seek(offset, whence)
  1646. self._pos = self._file.tell()
  1647. def close(self):
  1648. """Close the file."""
  1649. del self._file
  1650. def _read(self, size, read_method):
  1651. """Read size bytes using read_method."""
  1652. if size is None:
  1653. size = -1
  1654. self._file.seek(self._pos)
  1655. result = read_method(size)
  1656. self._pos = self._file.tell()
  1657. return result
  1658. class _PartialFile(_ProxyFile):
  1659. """A read-only wrapper of part of a file."""
  1660. def __init__(self, f, start=None, stop=None):
  1661. """Initialize a _PartialFile."""
  1662. _ProxyFile.__init__(self, f, start)
  1663. self._start = start
  1664. self._stop = stop
  1665. def tell(self):
  1666. """Return the position with respect to start."""
  1667. return _ProxyFile.tell(self) - self._start
  1668. def seek(self, offset, whence=0):
  1669. """Change position, possibly with respect to start or stop."""
  1670. if whence == 0:
  1671. self._pos = self._start
  1672. whence = 1
  1673. elif whence == 2:
  1674. self._pos = self._stop
  1675. whence = 1
  1676. _ProxyFile.seek(self, offset, whence)
  1677. def _read(self, size, read_method):
  1678. """Read size bytes using read_method, honoring start and stop."""
  1679. remaining = self._stop - self._pos
  1680. if remaining <= 0:
  1681. return ''
  1682. if size is None or size < 0 or size > remaining:
  1683. size = remaining
  1684. return _ProxyFile._read(self, size, read_method)
  1685. def _lock_file(f, dotlock=True):
  1686. """Lock file f using lockf and dot locking."""
  1687. dotlock_done = False
  1688. try:
  1689. if fcntl:
  1690. try:
  1691. fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
  1692. except IOError, e:
  1693. if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
  1694. raise ExternalClashError('lockf: lock unavailable: %s' %
  1695. f.name)
  1696. else:
  1697. raise
  1698. if dotlock:
  1699. try:
  1700. pre_lock = _create_temporary(f.name + '.lock')
  1701. pre_lock.close()
  1702. except IOError, e:
  1703. if e.errno in (errno.EACCES, errno.EROFS):
  1704. return # Without write access, just skip dotlocking.
  1705. else:
  1706. raise
  1707. try:
  1708. if hasattr(os, 'link'):
  1709. os.link(pre_lock.name, f.name + '.lock')
  1710. dotlock_done = True
  1711. os.unlink(pre_lock.name)
  1712. else:
  1713. os.rename(pre_lock.name, f.name + '.lock')
  1714. dotlock_done = True
  1715. except OSError, e:
  1716. if e.errno == errno.EEXIST or \
  1717. (os.name == 'os2' and e.errno == errno.EACCES):
  1718. os.remove(pre_lock.name)
  1719. raise ExternalClashError('dot lock unavailable: %s' %
  1720. f.name)
  1721. else:
  1722. raise
  1723. except:
  1724. if fcntl:
  1725. fcntl.lockf(f, fcntl.LOCK_UN)
  1726. if dotlock_done:
  1727. os.remove(f.name + '.lock')
  1728. raise
  1729. def _unlock_file(f):
  1730. """Unlock file f using lockf and dot locking."""
  1731. if fcntl:
  1732. fcntl.lockf(f, fcntl.LOCK_UN)
  1733. if os.path.exists(f.name + '.lock'):
  1734. os.remove(f.name + '.lock')
  1735. def _create_carefully(path):
  1736. """Create a file if it doesn't exist and open for reading and writing."""
  1737. fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0666)
  1738. try:
  1739. return open(path, 'rb+')
  1740. finally:
  1741. os.close(fd)
  1742. def _create_temporary(path):
  1743. """Create a temp file based on path and open for reading and writing."""
  1744. return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
  1745. socket.gethostname(),
  1746. os.getpid()))
  1747. def _sync_flush(f):
  1748. """Ensure changes to file f are physically on disk."""
  1749. f.flush()
  1750. if hasattr(os, 'fsync'):
  1751. os.fsync(f.fileno())
  1752. def _sync_close(f):
  1753. """Close file f, ensuring all changes are physically on disk."""
  1754. _sync_flush(f)
  1755. f.close()
  1756. ## Start: classes from the original module (for backward compatibility).
  1757. # Note that the Maildir class, whose name is unchanged, itself offers a next()
  1758. # method for backward compatibility.
  1759. class _Mailbox:
  1760. def __init__(self, fp, factory=rfc822.Message):
  1761. self.fp = fp
  1762. self.seekp = 0
  1763. self.factory = factory
  1764. def __iter__(self):
  1765. return iter(self.next, None)
  1766. def next(self):
  1767. while 1:
  1768. self.fp.seek(self.seekp)
  1769. try:
  1770. self._search_start()
  1771. except EOFError:
  1772. self.seekp = self.fp.tell()
  1773. return None
  1774. start = self.fp.tell()
  1775. self._search_end()
  1776. self.seekp = stop = self.fp.tell()
  1777. if start != stop:
  1778. break
  1779. return self.factory(_PartialFile(self.fp, start, stop))
  1780. # Recommended to use PortableUnixMailbox instead!
  1781. class UnixMailbox(_Mailbox):
  1782. def _search_start(self):
  1783. while 1:
  1784. pos = self.fp.tell()
  1785. line = self.fp.readline()
  1786. if not line:
  1787. raise EOFError
  1788. if line[:5] == 'From ' and self._isrealfromline(line):
  1789. self.fp.seek(pos)
  1790. return
  1791. def _search_end(self):
  1792. self.fp.readline() # Throw away header line
  1793. while 1:
  1794. pos = self.fp.tell()
  1795. line = self.fp.readline()
  1796. if not line:
  1797. return
  1798. if line[:5] == 'From ' and self._isrealfromline(line):
  1799. self.fp.seek(pos)
  1800. return
  1801. # An overridable mechanism to test for From-line-ness. You can either
  1802. # specify a different regular expression or define a whole new
  1803. # _isrealfromline() method. Note that this only gets called for lines
  1804. # starting with the 5 characters "From ".
  1805. #
  1806. # BAW: According to
  1807. #http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html
  1808. # the only portable, reliable way to find message delimiters in a BSD (i.e
  1809. # Unix mailbox) style folder is to search for "\n\nFrom .*\n", or at the
  1810. # beginning of the file, "^From .*\n". While _fromlinepattern below seems
  1811. # like a good idea, in practice, there are too many variations for more
  1812. # strict parsing of the line to be completely accurate.
  1813. #
  1814. # _strict_isrealfromline() is the old version which tries to do stricter
  1815. # parsing of the From_ line. _portable_isrealfromline() simply returns
  1816. # true, since it's never called if the line doesn't already start with
  1817. # "From ".
  1818. #
  1819. # This algorithm, and the way it interacts with _search_start() and
  1820. # _search_end() may not be completely correct, because it doesn't check
  1821. # that the two characters preceding "From " are \n\n or the beginning of
  1822. # the file. Fixing this would require a more extensive rewrite than is
  1823. # necessary. For convenience, we've added a PortableUnixMailbox class
  1824. # which does no checking of the format of the 'From' line.
  1825. _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+"
  1826. r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*"
  1827. r"[^\s]*\s*"
  1828. "$")
  1829. _regexp = None
  1830. def _strict_isrealfromline(self, line):
  1831. if not self._regexp:
  1832. import re
  1833. self._regexp = re.compile(self._fromlinepattern)
  1834. return self._regexp.match(line)
  1835. def _portable_isrealfromline(self, line):
  1836. return True
  1837. _isrealfromline = _strict_isrealfromline
  1838. class PortableUnixMailbox(UnixMailbox):
  1839. _isrealfromline = UnixMailbox._portable_isrealfromline
  1840. class MmdfMailbox(_Mailbox):
  1841. def _search_start(self):
  1842. while 1:
  1843. line = self.fp.readline()
  1844. if not line:
  1845. raise EOFError
  1846. if line[:5] == '\001\001\001\001\n':
  1847. return
  1848. def _search_end(self):
  1849. while 1:
  1850. pos = self.fp.tell()
  1851. line = self.fp.readline()
  1852. if not line:
  1853. return
  1854. if line == '\001\001\001\001\n':
  1855. self.fp.seek(pos)
  1856. return
  1857. class MHMailbox:
  1858. def __init__(self, dirname, factory=rfc822.Message):
  1859. import re
  1860. pat = re.compile('^[1-9][0-9]*$')
  1861. self.dirname = dirname
  1862. # the three following lines could be combined into:
  1863. # list = map(long, filter(pat.match, os.listdir(self.dirname)))
  1864. list = os.listdir(self.dirname)
  1865. list = filter(pat.match, list)
  1866. list = map(long, list)
  1867. list.sort()
  1868. # This only works in Python 1.6 or later;
  1869. # before that str() added 'L':
  1870. self.boxes = map(str, list)
  1871. self.boxes.reverse()
  1872. self.factory = factory
  1873. def __iter__(self):
  1874. return iter(self.next, None)
  1875. def next(self):
  1876. if not self.boxes:
  1877. return None
  1878. fn = self.boxes.pop()
  1879. fp = open(os.path.join(self.dirname, fn))
  1880. msg = self.factory(fp)
  1881. try:
  1882. msg._mh_msgno = fn
  1883. except (AttributeError, TypeError):
  1884. pass
  1885. return msg
  1886. class BabylMailbox(_Mailbox):
  1887. def _search_start(self):
  1888. while 1:
  1889. line = self.fp.readline()
  1890. if not line:
  1891. raise EOFError
  1892. if line == '*** EOOH ***\n':
  1893. return
  1894. def _search_end(self):
  1895. while 1:
  1896. pos = self.fp.tell()
  1897. line = self.fp.readline()
  1898. if not line:
  1899. return
  1900. if line == '\037\014\n' or line == '\037':
  1901. self.fp.seek(pos)
  1902. return
  1903. ## End: classes from the original module (for backward compatibility).
  1904. class Error(Exception):
  1905. """Raised for module-specific errors."""
  1906. class NoSuchMailboxError(Error):
  1907. """The specified mailbox does not exist and won't be created."""
  1908. class NotEmptyError(Error):
  1909. """The specified mailbox is not empty and deletion was requested."""
  1910. class ExternalClashError(Error):
  1911. """Another process caused an action to fail."""
  1912. class FormatError(Error):
  1913. """A file appears to have an invalid format."""