星期四, 十二月 06, 2007

python pop example


import poplib
import pprint
import email
import string
import re
import sys
import traceback

class GetMail():
    def __init__(self,server,username,passwd):
        self.servername = server
        self.username = username
        self.passwd = passwd
        self.data = []

    def connect(self):
        try:
            self.pop = poplib.POP3(self.servername)
            self.pop.set_debuglevel (1)
            self.pop.user(self.username)
            self.pop.pass_(self.passwd)
            return True
        except:
            print "--"*20
            traceback.print_exc(file=sys.stdout )
            print "--"*20
            return False

    def get_mail(self):
        num,total_size = self.pop.stat()           
        for index in range(1, num+1):
            status = self.pop.list(index)
            length = string.atoi(string.split(status)[-1])
            print "length %d" % length
            if length < 50000:
                hdr,messages,octet=self.pop.retr (index)
                message = ""
                for line in messages:
                    if line:
                        if line[-1] == "=":
                            message += line[0:-1]
                        else:
                            message += line
                            message += "\n"
                    else:
                        message += "\n"
                print message
                self.data.append(message)
               
if __name__ == "__main__":
    gm =GetMail("pop3.126.com","*","*")
    if not gm.connect():
        print "connect error"
        sys.exit(1)
    gm.get_mail()
    fileout = open("dafads","w")
    for message in gm.data:
        fileout.write (message)
        fileout.write("-*-"*20)
        fileout.write("\n\n")

0 comments: