views:

238

answers:

1

How do I use poplib, and download mails as message instances from email.Message class from email module in Python?

I am writing a program, which analyzes, all emails for specific information, storing parts of the message into a database. I can download the entire mail as text, howver walking through text searching for attachments is difficult.

idea is to parse messages for information

+2  A: 

use the FeedParser class in the email.feedparser module to construct an email.Message object from the messages read from the server with poplib.

specifically:

import poplib
import email

pop = poplib.POP3( "server..." )
[establish connection, authenticate, ...]
raw = pop.retr( 1 )
pop.close()

parser = email.parser.FeedParser()
for line in raw[1]:
    parser.feed( str( line+b'\n', 'us-ascii' ) )
message = parser.close()
Adrien Plisson