Python Forum

Full Version: mail.message parse
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I would like to read mail from a pop3 server and parse it in to a email.message object.
The program below reads the message correctly.
But the parsing fails to work correctly.
The line totalMsg.keys() is supposed to return all the keys in the message, ie "subject, to, from etc" but it only has one key in.
Please let me know if you have any idea on how to fix this.

Thanks for your help.

import poplib
import email
import email.parser
import email.policy
 
pop3server="servername"
pop3user="username"
pop3pass="password"
 
 
#connect
server=poplib.POP3(pop3server)
 
#login
server.user(pop3user)
server.pass_(pop3pass)
resp, items, octets = server.list()
 
numMsg = len(items)
 
parser=email.parser.BytesFeedParser()
 
if numMsg > 0:
    print ('You have {} new messages'.format(numMsg))
    #get first message
    header,mailmesg,octets=server.retr(1)
 
    #convert message to email.message.Message
    for j in mailmesg:
        parser.feed(j)
 
else:
    print ('No new mail')
    exit()
 
totalMsg=parser.close()
 
#print the message
print (totalMsg)
print ('keys in message:',totalMsg.keys())

Thanks solved the issue.
You have to add \r\n after each line when you feed to the parser.
#bestdocumentationever