Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python imap: how to parse multipart mail content

Tags:

python

email

imap

A mail can contain different blocks like:

--0016e68deb06b58acf04897c624e
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
content_1
...

--0016e68deb06b58acf04897c624e
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
content_2
... and so on

How can I get content of each block with python?
And also how to get properties of each block? (content-type, etc..)

like image 974
Sergey Avatar asked Nov 04 '10 08:11

Sergey


2 Answers

For parsing emails I have used Message.walk() method like this:

if msg.is_multipart():
    for part in msg.walk():
        ...

For content you can try: part.get_payload(). For content-type there is: part.get_content_type()

You will find documetation here: http://docs.python.org/library/email.message.html

You can also try email module with its iterators.

like image 180
Michał Niklas Avatar answered Nov 15 '22 10:11

Michał Niklas


http://docs.python.org/library/email.html

A very simple example (msg_as_str contains the raw bytes you got from the imap server):

import email
msg = email.message_from_string(msg_as_str)
print msg["Subject"]
like image 38
codeape Avatar answered Nov 15 '22 11:11

codeape