Python: receiving only POP3 message messages, no headers

I am trying to make a Python program that only extracts the body of an email message without passing headers or any other parameters. I am not sure how to do this.

The goal is to send basic commands to the program through the message text.

What I have now:

import poplib host = "pop.gmail.com" mail = poplib.POP3_SSL(host) print mail.getwelcome() print mail.user("user") print mail.pass_("pass") print mail.stat() print mail.list() print "" if mail.stat()[1] > 0: print "You have new mail." else: print "No new mail." print "" numMessages = len(mail.list()[1]) for i in range(numMessages): for j in mail.retr(i+1)[1]: print j mail.quit() input("Press any key to continue.") 

That everything is fine, except when "print J" is performed, it prints the entire message, including the headers. I just want to extract body text without any extra garbage.

Can anyone help? Thanks!

+6
python email text pop3 poplib
source share
3 answers

You can analyze emails using the email module .

+2
source share

I would use the email module to get the body of an email message using the get_payload () method, which skips the header information.

I added some lines to my code (they are marked with # new statement at the end of the line)

 import poplib import email # new statement host = "pop.gmail.com" mail = poplib.POP3_SSL(host) print mail.getwelcome() print mail.user("user") print mail.pass_("pass") print mail.stat() print mail.list() print "" if mail.stat()[1] > 0: print "You have new mail." else: print "No new mail." print "" numMessages = len(mail.list()[1]) for i in range(numMessages): for j in mail.retr(i+1)[1]: #print j msg = email.message_from_string(j) # new statement print(msg.get_payload()) # new statement mail.quit() input("Press any key to continue.") 
+5
source share

This is the code snippet of my own POP3 reader:

  response, lines, bytes = pop.retr(m) # remove trailing blank lines from message while lines[-1]=="": del lines[-1] try: endOfHeader = lines.index('') header = lines[:endOfHeader] body = lines[endOfHeader+1:] except ValueError: header = lines body = [] 

Disables the first blank line in the list of all lines as the end of the header information. Then just list the snippet from there to the end for the body of the message.

+3
source share

All Articles