email library

Ethan Furman ethan at stoneleaf.us
Fri Mar 18 12:43:44 EDT 2011


peterob wrote:
> Im completely confinvalided from email library. When you parse email from
> file it creates object Message.
> 
> f = open(emailFile, 'r')
> msg = email.message_from_file(f)
> f.close()
> 
> 
> How can I access RAW header of email represented by object msg? I dont
> wanna access each header field by hand.
> 
> Im doing another parsing, searching for attachments and so on, with
> email, but i need write raw data of email too. Do I have to allocate
> another memory for that emailFile? (by mmap or f=open(rawemail).

For the ultimate in raw, open the email file and parse it manually.

Your other option is use msg.walk() and msg.items() and walk through the 
returned (header, value) pairs.

8<-----------------------------
--> import email
--> msg = email.message_from_file(open(r'c:\temp2\latest_dbf.eml'))
--> from pprint import pprint as pp
--> for sub in msg.walk():
...   pp(sub.items())
...
[('Return-path', '<someone at somewhere.invalid>'),
  ('Envelope-to', 'someone at somewhere.invalid'),
  ('Delivery-date', 'Mon, 07 Mar 2011 18:32:18 -0600'),
  ('Received',
   'from [72.11.125.166] (port=2728 helo=[192.168.10.136])\n\tby 
gator410.hostgator.com with esmtpa (Exim 4.69)\n\t(envelope-from 
<someone at somewhere.invalid>)\n\tid
  1PwkqN-0001eV-54\n\tfor someone at somewhere.invalid; Mon, 07 Mar 2011 
18:32:16 -0600'),
  ('Message-ID', '<4D757B80.9020001 at somewhere.invalid>'),
  ('Date', 'Mon, 07 Mar 2011 16:42:40 -0800'),
  ('From', 'First Last <someone at somewhere.invalid>'),
  ('User-Agent', 'Thunderbird 1.5.0.10 (Windows/20070221)'),
  ('MIME-Version', '1.0'),
  ('To', 'First Last <someone at somewhere.invalid>'),
  ('Subject', 'latest dbf'),
  ('Content-Type',
   'multipart/mixed;\n boundary="------------010408020108000602070901"')]

[('Content-Type', 'text/plain; charset=ISO-8859-1; format=flowed'),
  ('Content-Transfer-Encoding', '7bit')]

[('Content-Type', 'text/plain;\n name="tables.py"'),
  ('Content-Transfer-Encoding', '7bit'),
  ('Content-Disposition', 'inline;\n filename="tables.py"')]

[('Content-Type', 'application/x-zip-compressed;\n name="dbf-0.88.18.zip"'),
  ('Content-Transfer-Encoding', 'base64'),
  ('Content-Disposition', 'inline;\n filename="dbf-0.88.18.zip"')]
8<-----------------------------

Hope this helps!

~Ethan~



More information about the Python-list mailing list