Created
October 10, 2023 03:24
-
-
Save Alex-Bond/d5fb514e1827fe2802470cccd74ad5fe to your computer and use it in GitHub Desktop.
Fixed MboxReader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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