#-*- coding: utf-8 -*- #!/user/bin/env python import email import poplib import sys def log(text): sys.stdout.write(text) sys.stdout.flush() host = 'XXXXXXXXXXX' user = 'XXXXXXXXXXXX' password = 'XXXXXXXX' # 打开邮箱工具箱 dest = 'mail.txt' destfd = open(dest, 'at') log('Connecting to %s...\n' % host) # 登陆POP3邮箱 p = poplib.POP3(host) try: log('Loging on...') p.user(user) p.pass_(password) 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 = [] #删除邮件列表 # 将邮件写入destfd 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 number in dellist: counter += 1 log ('Deleting message %d od %d\r' % (counter, len(dellist))) p.dele(number) if counter > 0: log('Successfully deleteed %d message from server.\n' % counter) else: log('No messages present to download.\n') log('Closing connection...') p.quit() log('done.\n')