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