如何在Python中读取POP服务器响应

0 投票
1 回答
1552 浏览
提问于 2025-04-18 17:29

我正在尝试读取pop3热mail服务器的响应或异常。这是个很简单的问题,但我刚开始学习Python,不知道该怎么做。这是我的代码:

import poplib
import sys
host = 'pop3.live.com'
port = 995
email='123456@hotmail.com'
pwd='123456'
server = poplib.POP3_SSL(host, port)
try:
    server.user(email)
    server.pass_(pwd)
    if('+OK'):
        print 'Email: '+email+'password: '+pwd
        server.quit()
        sys.exit(1)
except poplib.error_proto:
    if('POP+disabled'):
        print 'Email: '+email+'password: '+pwd
        server.quit()
        sys.exit(1)
    elif('authentication+failed'):
        print "wronge user and pass. try again"
        continue
    continue    

在异常处理中,“if ('POP+disabled')”是用来判断用户的登录名和密码是否正确,但账户没有在选项中启用POP3。

当我运行上面的代码时,即使我输入了错误的密码,它也会显示邮箱密码……

有没有人能帮我解决这个问题呢?

1 个回答

0

你可以使用server.getwelcome()这个方法来检查服务器的响应,确保一切正常后再开始解析消息。

服务器对象让你在认证后请求消息列表,然后你可以调用retr来获取每一条消息。



    welcomeresp = server.getwelcome()
    if welcomeresp.find("+OK"):
       numMessages = len(server.list()[1])
       for i in range(numMessages): 
          for j in server.retr(i+1): 
              server_msg, body, octets = j
              for line in body:
                 print line

想了解更多信息和示例,可以查看POP库的文档:

https://docs.python.org/2/library/poplib.html

撰写回答