When fetching large documents via SSL, the imaplib
attempts to read it all in one chunk, but the SSL
socket layer only returns ~16k at a time.
The result is that Python will end up allocating, say,
a 15 megabyte block, shrink it to a few kilobytes,
occasionally allocate a medium-sized block (to hold
the list of chunks), and repeat this again and again
and again. Not all malloc implementations can reuse
the (15 megabytes minus a few kilobyte) block when
allocating the next 15 megabyte block. In a worst
case scenario, you'll need some 13 gigabytes of
virtual memory to read a 15 megabyte message...
A simple solution is to change
data = self.sslobj.read(size-read)
to
data = self.sslobj.read(min(size-read, 16384))
For more on this, see this thread:
http://groups.google.com/group/comp.lang.python/browse_
frm/thread/3737500bac287575/d715bf614a86e786
</F>

I think I was just bitten by the non-SSL version of this bug on Python 2.5.1 (r251:54863) on Mac
OS 10.5. It manifested itself as a "malloc error: can't allocate region" while downloading a
message using imaplib.
As suggested by effbot I changed "data = self._sock.recv(recv_size)" to "data =
self._sock.recv(min(recv_size, 16384))" in both places that line appears in socket.py. Making
that change fixed the problem for me.
Note that http://bugs.python.org/issue1092502 seems to be a duplicate of this issue. That issue
contains a slightly different fix proposed by a_lauer, which I've not tried.