Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python2....
File: poplib.py
"""A POP3 client class.
[0] Fix | Delete
[1] Fix | Delete
Based on the J. Myers POP3 draft, Jan. 96
[2] Fix | Delete
"""
[3] Fix | Delete
[4] Fix | Delete
# Author: David Ascher <david_ascher@brown.edu>
[5] Fix | Delete
# [heavily stealing from nntplib.py]
[6] Fix | Delete
# Updated: Piers Lauder <piers@cs.su.oz.au> [Jul '97]
[7] Fix | Delete
# String method conversion and test jig improvements by ESR, February 2001.
[8] Fix | Delete
# Added the POP3_SSL class. Methods loosely based on IMAP_SSL. Hector Urtubia <urtubia@mrbook.org> Aug 2003
[9] Fix | Delete
[10] Fix | Delete
# Example (see the test function at the end of this file)
[11] Fix | Delete
[12] Fix | Delete
# Imports
[13] Fix | Delete
[14] Fix | Delete
import re, socket
[15] Fix | Delete
[16] Fix | Delete
__all__ = ["POP3","error_proto"]
[17] Fix | Delete
[18] Fix | Delete
# Exception raised when an error or invalid response is received:
[19] Fix | Delete
[20] Fix | Delete
class error_proto(Exception): pass
[21] Fix | Delete
[22] Fix | Delete
# Standard Port
[23] Fix | Delete
POP3_PORT = 110
[24] Fix | Delete
[25] Fix | Delete
# POP SSL PORT
[26] Fix | Delete
POP3_SSL_PORT = 995
[27] Fix | Delete
[28] Fix | Delete
# Line terminators (we always output CRLF, but accept any of CRLF, LFCR, LF)
[29] Fix | Delete
CR = '\r'
[30] Fix | Delete
LF = '\n'
[31] Fix | Delete
CRLF = CR+LF
[32] Fix | Delete
[33] Fix | Delete
# maximal line length when calling readline(). This is to prevent
[34] Fix | Delete
# reading arbitrary length lines. RFC 1939 limits POP3 line length to
[35] Fix | Delete
# 512 characters, including CRLF. We have selected 2048 just to be on
[36] Fix | Delete
# the safe side.
[37] Fix | Delete
_MAXLINE = 2048
[38] Fix | Delete
[39] Fix | Delete
[40] Fix | Delete
class POP3:
[41] Fix | Delete
[42] Fix | Delete
"""This class supports both the minimal and optional command sets.
[43] Fix | Delete
Arguments can be strings or integers (where appropriate)
[44] Fix | Delete
(e.g.: retr(1) and retr('1') both work equally well.
[45] Fix | Delete
[46] Fix | Delete
Minimal Command Set:
[47] Fix | Delete
USER name user(name)
[48] Fix | Delete
PASS string pass_(string)
[49] Fix | Delete
STAT stat()
[50] Fix | Delete
LIST [msg] list(msg = None)
[51] Fix | Delete
RETR msg retr(msg)
[52] Fix | Delete
DELE msg dele(msg)
[53] Fix | Delete
NOOP noop()
[54] Fix | Delete
RSET rset()
[55] Fix | Delete
QUIT quit()
[56] Fix | Delete
[57] Fix | Delete
Optional Commands (some servers support these):
[58] Fix | Delete
RPOP name rpop(name)
[59] Fix | Delete
APOP name digest apop(name, digest)
[60] Fix | Delete
TOP msg n top(msg, n)
[61] Fix | Delete
UIDL [msg] uidl(msg = None)
[62] Fix | Delete
[63] Fix | Delete
Raises one exception: 'error_proto'.
[64] Fix | Delete
[65] Fix | Delete
Instantiate with:
[66] Fix | Delete
POP3(hostname, port=110)
[67] Fix | Delete
[68] Fix | Delete
NB: the POP protocol locks the mailbox from user
[69] Fix | Delete
authorization until QUIT, so be sure to get in, suck
[70] Fix | Delete
the messages, and quit, each time you access the
[71] Fix | Delete
mailbox.
[72] Fix | Delete
[73] Fix | Delete
POP is a line-based protocol, which means large mail
[74] Fix | Delete
messages consume lots of python cycles reading them
[75] Fix | Delete
line-by-line.
[76] Fix | Delete
[77] Fix | Delete
If it's available on your mail server, use IMAP4
[78] Fix | Delete
instead, it doesn't suffer from the two problems
[79] Fix | Delete
above.
[80] Fix | Delete
"""
[81] Fix | Delete
[82] Fix | Delete
[83] Fix | Delete
def __init__(self, host, port=POP3_PORT,
[84] Fix | Delete
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
[85] Fix | Delete
self.host = host
[86] Fix | Delete
self.port = port
[87] Fix | Delete
self.sock = socket.create_connection((host, port), timeout)
[88] Fix | Delete
self.file = self.sock.makefile('rb')
[89] Fix | Delete
self._debugging = 0
[90] Fix | Delete
self.welcome = self._getresp()
[91] Fix | Delete
[92] Fix | Delete
[93] Fix | Delete
def _putline(self, line):
[94] Fix | Delete
if self._debugging > 1: print '*put*', repr(line)
[95] Fix | Delete
self.sock.sendall('%s%s' % (line, CRLF))
[96] Fix | Delete
[97] Fix | Delete
[98] Fix | Delete
# Internal: send one command to the server (through _putline())
[99] Fix | Delete
[100] Fix | Delete
def _putcmd(self, line):
[101] Fix | Delete
if self._debugging: print '*cmd*', repr(line)
[102] Fix | Delete
self._putline(line)
[103] Fix | Delete
[104] Fix | Delete
[105] Fix | Delete
# Internal: return one line from the server, stripping CRLF.
[106] Fix | Delete
# This is where all the CPU time of this module is consumed.
[107] Fix | Delete
# Raise error_proto('-ERR EOF') if the connection is closed.
[108] Fix | Delete
[109] Fix | Delete
def _getline(self):
[110] Fix | Delete
line = self.file.readline(_MAXLINE + 1)
[111] Fix | Delete
if len(line) > _MAXLINE:
[112] Fix | Delete
raise error_proto('line too long')
[113] Fix | Delete
if self._debugging > 1: print '*get*', repr(line)
[114] Fix | Delete
if not line: raise error_proto('-ERR EOF')
[115] Fix | Delete
octets = len(line)
[116] Fix | Delete
# server can send any combination of CR & LF
[117] Fix | Delete
# however, 'readline()' returns lines ending in LF
[118] Fix | Delete
# so only possibilities are ...LF, ...CRLF, CR...LF
[119] Fix | Delete
if line[-2:] == CRLF:
[120] Fix | Delete
return line[:-2], octets
[121] Fix | Delete
if line[0] == CR:
[122] Fix | Delete
return line[1:-1], octets
[123] Fix | Delete
return line[:-1], octets
[124] Fix | Delete
[125] Fix | Delete
[126] Fix | Delete
# Internal: get a response from the server.
[127] Fix | Delete
# Raise 'error_proto' if the response doesn't start with '+'.
[128] Fix | Delete
[129] Fix | Delete
def _getresp(self):
[130] Fix | Delete
resp, o = self._getline()
[131] Fix | Delete
if self._debugging > 1: print '*resp*', repr(resp)
[132] Fix | Delete
c = resp[:1]
[133] Fix | Delete
if c != '+':
[134] Fix | Delete
raise error_proto(resp)
[135] Fix | Delete
return resp
[136] Fix | Delete
[137] Fix | Delete
[138] Fix | Delete
# Internal: get a response plus following text from the server.
[139] Fix | Delete
[140] Fix | Delete
def _getlongresp(self):
[141] Fix | Delete
resp = self._getresp()
[142] Fix | Delete
list = []; octets = 0
[143] Fix | Delete
line, o = self._getline()
[144] Fix | Delete
while line != '.':
[145] Fix | Delete
if line[:2] == '..':
[146] Fix | Delete
o = o-1
[147] Fix | Delete
line = line[1:]
[148] Fix | Delete
octets = octets + o
[149] Fix | Delete
list.append(line)
[150] Fix | Delete
line, o = self._getline()
[151] Fix | Delete
return resp, list, octets
[152] Fix | Delete
[153] Fix | Delete
[154] Fix | Delete
# Internal: send a command and get the response
[155] Fix | Delete
[156] Fix | Delete
def _shortcmd(self, line):
[157] Fix | Delete
self._putcmd(line)
[158] Fix | Delete
return self._getresp()
[159] Fix | Delete
[160] Fix | Delete
[161] Fix | Delete
# Internal: send a command and get the response plus following text
[162] Fix | Delete
[163] Fix | Delete
def _longcmd(self, line):
[164] Fix | Delete
self._putcmd(line)
[165] Fix | Delete
return self._getlongresp()
[166] Fix | Delete
[167] Fix | Delete
[168] Fix | Delete
# These can be useful:
[169] Fix | Delete
[170] Fix | Delete
def getwelcome(self):
[171] Fix | Delete
return self.welcome
[172] Fix | Delete
[173] Fix | Delete
[174] Fix | Delete
def set_debuglevel(self, level):
[175] Fix | Delete
self._debugging = level
[176] Fix | Delete
[177] Fix | Delete
[178] Fix | Delete
# Here are all the POP commands:
[179] Fix | Delete
[180] Fix | Delete
def user(self, user):
[181] Fix | Delete
"""Send user name, return response
[182] Fix | Delete
[183] Fix | Delete
(should indicate password required).
[184] Fix | Delete
"""
[185] Fix | Delete
return self._shortcmd('USER %s' % user)
[186] Fix | Delete
[187] Fix | Delete
[188] Fix | Delete
def pass_(self, pswd):
[189] Fix | Delete
"""Send password, return response
[190] Fix | Delete
[191] Fix | Delete
(response includes message count, mailbox size).
[192] Fix | Delete
[193] Fix | Delete
NB: mailbox is locked by server from here to 'quit()'
[194] Fix | Delete
"""
[195] Fix | Delete
return self._shortcmd('PASS %s' % pswd)
[196] Fix | Delete
[197] Fix | Delete
[198] Fix | Delete
def stat(self):
[199] Fix | Delete
"""Get mailbox status.
[200] Fix | Delete
[201] Fix | Delete
Result is tuple of 2 ints (message count, mailbox size)
[202] Fix | Delete
"""
[203] Fix | Delete
retval = self._shortcmd('STAT')
[204] Fix | Delete
rets = retval.split()
[205] Fix | Delete
if self._debugging: print '*stat*', repr(rets)
[206] Fix | Delete
numMessages = int(rets[1])
[207] Fix | Delete
sizeMessages = int(rets[2])
[208] Fix | Delete
return (numMessages, sizeMessages)
[209] Fix | Delete
[210] Fix | Delete
[211] Fix | Delete
def list(self, which=None):
[212] Fix | Delete
"""Request listing, return result.
[213] Fix | Delete
[214] Fix | Delete
Result without a message number argument is in form
[215] Fix | Delete
['response', ['mesg_num octets', ...], octets].
[216] Fix | Delete
[217] Fix | Delete
Result when a message number argument is given is a
[218] Fix | Delete
single response: the "scan listing" for that message.
[219] Fix | Delete
"""
[220] Fix | Delete
if which is not None:
[221] Fix | Delete
return self._shortcmd('LIST %s' % which)
[222] Fix | Delete
return self._longcmd('LIST')
[223] Fix | Delete
[224] Fix | Delete
[225] Fix | Delete
def retr(self, which):
[226] Fix | Delete
"""Retrieve whole message number 'which'.
[227] Fix | Delete
[228] Fix | Delete
Result is in form ['response', ['line', ...], octets].
[229] Fix | Delete
"""
[230] Fix | Delete
return self._longcmd('RETR %s' % which)
[231] Fix | Delete
[232] Fix | Delete
[233] Fix | Delete
def dele(self, which):
[234] Fix | Delete
"""Delete message number 'which'.
[235] Fix | Delete
[236] Fix | Delete
Result is 'response'.
[237] Fix | Delete
"""
[238] Fix | Delete
return self._shortcmd('DELE %s' % which)
[239] Fix | Delete
[240] Fix | Delete
[241] Fix | Delete
def noop(self):
[242] Fix | Delete
"""Does nothing.
[243] Fix | Delete
[244] Fix | Delete
One supposes the response indicates the server is alive.
[245] Fix | Delete
"""
[246] Fix | Delete
return self._shortcmd('NOOP')
[247] Fix | Delete
[248] Fix | Delete
[249] Fix | Delete
def rset(self):
[250] Fix | Delete
"""Unmark all messages marked for deletion."""
[251] Fix | Delete
return self._shortcmd('RSET')
[252] Fix | Delete
[253] Fix | Delete
[254] Fix | Delete
def quit(self):
[255] Fix | Delete
"""Signoff: commit changes on server, unlock mailbox, close connection."""
[256] Fix | Delete
try:
[257] Fix | Delete
resp = self._shortcmd('QUIT')
[258] Fix | Delete
except error_proto, val:
[259] Fix | Delete
resp = val
[260] Fix | Delete
self.file.close()
[261] Fix | Delete
self.sock.close()
[262] Fix | Delete
del self.file, self.sock
[263] Fix | Delete
return resp
[264] Fix | Delete
[265] Fix | Delete
#__del__ = quit
[266] Fix | Delete
[267] Fix | Delete
[268] Fix | Delete
# optional commands:
[269] Fix | Delete
[270] Fix | Delete
def rpop(self, user):
[271] Fix | Delete
"""Not sure what this does."""
[272] Fix | Delete
return self._shortcmd('RPOP %s' % user)
[273] Fix | Delete
[274] Fix | Delete
[275] Fix | Delete
timestamp = re.compile(r'\+OK.*(<[^>]+>)')
[276] Fix | Delete
[277] Fix | Delete
def apop(self, user, secret):
[278] Fix | Delete
"""Authorisation
[279] Fix | Delete
[280] Fix | Delete
- only possible if server has supplied a timestamp in initial greeting.
[281] Fix | Delete
[282] Fix | Delete
Args:
[283] Fix | Delete
user - mailbox user;
[284] Fix | Delete
secret - secret shared between client and server.
[285] Fix | Delete
[286] Fix | Delete
NB: mailbox is locked by server from here to 'quit()'
[287] Fix | Delete
"""
[288] Fix | Delete
m = self.timestamp.match(self.welcome)
[289] Fix | Delete
if not m:
[290] Fix | Delete
raise error_proto('-ERR APOP not supported by server')
[291] Fix | Delete
import hashlib
[292] Fix | Delete
digest = hashlib.md5(m.group(1)+secret).digest()
[293] Fix | Delete
digest = ''.join(map(lambda x:'%02x'%ord(x), digest))
[294] Fix | Delete
return self._shortcmd('APOP %s %s' % (user, digest))
[295] Fix | Delete
[296] Fix | Delete
[297] Fix | Delete
def top(self, which, howmuch):
[298] Fix | Delete
"""Retrieve message header of message number 'which'
[299] Fix | Delete
and first 'howmuch' lines of message body.
[300] Fix | Delete
[301] Fix | Delete
Result is in form ['response', ['line', ...], octets].
[302] Fix | Delete
"""
[303] Fix | Delete
return self._longcmd('TOP %s %s' % (which, howmuch))
[304] Fix | Delete
[305] Fix | Delete
[306] Fix | Delete
def uidl(self, which=None):
[307] Fix | Delete
"""Return message digest (unique id) list.
[308] Fix | Delete
[309] Fix | Delete
If 'which', result contains unique id for that message
[310] Fix | Delete
in the form 'response mesgnum uid', otherwise result is
[311] Fix | Delete
the list ['response', ['mesgnum uid', ...], octets]
[312] Fix | Delete
"""
[313] Fix | Delete
if which is not None:
[314] Fix | Delete
return self._shortcmd('UIDL %s' % which)
[315] Fix | Delete
return self._longcmd('UIDL')
[316] Fix | Delete
[317] Fix | Delete
try:
[318] Fix | Delete
import ssl
[319] Fix | Delete
except ImportError:
[320] Fix | Delete
pass
[321] Fix | Delete
else:
[322] Fix | Delete
[323] Fix | Delete
class POP3_SSL(POP3):
[324] Fix | Delete
"""POP3 client class over SSL connection
[325] Fix | Delete
[326] Fix | Delete
Instantiate with: POP3_SSL(hostname, port=995, keyfile=None, certfile=None)
[327] Fix | Delete
[328] Fix | Delete
hostname - the hostname of the pop3 over ssl server
[329] Fix | Delete
port - port number
[330] Fix | Delete
keyfile - PEM formatted file that contains your private key
[331] Fix | Delete
certfile - PEM formatted certificate chain file
[332] Fix | Delete
[333] Fix | Delete
See the methods of the parent class POP3 for more documentation.
[334] Fix | Delete
"""
[335] Fix | Delete
[336] Fix | Delete
def __init__(self, host, port = POP3_SSL_PORT, keyfile = None, certfile = None):
[337] Fix | Delete
self.host = host
[338] Fix | Delete
self.port = port
[339] Fix | Delete
self.keyfile = keyfile
[340] Fix | Delete
self.certfile = certfile
[341] Fix | Delete
self.buffer = ""
[342] Fix | Delete
msg = "getaddrinfo returns an empty list"
[343] Fix | Delete
self.sock = None
[344] Fix | Delete
for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
[345] Fix | Delete
af, socktype, proto, canonname, sa = res
[346] Fix | Delete
try:
[347] Fix | Delete
self.sock = socket.socket(af, socktype, proto)
[348] Fix | Delete
self.sock.connect(sa)
[349] Fix | Delete
except socket.error, msg:
[350] Fix | Delete
if self.sock:
[351] Fix | Delete
self.sock.close()
[352] Fix | Delete
self.sock = None
[353] Fix | Delete
continue
[354] Fix | Delete
break
[355] Fix | Delete
if not self.sock:
[356] Fix | Delete
raise socket.error, msg
[357] Fix | Delete
self.file = self.sock.makefile('rb')
[358] Fix | Delete
self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
[359] Fix | Delete
self._debugging = 0
[360] Fix | Delete
self.welcome = self._getresp()
[361] Fix | Delete
[362] Fix | Delete
def _fillBuffer(self):
[363] Fix | Delete
localbuf = self.sslobj.read()
[364] Fix | Delete
if len(localbuf) == 0:
[365] Fix | Delete
raise error_proto('-ERR EOF')
[366] Fix | Delete
self.buffer += localbuf
[367] Fix | Delete
[368] Fix | Delete
def _getline(self):
[369] Fix | Delete
line = ""
[370] Fix | Delete
renewline = re.compile(r'.*?\n')
[371] Fix | Delete
match = renewline.match(self.buffer)
[372] Fix | Delete
while not match:
[373] Fix | Delete
self._fillBuffer()
[374] Fix | Delete
if len(self.buffer) > _MAXLINE:
[375] Fix | Delete
raise error_proto('line too long')
[376] Fix | Delete
match = renewline.match(self.buffer)
[377] Fix | Delete
line = match.group(0)
[378] Fix | Delete
self.buffer = renewline.sub('' ,self.buffer, 1)
[379] Fix | Delete
if self._debugging > 1: print '*get*', repr(line)
[380] Fix | Delete
[381] Fix | Delete
octets = len(line)
[382] Fix | Delete
if line[-2:] == CRLF:
[383] Fix | Delete
return line[:-2], octets
[384] Fix | Delete
if line[0] == CR:
[385] Fix | Delete
return line[1:-1], octets
[386] Fix | Delete
return line[:-1], octets
[387] Fix | Delete
[388] Fix | Delete
def _putline(self, line):
[389] Fix | Delete
if self._debugging > 1: print '*put*', repr(line)
[390] Fix | Delete
line += CRLF
[391] Fix | Delete
bytes = len(line)
[392] Fix | Delete
while bytes > 0:
[393] Fix | Delete
sent = self.sslobj.write(line)
[394] Fix | Delete
if sent == bytes:
[395] Fix | Delete
break # avoid copy
[396] Fix | Delete
line = line[sent:]
[397] Fix | Delete
bytes = bytes - sent
[398] Fix | Delete
[399] Fix | Delete
def quit(self):
[400] Fix | Delete
"""Signoff: commit changes on server, unlock mailbox, close connection."""
[401] Fix | Delete
try:
[402] Fix | Delete
resp = self._shortcmd('QUIT')
[403] Fix | Delete
except error_proto, val:
[404] Fix | Delete
resp = val
[405] Fix | Delete
self.sock.close()
[406] Fix | Delete
del self.sslobj, self.sock
[407] Fix | Delete
return resp
[408] Fix | Delete
[409] Fix | Delete
__all__.append("POP3_SSL")
[410] Fix | Delete
[411] Fix | Delete
if __name__ == "__main__":
[412] Fix | Delete
import sys
[413] Fix | Delete
a = POP3(sys.argv[1])
[414] Fix | Delete
print a.getwelcome()
[415] Fix | Delete
a.user(sys.argv[2])
[416] Fix | Delete
a.pass_(sys.argv[3])
[417] Fix | Delete
a.list()
[418] Fix | Delete
(numMsgs, totalSize) = a.stat()
[419] Fix | Delete
for i in range(1, numMsgs + 1):
[420] Fix | Delete
(header, msg, octets) = a.retr(i)
[421] Fix | Delete
print "Message %d:" % i
[422] Fix | Delete
for line in msg:
[423] Fix | Delete
print ' ' + line
[424] Fix | Delete
print '-----------------------'
[425] Fix | Delete
a.quit()
[426] Fix | Delete
[427] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function