1 """A POP3 client class.
3 Based on the J. Myers POP3 draft, Jan. 96
6 # Author: David Ascher <david_ascher@brown.edu>
7 # [heavily stealing from nntplib.py]
8 # Updated: Piers Lauder <piers@cs.su.oz.au> [Jul '97]
9 # String method conversion and test jig improvements by ESR, February 2001.
11 # Example (see the test function at the end of this file)
17 __all__
= ["POP3","error_proto"]
19 # Exception raised when an error or invalid response is received:
21 class error_proto(Exception): pass
26 # Line terminators (we always output CRLF, but accept any of CRLF, LFCR, LF)
34 """This class supports both the minimal and optional command sets.
35 Arguments can be strings or integers (where appropriate)
36 (e.g.: retr(1) and retr('1') both work equally well.
40 PASS string pass_(string)
42 LIST [msg] list(msg = None)
49 Optional Commands (some servers support these):
51 APOP name digest apop(name, digest)
53 UIDL [msg] uidl(msg = None)
55 Raises one exception: 'error_proto'.
58 POP3(hostname, port=110)
60 NB: the POP protocol locks the mailbox from user
61 authorization until QUIT, so be sure to get in, suck
62 the messages, and quit, each time you access the
65 POP is a line-based protocol, which means large mail
66 messages consume lots of python cycles reading them
69 If it's available on your mail server, use IMAP4
70 instead, it doesn't suffer from the two problems
75 def __init__(self
, host
, port
= POP3_PORT
):
78 msg
= "getaddrinfo returns an empty list"
80 for res
in socket
.getaddrinfo(self
.host
, self
.port
, 0, socket
.SOCK_STREAM
):
81 af
, socktype
, proto
, canonname
, sa
= res
83 self
.sock
= socket
.socket(af
, socktype
, proto
)
85 except socket
.error
, msg
:
92 raise socket
.error
, msg
93 self
.file = self
.sock
.makefile('rb')
95 self
.welcome
= self
._getresp
()
98 def _putline(self
, line
):
99 if self
._debugging
> 1: print '*put*', `line`
100 self
.sock
.send('%s%s' % (line
, CRLF
))
103 # Internal: send one command to the server (through _putline())
105 def _putcmd(self
, line
):
106 if self
._debugging
: print '*cmd*', `line`
110 # Internal: return one line from the server, stripping CRLF.
111 # This is where all the CPU time of this module is consumed.
112 # Raise error_proto('-ERR EOF') if the connection is closed.
115 line
= self
.file.readline()
116 if self
._debugging
> 1: print '*get*', `line`
117 if not line
: raise error_proto('-ERR EOF')
119 # server can send any combination of CR & LF
120 # however, 'readline()' returns lines ending in LF
121 # so only possibilities are ...LF, ...CRLF, CR...LF
122 if line
[-2:] == CRLF
:
123 return line
[:-2], octets
125 return line
[1:-1], octets
126 return line
[:-1], octets
129 # Internal: get a response from the server.
130 # Raise 'error_proto' if the response doesn't start with '+'.
133 resp
, o
= self
._getline
()
134 if self
._debugging
> 1: print '*resp*', `resp`
137 raise error_proto(resp
)
141 # Internal: get a response plus following text from the server.
143 def _getlongresp(self
):
144 resp
= self
._getresp
()
145 list = []; octets
= 0
146 line
, o
= self
._getline
()
153 line
, o
= self
._getline
()
154 return resp
, list, octets
157 # Internal: send a command and get the response
159 def _shortcmd(self
, line
):
161 return self
._getresp
()
164 # Internal: send a command and get the response plus following text
166 def _longcmd(self
, line
):
168 return self
._getlongresp
()
171 # These can be useful:
173 def getwelcome(self
):
177 def set_debuglevel(self
, level
):
178 self
._debugging
= level
181 # Here are all the POP commands:
183 def user(self
, user
):
184 """Send user name, return response
186 (should indicate password required).
188 return self
._shortcmd
('USER %s' % user
)
191 def pass_(self
, pswd
):
192 """Send password, return response
194 (response includes message count, mailbox size).
196 NB: mailbox is locked by server from here to 'quit()'
198 return self
._shortcmd
('PASS %s' % pswd
)
202 """Get mailbox status.
204 Result is tuple of 2 ints (message count, mailbox size)
206 retval
= self
._shortcmd
('STAT')
207 rets
= retval
.split()
208 if self
._debugging
: print '*stat*', `rets`
209 numMessages
= int(rets
[1])
210 sizeMessages
= int(rets
[2])
211 return (numMessages
, sizeMessages
)
214 def list(self
, which
=None):
215 """Request listing, return result.
217 Result without a message number argument is in form
218 ['response', ['mesg_num octets', ...]].
220 Result when a message number argument is given is a
221 single response: the "scan listing" for that message.
224 return self
._shortcmd
('LIST %s' % which
)
225 return self
._longcmd
('LIST')
228 def retr(self
, which
):
229 """Retrieve whole message number 'which'.
231 Result is in form ['response', ['line', ...], octets].
233 return self
._longcmd
('RETR %s' % which
)
236 def dele(self
, which
):
237 """Delete message number 'which'.
239 Result is 'response'.
241 return self
._shortcmd
('DELE %s' % which
)
247 One supposes the response indicates the server is alive.
249 return self
._shortcmd
('NOOP')
253 """Not sure what this does."""
254 return self
._shortcmd
('RSET')
258 """Signoff: commit changes on server, unlock mailbox, close connection."""
260 resp
= self
._shortcmd
('QUIT')
261 except error_proto
, val
:
265 del self
.file, self
.sock
273 def rpop(self
, user
):
274 """Not sure what this does."""
275 return self
._shortcmd
('RPOP %s' % user
)
278 timestamp
= re
.compile(r
'\+OK.*(<[^>]+>)')
280 def apop(self
, user
, secret
):
283 - only possible if server has supplied a timestamp in initial greeting.
287 secret - secret shared between client and server.
289 NB: mailbox is locked by server from here to 'quit()'
291 m
= self
.timestamp
.match(self
.welcome
)
293 raise error_proto('-ERR APOP not supported by server')
295 digest
= md5
.new(m
.group(1)+secret
).digest()
296 digest
= ''.join(map(lambda x
:'%02x'%ord(x
), digest
))
297 return self
._shortcmd
('APOP %s %s' % (user
, digest
))
300 def top(self
, which
, howmuch
):
301 """Retrieve message header of message number 'which'
302 and first 'howmuch' lines of message body.
304 Result is in form ['response', ['line', ...], octets].
306 return self
._longcmd
('TOP %s %s' % (which
, howmuch
))
309 def uidl(self
, which
=None):
310 """Return message digest (unique id) list.
312 If 'which', result contains unique id for that message
313 in the form 'response mesgnum uid', otherwise result is
314 the list ['response', ['mesgnum uid', ...], octets]
317 return self
._shortcmd
('UIDL %s' % which
)
318 return self
._longcmd
('UIDL')
321 if __name__
== "__main__":
323 a
= POP3(sys
.argv
[1])
328 (numMsgs
, totalSize
) = a
.stat()
329 for i
in range(1, numMsgs
+ 1):
330 (header
, msg
, octets
) = a
.retr(i
)
331 print "Message ", `i`
, ':'
334 print '-----------------------'