from email.generator import Generator
from io import StringIO


def flatten_message(msg):
    """Returns the message flattened to a string, for use in writing to a file.  NOTE:
    use this instead of message.as_string() to avoid mangling message.
    """
    fp = StringIO()
    g = Generator(fp, mangle_from_=False)
    g.flatten(msg)
    return fp.getvalue()