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.
解决方案
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'