Python: Retrieving only POP3 message text, no headers

你。 提交于 2019-12-09 12:24:03

问题


I'm trying to make a Python program that retrieves only the body text of an email without passing headers or any other parameters. I'm not sure how to go about this.

The goal is to be able to send basic commands to a program via message text.

What I have now is this:

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.")

Which is all fine, except when "print J" is executed it prints the entire message, including headers. I just want to extract the body text without any additional garbage.

Can anyone help? Thanks!


回答1:


You can parse eMails using the email module.




回答2:


I would use email module to get the body of email message with get_payload() method which skips header info.

I added few lines to your code (they are marked with # new statement at the end of 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.")



回答3:


This is a fragment of code from 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 = []

This keys off the first empty line in the list of all lines as the end of the header info. Then just list slice from there to the end for the message body.



来源:https://stackoverflow.com/questions/2218066/python-retrieving-only-pop3-message-text-no-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!