The python docs caution against using the POP3 protocol. Your mail server probably understands IMAP, so you can use IMAP4.partial() to fetch the message in parts, writing each part to disk immediately.
But if you have to use POP3, you're in luck: The POP3 protocol is line-oriented. Python's poplib library is pure python, and it's a trivial matter to add an iterator by looking at the source. I didn't bother to derive from the POP3
class, so here's how to do it by monkey-patching:
from poplib import POP3
def iretr(self, which):
"""
Retrieve whole message number 'which', in iterator form.
Return content in the form (line, octets)
"""
self._putcmd('RETR %s' % which)
resp = self._getresp() # Will raise exception on error
# Simplified from _getlongresp()
line, o = self._getline()
while line != '.':
if line[:2] == '..':
o = o-1
line = line[1:]
yield line, o
line, o = self._getline()
POP3.iretr = iretr
You can then fetch your message and write to disk one line at a time, like this:
pop_conn = POP3(servername)
...
msg_file = open(msg_file_name, "wb")
for line, octets in pop_conn.iretr(msg_number):
msg_file.write(line+"\n")
msg_file.close()