Skip to content

Instantly share code, notes, and snippets.

@Alex-Bond
Created October 10, 2023 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alex-Bond/d5fb514e1827fe2802470cccd74ad5fe to your computer and use it in GitHub Desktop.
Save Alex-Bond/d5fb514e1827fe2802470cccd74ad5fe to your computer and use it in GitHub Desktop.
Fixed MboxReader
import email
from email.policy import default
class MboxReader:
def __init__(self, filename):
self.handle = open(filename, 'rb')
assert self.handle.readline().startswith(b'From ')
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.handle.close()
def __iter__(self):
return iter(self.__next__())
def __next__(self):
lines = []
while True:
line = self.handle.readline()
if line == b'' or line.startswith(b'From '):
yield email.message_from_bytes(b''.join(lines), policy=default)
if line == b'':
break
lines = []
continue
if line.startswith(b'>') and line.lstrip(b'>').startswith(b'From '):
line = line[1:]
lines.append(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment