python之poplib库

pop3能实现访问远程主机下载新的邮件或者下载后删掉这些邮件。不支持多信箱,也不能提供持久稳定的邮件认证。也就是说不能使用pop3来作为邮件同步协议。 poplib支持多个认证方法。最普遍的是基本的用户名和密码方式以及APOP,后者是POP的一种可选扩展,可以帮助服务器在传输明文的时候避免袭击者盗取密码。连接和认证过程如下:

1.建立一个pop3对象,传给它远程服务器的主机名和端口号。

2.调用user()和pass_()函数来发送用户名和密码。

3.如果产生poplib.error_proto异常,登录就失败,服务器就会发送和异常有关的字符串和解释文字。

4.登录连接后,调用star()返回一个tuple,其中包含了服务器邮箱中的邮件数量和邮件总的大小。

5.最后,调用quit(),关闭pop连接.

[root@localhost example]# cat popconn.py 
#!/usr/bin/python
#POP connection and authentication
#coding:utf-8

import getpass, poplib, sys

host = 'pop3.163.com'
user = 'test@163.com'
passwd = getpass.getpass()

p = poplib.POP3(host)
try:
        p.user(user)
        p.pass_(passwd)
except poplib.error_proto, e:
        print "Login failed:", e
        sys.exit(1)

status = p.stat()
print "Mailbox has %d messages for a total of %d bytes" % (status[0], status[1])
p.quit()
                                                                                                
[root@localhost example]# python popconn.py
Password: 
Mailbox has 493 messages for a total of 34415730 bytes

APOP认证

使用一种加密方法来确保密码不被网络嗅探器窃取。APOP认证需要服务器支持,客户端连接时可以先尝试APOP认证,如果失败再尝试标准认证。

#!/usr/bin/python
# POP connection and authentication with APOP

import getpass, poplib, sys

host = 'pop3.163.com'
user = 'test@163.com'
passwd = getpass.getpass()

p = poplib.POP3(host)
try:
        print "Attempting APOP authentication..."
        p.apop(user, passwd)
except poplib.error_proto:
        print "Attempting standard authentication..."
        try:
                p.user(user)
                p.pass_(passwd)
        except poplib.error_proto:
                print "Login failed:", e
                sys.exit(1)

status = p.stat()
print "Mailbox has %d messages for a total of %d bytes" % (status[0], status[1])

p.quit()

取得邮箱信息:
前面的例子使用的是stat返回的结果为邮件的数量和全部大小。如果要返回每一封邮件更详细的信息,就要用指令 list() 。

#!/usr/bin/python
#POP mailbox scanning

import getpass, poplib, sys

host = 'pop3.163.com'
user = 'test@163.com'
passwd = getpass.getpass()

p = poplib.POP3(host)
try:
        p.user(user)
        p.pass_(passwd)
except poplib.error_proto, e:
        print "Login failed:", e
        sys.exit(1)

status = p.stat()
print "Mailbox has %d messges for a total of %d bytes" % (status[0], status[1])

for item in p.list()[1]:
        number, octets = item.split(' ')
        print "Message %s: %s bytes" % (number, octets)

p.quit()

p.list返回一个包含两个条目的组,第一个为应答代码,第二个是字符串列表,其中包括邮件数字和邮件的字节数。

下载邮件: poplib模块的retr()函数通过传递想要下载的邮件数字来下载邮件,每次下载一封邮件。 例:从服务器下载全部邮件并保留它们并以标准的unix mbox 格式写入文件中。

#!/usr/bin/python
#POP mailbox downloader

import getpass, poplib, sys, email

host = 'pop3.163.com'
user = 'test@163.com'
dest = './mailbox'
passwd = getpass.getpass()

destfd = open(dest, "at")

p = poplib.POP3(host)
try:
        p.user(user)
        p.pass_(passwd)
except poplib.error_proto, e:
        print "Login failed:", e
        sys.exit(1)

for item in p.list()[1]:
        number, octets = item.split(' ')
        print "Downloading message %s (%s bytes)" % (number, octets)
        lines = p.retr(number)[1]
        msg = email.message_from_string("\n".join(lines))
        destfd.write(msg.as_string(unixfrom = 1))
        destfd.write("\n")

p.quit()
destfd.close()

删除邮件:
poplib库调用dele()函数向服务器发送POP DELE指令,dele函数调用时需要传递一个要删除邮件的数字。

[root@localhost example]# cat download-and-delete.py
#!/usr/bin/python
#POP mailbox downloader with deletion

import getpass, poplib, sys, email

def log(text):
        sys.stdout.write(text)
        sys.stdout.flush()

host = 'pop3.163.com'
user = 'test@163.com'
dest = './mailbox'
passwd = getpass.getpass()
destfd = open(dest, 'at')

log("Connecting to %s ...\n" % host)

p = poplib.POP3(host)
try:
        log("Logging on...")
        p.user(user)
        p.pass_(passwd)
        log(" success.\n")
except poplib.error_proto, e:
        print "Login failed:", e
        sys.exit(1)

log("Scanning INBOX...")
mblist = p.list()[1]
log(" %d messages.\n" % len(mblist))

dellist = []

for item in mblist:
        number, octets = item.split(' ')
        log("Downloading message %s (%s bytes)..." % (number, octets))
        lines = p.retr(number)[1]
        msg = email.message_from_string("\n".join(lines))
        destfd.write(msg.as_string(unixfrom = 1))
        destfd.write("\n")
        dellist.append(number)
        log(" done.\n")

destfd.close()

counter = 0
for num in dellist:
        counter += 1
        log("Deleting message %d of %d\n" % (counter, len(dellist)))
        #p.dele(num)
if counter > 0:
        log("Successfully deleted %d messages from server.\n" % counter)
else:
        log("NO messages present to download.\n")

log("Closing connection...")
p.quit()
log(" done.\n")

 

posted @ 2013-10-17 09:58  运维文件夹  阅读(3809)  评论(0编辑  收藏  举报