pythonemail

Saving to .msg file in Python, or alternatively, sending mail to the file system


I'm using the emails library to send mail, but I also need to save it as .msg file. I've done some research and also read the msg format specification and stumbled upon this SO answer that shows how to send mail to the file system in C# and I was wondering if it was possible in Python as well.


Solution

  • It is possible and easy. Let's assume that msg is a previously composed message with all headers and content, and that you want to write it to the file object out. You just need:

    gen = email.generator.Generator(out)  # create a generator
    gen.flatten(msg)   # write the message to the file object
    

    Full example:

    import email
    
    # create a simple message
    msg = email.mime.text.MIMEText('''This is a simple message.
    And a very simple one.''')
    msg['Subject'] = 'Simple message'
    msg['From'] = 'sender@sending.domain'
    msg['To'] = 'rcpt@receiver.domain'
    
    # open a file and save mail to it
    with open('filename.elm', 'w') as out:
        gen = email.generator.Generator(out)
        gen.flatten(msg)
    

    The content of filename.elm is:

    Content-Type: text/plain; charset="us-ascii"
    MIME-Version: 1.0
    Content-Transfer-Encoding: 7bit
    Subject: Simple message
    From: sender@sending.domain
    To: rcpt@receiver.domain
    
    This is a simple message.
    And a very simple one.