I have an email message obtained via Python’s email.parser module:
parser = email.parser.Parser()
msg1 = parser.parse(sys.stdin)
I would like to create a copy of this object, but I’m not sure how best to go about that. I can use the copy module…
msg2 = copy.deepcopy(msg1)
…but given that a MIME message may contain a somewhat arbitrary tree of parts I’m not sure if this is the right solution or not. I could serialize and reparse the message…
msg2 = parser.parse(msg1.as_string())
…but the documentation suggests that the as_string method may not always do the right thing. I can create a StringIO object and use a generator…
buf = String()
g = email.generator.Generator(buf)
g.flatten(msg1)
msg2 = parser.parse(buf.getvalue())
…but that seems like an awful lot of work to copy something that’s already been parsed once.
Using the copy module seems like the simplest solution, but I’m unfamiliar with the copy module. Am I doing the right thing?
Since it is a MIME message, you may be able to assume that no matter how nested an attribute may be, there will be an end. If so, deepcopy should do a recursive copy on every attribute of the message, so you will end up with the right thing doing copy.deepcopy.