I am trying to modify emails stored as text files. I first import a message like this :
import email
f = open('filename')
msg = email.message_from_file(f)
Then, I make all the modifications I want, using the features of the email module.
The last step is to save the Message object (msg) in a file. What is the piece of code that does this ? There seems not to be any simple function like “message_to_file()”…
Many thanks.
The Messsage.as_string method should give you a flattened version of the message that you can write out just as you would any other string:
msg.as_string()
If this doesn’t provide exactly the format you want, consider trying the email.generator module? If I read things correctly, you should be able to do something like this:
Assuming
out_fileis an open and writable file andmsgis your message.