[Email-SIG] How to extract attachment?
Mark Sapiro
msapiro at value.net
Mon Jun 26 21:30:48 CEST 2006
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 <http://docs.python.org/lib/module-email.Message.html> and
<http://docs.python.org/lib/module-mimetypes.html>
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 <msapiro at value.net> The highway is for gamblers,
San Francisco Bay Area, California better use your sense - B. Dylan
More information about the Email-SIG
mailing list