blob: 0b22b2e4efe3ad52c224b99767a532e8a37ca957 [file] [log] [blame]
Guido van Rossum03774bb1998-04-09 13:50:55 +00001"""A POP3 client class.
Guido van Rossum484772d1998-04-06 18:27:27 +00002
Guido van Rossum03774bb1998-04-09 13:50:55 +00003Based on the J. Myers POP3 draft, Jan. 96
Guido van Rossum484772d1998-04-06 18:27:27 +00004"""
5
Guido van Rossum98d9fd32000-02-28 15:12:25 +00006# Author: David Ascher <david_ascher@brown.edu>
7# [heavily stealing from nntplib.py]
8# Updated: Piers Lauder <piers@cs.su.oz.au> [Jul '97]
Eric S. Raymond341f9292001-02-09 06:56:56 +00009# String method conversion and test jig improvements by ESR, February 2001.
Guido van Rossum98d9fd32000-02-28 15:12:25 +000010
Guido van Rossum484772d1998-04-06 18:27:27 +000011# Example (see the test function at the end of this file)
12
Guido van Rossum484772d1998-04-06 18:27:27 +000013# Imports
14
Eric S. Raymond341f9292001-02-09 06:56:56 +000015import re, socket
Guido van Rossum484772d1998-04-06 18:27:27 +000016
Skip Montanaroc62c81e2001-02-12 02:00:42 +000017__all__ = ["POP3","error_proto"]
18
Guido van Rossum484772d1998-04-06 18:27:27 +000019# Exception raised when an error or invalid response is received:
Guido van Rossum03774bb1998-04-09 13:50:55 +000020
21class error_proto(Exception): pass
Guido van Rossum484772d1998-04-06 18:27:27 +000022
23# Standard Port
24POP3_PORT = 110
25
Guido van Rossum03774bb1998-04-09 13:50:55 +000026# Line terminators (we always output CRLF, but accept any of CRLF, LFCR, LF)
27CR = '\r'
28LF = '\n'
29CRLF = CR+LF
Guido van Rossum484772d1998-04-06 18:27:27 +000030
31
32class POP3:
Guido van Rossum03774bb1998-04-09 13:50:55 +000033
Tim Peters2344fae2001-01-15 00:50:52 +000034 """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.
Guido van Rossum03774bb1998-04-09 13:50:55 +000037
Tim Peters2344fae2001-01-15 00:50:52 +000038 Minimal Command Set:
39 USER name user(name)
40 PASS string pass_(string)
41 STAT stat()
42 LIST [msg] list(msg = None)
43 RETR msg retr(msg)
44 DELE msg dele(msg)
45 NOOP noop()
46 RSET rset()
47 QUIT quit()
Guido van Rossum03774bb1998-04-09 13:50:55 +000048
Tim Peters2344fae2001-01-15 00:50:52 +000049 Optional Commands (some servers support these):
50 RPOP name rpop(name)
51 APOP name digest apop(name, digest)
52 TOP msg n top(msg, n)
53 UIDL [msg] uidl(msg = None)
Guido van Rossum03774bb1998-04-09 13:50:55 +000054
Tim Peters2344fae2001-01-15 00:50:52 +000055 Raises one exception: 'error_proto'.
Guido van Rossum03774bb1998-04-09 13:50:55 +000056
Tim Peters2344fae2001-01-15 00:50:52 +000057 Instantiate with:
58 POP3(hostname, port=110)
Guido van Rossum03774bb1998-04-09 13:50:55 +000059
Tim Peters2344fae2001-01-15 00:50:52 +000060 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
63 mailbox.
Guido van Rossum03774bb1998-04-09 13:50:55 +000064
Tim Peters2344fae2001-01-15 00:50:52 +000065 POP is a line-based protocol, which means large mail
66 messages consume lots of python cycles reading them
67 line-by-line.
Guido van Rossum03774bb1998-04-09 13:50:55 +000068
Tim Peters2344fae2001-01-15 00:50:52 +000069 If it's available on your mail server, use IMAP4
70 instead, it doesn't suffer from the two problems
71 above.
72 """
Guido van Rossum03774bb1998-04-09 13:50:55 +000073
74
Tim Peters2344fae2001-01-15 00:50:52 +000075 def __init__(self, host, port = POP3_PORT):
Martin v. Löwis4eb59402001-07-26 13:37:33 +000076 self.host = host
77 self.port = port
Martin v. Löwis2ad25692001-07-31 08:40:21 +000078 msg = "getaddrinfo returns an empty list"
Martin v. Löwis322c0d12001-10-07 08:53:32 +000079 self.sock = None
Martin v. Löwis4eb59402001-07-26 13:37:33 +000080 for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
81 af, socktype, proto, canonname, sa = res
82 try:
83 self.sock = socket.socket(af, socktype, proto)
84 self.sock.connect(sa)
85 except socket.error, msg:
Martin v. Löwis322c0d12001-10-07 08:53:32 +000086 if self.sock:
87 self.sock.close()
Martin v. Löwis4eb59402001-07-26 13:37:33 +000088 self.sock = None
89 continue
90 break
91 if not self.sock:
92 raise socket.error, msg
93 self.file = self.sock.makefile('rb')
94 self._debugging = 0
95 self.welcome = self._getresp()
Guido van Rossum484772d1998-04-06 18:27:27 +000096
Guido van Rossum03774bb1998-04-09 13:50:55 +000097
Tim Peters2344fae2001-01-15 00:50:52 +000098 def _putline(self, line):
Fred Drakea16433b2001-12-05 22:37:21 +000099 if self._debugging > 1: print '*put*', `line`
Martin v. Löwise12454f2002-02-16 23:06:19 +0000100 self.sock.sendall('%s%s' % (line, CRLF))
Guido van Rossum03774bb1998-04-09 13:50:55 +0000101
Guido van Rossum484772d1998-04-06 18:27:27 +0000102
Tim Peters2344fae2001-01-15 00:50:52 +0000103 # Internal: send one command to the server (through _putline())
Guido van Rossum03774bb1998-04-09 13:50:55 +0000104
Tim Peters2344fae2001-01-15 00:50:52 +0000105 def _putcmd(self, line):
Fred Drakea16433b2001-12-05 22:37:21 +0000106 if self._debugging: print '*cmd*', `line`
Tim Peters2344fae2001-01-15 00:50:52 +0000107 self._putline(line)
Guido van Rossum484772d1998-04-06 18:27:27 +0000108
Guido van Rossum03774bb1998-04-09 13:50:55 +0000109
Tim Peters2344fae2001-01-15 00:50:52 +0000110 # 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.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000113
Tim Peters2344fae2001-01-15 00:50:52 +0000114 def _getline(self):
115 line = self.file.readline()
Fred Drakea16433b2001-12-05 22:37:21 +0000116 if self._debugging > 1: print '*get*', `line`
Tim Peters2344fae2001-01-15 00:50:52 +0000117 if not line: raise error_proto('-ERR EOF')
118 octets = len(line)
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
124 if line[0] == CR:
125 return line[1:-1], octets
126 return line[:-1], octets
Guido van Rossum03774bb1998-04-09 13:50:55 +0000127
Guido van Rossum484772d1998-04-06 18:27:27 +0000128
Tim Peters2344fae2001-01-15 00:50:52 +0000129 # Internal: get a response from the server.
130 # Raise 'error_proto' if the response doesn't start with '+'.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000131
Tim Peters2344fae2001-01-15 00:50:52 +0000132 def _getresp(self):
133 resp, o = self._getline()
Fred Drakea16433b2001-12-05 22:37:21 +0000134 if self._debugging > 1: print '*resp*', `resp`
Tim Peters2344fae2001-01-15 00:50:52 +0000135 c = resp[:1]
136 if c != '+':
137 raise error_proto(resp)
138 return resp
Guido van Rossum484772d1998-04-06 18:27:27 +0000139
Guido van Rossum03774bb1998-04-09 13:50:55 +0000140
Tim Peters2344fae2001-01-15 00:50:52 +0000141 # Internal: get a response plus following text from the server.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000142
Tim Peters2344fae2001-01-15 00:50:52 +0000143 def _getlongresp(self):
144 resp = self._getresp()
145 list = []; octets = 0
146 line, o = self._getline()
147 while line != '.':
148 if line[:2] == '..':
149 o = o-1
150 line = line[1:]
151 octets = octets + o
152 list.append(line)
153 line, o = self._getline()
154 return resp, list, octets
Guido van Rossum03774bb1998-04-09 13:50:55 +0000155
Guido van Rossum484772d1998-04-06 18:27:27 +0000156
Tim Peters2344fae2001-01-15 00:50:52 +0000157 # Internal: send a command and get the response
Guido van Rossum03774bb1998-04-09 13:50:55 +0000158
Tim Peters2344fae2001-01-15 00:50:52 +0000159 def _shortcmd(self, line):
160 self._putcmd(line)
161 return self._getresp()
Guido van Rossum484772d1998-04-06 18:27:27 +0000162
Guido van Rossum03774bb1998-04-09 13:50:55 +0000163
Tim Peters2344fae2001-01-15 00:50:52 +0000164 # Internal: send a command and get the response plus following text
Guido van Rossum03774bb1998-04-09 13:50:55 +0000165
Tim Peters2344fae2001-01-15 00:50:52 +0000166 def _longcmd(self, line):
167 self._putcmd(line)
168 return self._getlongresp()
Guido van Rossum484772d1998-04-06 18:27:27 +0000169
Guido van Rossum03774bb1998-04-09 13:50:55 +0000170
Tim Peters2344fae2001-01-15 00:50:52 +0000171 # These can be useful:
172
173 def getwelcome(self):
174 return self.welcome
175
176
177 def set_debuglevel(self, level):
178 self._debugging = level
179
180
181 # Here are all the POP commands:
182
183 def user(self, user):
184 """Send user name, return response
Guido van Rossum484772d1998-04-06 18:27:27 +0000185
Tim Peters2344fae2001-01-15 00:50:52 +0000186 (should indicate password required).
187 """
188 return self._shortcmd('USER %s' % user)
Guido van Rossum484772d1998-04-06 18:27:27 +0000189
Guido van Rossum03774bb1998-04-09 13:50:55 +0000190
Tim Peters2344fae2001-01-15 00:50:52 +0000191 def pass_(self, pswd):
192 """Send password, return response
Guido van Rossum484772d1998-04-06 18:27:27 +0000193
Tim Peters2344fae2001-01-15 00:50:52 +0000194 (response includes message count, mailbox size).
Guido van Rossum03774bb1998-04-09 13:50:55 +0000195
Tim Peters2344fae2001-01-15 00:50:52 +0000196 NB: mailbox is locked by server from here to 'quit()'
197 """
198 return self._shortcmd('PASS %s' % pswd)
Guido van Rossum484772d1998-04-06 18:27:27 +0000199
Guido van Rossum03774bb1998-04-09 13:50:55 +0000200
Tim Peters2344fae2001-01-15 00:50:52 +0000201 def stat(self):
202 """Get mailbox status.
Guido van Rossum484772d1998-04-06 18:27:27 +0000203
Tim Peters2344fae2001-01-15 00:50:52 +0000204 Result is tuple of 2 ints (message count, mailbox size)
205 """
206 retval = self._shortcmd('STAT')
Eric S. Raymond341f9292001-02-09 06:56:56 +0000207 rets = retval.split()
Fred Drakea16433b2001-12-05 22:37:21 +0000208 if self._debugging: print '*stat*', `rets`
Eric S. Raymond341f9292001-02-09 06:56:56 +0000209 numMessages = int(rets[1])
210 sizeMessages = int(rets[2])
Tim Peters2344fae2001-01-15 00:50:52 +0000211 return (numMessages, sizeMessages)
Guido van Rossum03774bb1998-04-09 13:50:55 +0000212
Guido van Rossum03774bb1998-04-09 13:50:55 +0000213
Tim Peters2344fae2001-01-15 00:50:52 +0000214 def list(self, which=None):
215 """Request listing, return result.
Guido van Rossum484772d1998-04-06 18:27:27 +0000216
Tim Peters2344fae2001-01-15 00:50:52 +0000217 Result without a message number argument is in form
218 ['response', ['mesg_num octets', ...]].
Guido van Rossum484772d1998-04-06 18:27:27 +0000219
Tim Peters2344fae2001-01-15 00:50:52 +0000220 Result when a message number argument is given is a
221 single response: the "scan listing" for that message.
222 """
Raymond Hettinger16e3c422002-06-01 16:07:16 +0000223 if which is not None:
Tim Peters2344fae2001-01-15 00:50:52 +0000224 return self._shortcmd('LIST %s' % which)
225 return self._longcmd('LIST')
Guido van Rossum03774bb1998-04-09 13:50:55 +0000226
Guido van Rossum03774bb1998-04-09 13:50:55 +0000227
Tim Peters2344fae2001-01-15 00:50:52 +0000228 def retr(self, which):
229 """Retrieve whole message number 'which'.
Guido van Rossumf6ae7431998-09-02 14:42:02 +0000230
Tim Peters2344fae2001-01-15 00:50:52 +0000231 Result is in form ['response', ['line', ...], octets].
232 """
233 return self._longcmd('RETR %s' % which)
Guido van Rossum03774bb1998-04-09 13:50:55 +0000234
Guido van Rossum484772d1998-04-06 18:27:27 +0000235
Tim Peters2344fae2001-01-15 00:50:52 +0000236 def dele(self, which):
237 """Delete message number 'which'.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000238
Tim Peters2344fae2001-01-15 00:50:52 +0000239 Result is 'response'.
240 """
241 return self._shortcmd('DELE %s' % which)
Guido van Rossum03774bb1998-04-09 13:50:55 +0000242
Guido van Rossum484772d1998-04-06 18:27:27 +0000243
Tim Peters2344fae2001-01-15 00:50:52 +0000244 def noop(self):
245 """Does nothing.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000246
Tim Peters2344fae2001-01-15 00:50:52 +0000247 One supposes the response indicates the server is alive.
248 """
249 return self._shortcmd('NOOP')
Guido van Rossum03774bb1998-04-09 13:50:55 +0000250
Guido van Rossum484772d1998-04-06 18:27:27 +0000251
Tim Peters2344fae2001-01-15 00:50:52 +0000252 def rset(self):
253 """Not sure what this does."""
254 return self._shortcmd('RSET')
Guido van Rossum484772d1998-04-06 18:27:27 +0000255
Guido van Rossum03774bb1998-04-09 13:50:55 +0000256
Tim Peters2344fae2001-01-15 00:50:52 +0000257 def quit(self):
258 """Signoff: commit changes on server, unlock mailbox, close connection."""
259 try:
260 resp = self._shortcmd('QUIT')
261 except error_proto, val:
262 resp = val
263 self.file.close()
264 self.sock.close()
265 del self.file, self.sock
266 return resp
Guido van Rossum484772d1998-04-06 18:27:27 +0000267
Tim Peters2344fae2001-01-15 00:50:52 +0000268 #__del__ = quit
Guido van Rossum484772d1998-04-06 18:27:27 +0000269
Guido van Rossum484772d1998-04-06 18:27:27 +0000270
Tim Peters2344fae2001-01-15 00:50:52 +0000271 # optional commands:
Guido van Rossum03774bb1998-04-09 13:50:55 +0000272
Tim Peters2344fae2001-01-15 00:50:52 +0000273 def rpop(self, user):
274 """Not sure what this does."""
275 return self._shortcmd('RPOP %s' % user)
Guido van Rossum03774bb1998-04-09 13:50:55 +0000276
Guido van Rossum03774bb1998-04-09 13:50:55 +0000277
Moshe Zadkaccc2e3d2001-01-19 19:56:27 +0000278 timestamp = re.compile(r'\+OK.*(<[^>]+>)')
Guido van Rossum03774bb1998-04-09 13:50:55 +0000279
Tim Peters2344fae2001-01-15 00:50:52 +0000280 def apop(self, user, secret):
281 """Authorisation
Guido van Rossum03774bb1998-04-09 13:50:55 +0000282
Tim Peters2344fae2001-01-15 00:50:52 +0000283 - only possible if server has supplied a timestamp in initial greeting.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000284
Tim Peters2344fae2001-01-15 00:50:52 +0000285 Args:
286 user - mailbox user;
287 secret - secret shared between client and server.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000288
Tim Peters2344fae2001-01-15 00:50:52 +0000289 NB: mailbox is locked by server from here to 'quit()'
290 """
Moshe Zadkaccc2e3d2001-01-19 19:56:27 +0000291 m = self.timestamp.match(self.welcome)
292 if not m:
Tim Peters2344fae2001-01-15 00:50:52 +0000293 raise error_proto('-ERR APOP not supported by server')
294 import md5
Moshe Zadkaccc2e3d2001-01-19 19:56:27 +0000295 digest = md5.new(m.group(1)+secret).digest()
Eric S. Raymond341f9292001-02-09 06:56:56 +0000296 digest = ''.join(map(lambda x:'%02x'%ord(x), digest))
Tim Peters2344fae2001-01-15 00:50:52 +0000297 return self._shortcmd('APOP %s %s' % (user, digest))
Guido van Rossum03774bb1998-04-09 13:50:55 +0000298
Guido van Rossum03774bb1998-04-09 13:50:55 +0000299
Tim Peters2344fae2001-01-15 00:50:52 +0000300 def top(self, which, howmuch):
301 """Retrieve message header of message number 'which'
302 and first 'howmuch' lines of message body.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000303
Tim Peters2344fae2001-01-15 00:50:52 +0000304 Result is in form ['response', ['line', ...], octets].
305 """
306 return self._longcmd('TOP %s %s' % (which, howmuch))
Guido van Rossum03774bb1998-04-09 13:50:55 +0000307
Guido van Rossum03774bb1998-04-09 13:50:55 +0000308
Tim Peters2344fae2001-01-15 00:50:52 +0000309 def uidl(self, which=None):
310 """Return message digest (unique id) list.
Guido van Rossum03774bb1998-04-09 13:50:55 +0000311
Tim Peters2344fae2001-01-15 00:50:52 +0000312 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]
315 """
Raymond Hettinger16e3c422002-06-01 16:07:16 +0000316 if which is not None:
Tim Peters2344fae2001-01-15 00:50:52 +0000317 return self._shortcmd('UIDL %s' % which)
318 return self._longcmd('UIDL')
Guido van Rossum03774bb1998-04-09 13:50:55 +0000319
Guido van Rossum03774bb1998-04-09 13:50:55 +0000320
Guido van Rossum484772d1998-04-06 18:27:27 +0000321if __name__ == "__main__":
Eric S. Raymond341f9292001-02-09 06:56:56 +0000322 import sys
323 a = POP3(sys.argv[1])
Tim Peters2344fae2001-01-15 00:50:52 +0000324 print a.getwelcome()
Eric S. Raymond341f9292001-02-09 06:56:56 +0000325 a.user(sys.argv[2])
326 a.pass_(sys.argv[3])
Tim Peters2344fae2001-01-15 00:50:52 +0000327 a.list()
328 (numMsgs, totalSize) = a.stat()
329 for i in range(1, numMsgs + 1):
330 (header, msg, octets) = a.retr(i)
331 print "Message ", `i`, ':'
332 for line in msg:
333 print ' ' + line
334 print '-----------------------'
335 a.quit()