[EMAIL PROTECTED] wrote: > I'm trying to figure out how to save an e-mail attachment from a POP3 > mailbox. I've scoured the web, but -none- of the examples I have > found have actually worked. For instance, in this example: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/8423cad79ff21730/0d8922943a164ccf?lnk=gst&q=email+attachment#0d8922943a164ccf, > fn is always None, but the e-mail -does- have an attachment (an xml > file). > > -- > http://mail.python.org/mailman/listinfo/python-list > > Try attached (caution *not* tested, I just cut and pasted it from a larger script I use (it should work :) ).
I have used a similar method quite successfully. HTH Regards Nicolaas -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle.
import mimetypes, email def GetMailRaw (self, msg = {}): """ Returns full email message in textformat.""" mailrawtext = '' for line in msg: mailrawtext += line mailrawtext += '\n' return str( mailrawtext ) def GetAttachments (self, mail ): """ This function is recursive, if the message contains multipart message the function is recursively called to get all the attachments""" if ( not mail.is_multipart()): print "NOTE: THIS DOCUMENT IS NOT MULTIPART - NO ATTACHMENTS TO PARSE." return "NOT_MULTIPART" partsThatAreAttachments = [] #empty list index = 0 list = mail.get_payload() # End of recursion, the payload is a string if type(list) == type(""): return for part in list: maintype = part.get_content_maintype() # If attachment - add to attachment list if ( maintype != "text" and maintype != "multipart" and maintype != "message"): # Also the message type is a kind of multipart partsThatAreAttachments.append(index) if (maintype == "multipart" or maintype == "message"): # If there are more attachments - get them self.GetAttachments (part) index = index + 1 allAttachments = {} listParts = mail.get_payload() # parts of mail message offset = 0 for indexOfAttachment in partsThatAreAttachments: indexOfAttachment = indexOfAttachment - offset #save the part to delete - in present working dir filename = listParts[indexOfAttachment].get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: #generic extension ext = ".bin" filename = "part-%03d%s" % ( indexOfAttachment , ext) # DEBUG # Save attachments to present working dir # fp = open (filename, "wb") # fp.write(listparts[indexofattachment].get_payload(decode=1)) # fp.close() # Add attachment to attachment dictionary allAttachments.setdefault(filename, []).append(listParts[indexOfAttachment].get_payload ()) del listParts[indexOfAttachment] offset = offset + 1 return allAttachments mailraw = GetMailRaw(popresponse) mail = email.message_from_string(mailraw) attachments = GetAttachments(mail)
-- http://mail.python.org/mailman/listinfo/python-list