[issue11693] memory leak in email.generator.Generator().flatten() method

Kaushik Kannan report at bugs.python.org
Mon Mar 28 10:54:05 CEST 2011


New submission from Kaushik Kannan <kaushik1618 at gmail.com>:

I wrote a daemon to monitor a directory and send out emails periodically. To create the email, I used MIMEMultipart() object. When as_string() method is called on the MIMEMultipart() object, it seemed to cause memory leaks. On looking at the as_string() method, I saw that the  email.generator.Generator().flatten() method call is causing the memory leak. I copied the as_string() method out as a function and used it for tracing the memory leak.


#!/usr/bin/python

from guppy import hpy
import time
import gc

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from cStringIO import StringIO
from email.generator import Generator

def as_string_mod(msg, unixfrom=False):
        """Return the entire formatted message as a string.
        Optional `unixfrom' when True, means include the Unix From_ envelope
        header.

        This is a convenience method and may not generate the message exactly
        as you intend because by default it mangles lines that begin with
        "From ".  For more flexibility, use the flatten() method of a
        Generator instance.
        """
        fp = StringIO()
        g = Generator(fp)
        g.flatten(msg, unixfrom=unixfrom)
        return fp.getvalue()

msg = MIMEMultipart()
msg['From'] = 'from at gmail.com'
msg['To'] = 'to at gmail.com'
msg['Subject'] = 'Function'
msg.attach(MIMEText('Blah'))

if __name__=='__main__':
	while True:
		as_string_mod(msg)
		gc.collect()
		print hpy().heap()
		time.sleep(5)

----------
nosy: +kauboy

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11693>
_______________________________________


More information about the Python-bugs-list mailing list