From szybalski at gmail.com Mon Jun 26 20:55:32 2006 From: szybalski at gmail.com (Lukasz Szybalski) Date: Mon, 26 Jun 2006 13:55:32 -0500 Subject: [Email-SIG] How to extract attachment? Message-ID: <804e5c70606261155l50270005ia18f6b955921f867@mail.gmail.com> Hello, I received an email with attachment. The attachment can be binary or text. How do I extract and save the message to database and attachment to some folder? (f_name,f_email)=email.Utils.parseaddr(m['from']) (t_name,t_email)=email.Utils.parseaddr(m['to']) (r_name,r_email)=email.Utils.parseaddr(m['reply_to']) subject = m['subject'] body=m.get_payload() Since payload is multipart now. get_payload will be a list of parts. 1. How can i do: for i in m.get_payload(): save text to db (or extract text as string) save attachment to file with correct extension [.xml .exe .doc .pdf] (How can i extract file so i can do f.write(file) ) 2.How can i distinguish what is what? Will get_payload() display text first and then attachment? Thanks Lukasz From msapiro at value.net Mon Jun 26 21:30:48 2006 From: msapiro at value.net (Mark Sapiro) Date: Mon, 26 Jun 2006 12:30:48 -0700 Subject: [Email-SIG] How to extract attachment? In-Reply-To: <804e5c70606261155l50270005ia18f6b955921f867@mail.gmail.com> Message-ID: Lukasz Szybalski wrote: >I received an email with attachment. The attachment can be binary or text. >How do I extract and save the message to database and attachment to some folder? > >(f_name,f_email)=email.Utils.parseaddr(m['from']) >(t_name,t_email)=email.Utils.parseaddr(m['to']) >(r_name,r_email)=email.Utils.parseaddr(m['reply_to']) >subject = m['subject'] > body=m.get_payload() > >Since payload is multipart now. get_payload will be a list of parts. > >1. How can i do: > >for i in m.get_payload(): > save text to db (or extract text as string) > save attachment to file with correct extension [.xml .exe .doc >.pdf] (How can i extract file so i can do f.write(file) ) > >2.How can i distinguish what is what? Will get_payload() display text >first and then attachment? See and import mimetypes for i in m.walk(): if i.is_multipart(): continue if i.get_content_maintype() == 'text': pl = i.get_payload(decode=True) ... continue att_name = i.get_filename(None) if not att_name: ext = mimetypes.guess_extension(i.get_content_type()) att_name = 'makeitup%s' % ext pl = i.get_payload(decode=True) ... -- Mark Sapiro The highway is for gamblers, San Francisco Bay Area, California better use your sense - B. Dylan