Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fbe63de

Browse files
committed
UnixMailbox: don't be fooled by lines that begin with "From " but
otherwise don't look like headers at all... Also robustify the test code a bit.
1 parent 7e07b38 commit fbe63de

1 file changed

Lines changed: 22 additions & 6 deletions

File tree

Lib/mailbox.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def _search_start(self):
8585
line = self.fp.readline()
8686
if not line:
8787
raise EOFError
88-
if line[:5] == 'From ':
88+
if line[:5] == 'From ' and self._isrealfromline(line):
8989
return
9090

9191
def _search_end(self):
@@ -94,10 +94,26 @@ def _search_end(self):
9494
line = self.fp.readline()
9595
if not line:
9696
return
97-
if line[:5] == 'From ':
97+
if line[:5] == 'From ' and self._isrealfromline(line):
9898
self.fp.seek(pos)
9999
return
100100

101+
# An overridable mechanism to test for From-line-ness.
102+
# You can either specify a different regular expression
103+
# or define a whole new _isrealfromline() method.
104+
# Note that this only gets called for lines starting with
105+
# the 5 characters "From ".
106+
107+
_fromlinepattern = r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" \
108+
r"\d?\d:\d\d:\d\d(\s+[^\s]+)?\s+\d\d\d\d\s*$"
109+
_regexp = None
110+
111+
def _isrealfromline(self, line):
112+
if not self._regexp:
113+
import re
114+
self._regexp = re.compile(self._fromlinepattern)
115+
return self._regexp.match(line)
116+
101117
class MmdfMailbox(_Mailbox):
102118

103119
def _search_start(self):
@@ -190,7 +206,7 @@ def _test():
190206
msgs = []
191207
while 1:
192208
msg = mb.next()
193-
if not msg:
209+
if msg is None:
194210
break
195211
msgs.append(msg)
196212
msg.fp = None
@@ -203,9 +219,9 @@ def _test():
203219
else:
204220
print 'Mailbox',mbox,'has',len(msgs),'messages:'
205221
for msg in msgs:
206-
f = msg.getheader('from')
207-
s = msg.getheader('subject')
208-
d = (msg.getheader('date'))
222+
f = msg.getheader('from') or ""
223+
s = msg.getheader('subject') or ""
224+
d = msg.getheader('date') or ""
209225
print '%20.20s %18.18s %-30.30s'%(f, d[5:], s)
210226

211227

0 commit comments

Comments
 (0)