Reputation: 1791
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
Upvotes: 1
Views: 2149
Reputation: 8035
Doesn't deal with character set issues like Adrien Plisson's answer.
import poplib
import email
pop = poplib.POP3( "server..." )
[establish connection, authenticate, ...]
raw = pop.retr( 1 )
pop.close()
message = email.message_from_string('\n'.join(raw[1]))
Upvotes: 2
Reputation: 23293
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()
Upvotes: 3