An example of using the email module to unpack and decode a MIME message. This example uses the message's walk() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #!/usr/bin/env python
import email.Parser
import os
import sys
def main():
if len(sys.argv)==1:
print "Usage: %s filename" % os.path.basename(sys.argv[0])
sys.exit(1)
mailFile=open(sys.argv[1],"rb")
p=email.Parser.Parser()
msg=p.parse(mailFile)
mailFile.close()
partCounter=1
for part in msg.walk():
if part.get_main_type()=="multipart":
continue
name=part.get_param("name")
if name==None:
name="part-%i" % partCounter
partCounter+=1
# In real life, make sure that name is a reasonable
# filename on your OS.
f=open(name,"wb")
f.write(part.get_payload(decode=1))
f.close()
print name
return None
if __name__=="__main__":
main()
|
The email module makes manipulating MIME messages easier than it was before. It's still not trivial so the example may be useful.
Tags: network
get_main_type is deprecated/gone. From 2.4 on it's get_content_maintype()