blob: 8f64ec17e4671e168bf04876ce905f4e123d2c2d [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
R. David Murray7dff9e02010-11-08 17:15:13 +00002import email.mime.text
Guido van Rossum04110fb2007-08-24 16:32:05 +00003import email.utils
Guido van Rossumd8faa362007-04-27 19:54:29 +00004import socket
Guido van Rossum806c2462007-08-06 23:33:07 +00005import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +00007import io
R. David Murray7dff9e02010-11-08 17:15:13 +00008import re
Guido van Rossum806c2462007-08-06 23:33:07 +00009import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import time
Guido van Rossum806c2462007-08-06 23:33:07 +000011import select
Ross Lagerwall86407432012-03-29 18:08:48 +020012import errno
Guido van Rossumd8faa362007-04-27 19:54:29 +000013
Victor Stinner45df8202010-04-28 22:31:17 +000014import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000015from test import support, mock_socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000016
Victor Stinner45df8202010-04-28 22:31:17 +000017try:
18 import threading
19except ImportError:
20 threading = None
21
Benjamin Petersonee8712c2008-05-20 21:35:26 +000022HOST = support.HOST
Guido van Rossumd8faa362007-04-27 19:54:29 +000023
Josiah Carlsond74900e2008-07-07 04:15:08 +000024if sys.platform == 'darwin':
25 # select.poll returns a select.POLLHUP at the end of the tests
26 # on darwin, so just ignore it
27 def handle_expt(self):
28 pass
29 smtpd.SMTPChannel.handle_expt = handle_expt
30
31
Christian Heimes5e696852008-04-09 08:37:03 +000032def server(evt, buf, serv):
Christian Heimes380f7f22008-02-28 11:19:05 +000033 serv.listen(5)
34 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000035 try:
36 conn, addr = serv.accept()
37 except socket.timeout:
38 pass
39 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000040 n = 500
41 while buf and n > 0:
42 r, w, e = select.select([], [conn], [])
43 if w:
44 sent = conn.send(buf)
45 buf = buf[sent:]
46
47 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000048
Guido van Rossumd8faa362007-04-27 19:54:29 +000049 conn.close()
50 finally:
51 serv.close()
52 evt.set()
53
Victor Stinner45df8202010-04-28 22:31:17 +000054class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000055
56 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000057 smtplib.socket = mock_socket
58 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000059
60 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000061 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000062
R. David Murray7dff9e02010-11-08 17:15:13 +000063 # This method is no longer used but is retained for backward compatibility,
64 # so test to make sure it still works.
65 def testQuoteData(self):
66 teststr = "abc\n.jkl\rfoo\r\n..blue"
67 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
68 self.assertEqual(expected, smtplib.quotedata(teststr))
69
Guido van Rossum806c2462007-08-06 23:33:07 +000070 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000071 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000072 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000073 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000074 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000075
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080076 def testSourceAddress(self):
77 mock_socket.reply_with(b"220 Hola mundo")
78 # connects
79 smtp = smtplib.SMTP(HOST, self.port,
80 source_address=('127.0.0.1',19876))
81 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
82 smtp.close()
83
Guido van Rossum806c2462007-08-06 23:33:07 +000084 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000085 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000086 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000087 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000088 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000089
90 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000091 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000092 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000093 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000094 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000095 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000096
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000098 mock_socket.reply_with(b"220 Hola mundo")
Richard Jones64b02de2010-08-03 06:39:33 +000099 self.assertTrue(mock_socket.getdefaulttimeout() is None)
100 mock_socket.setdefaulttimeout(30)
101 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000102 try:
103 smtp = smtplib.SMTP(HOST, self.port)
104 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000105 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000107 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108
109 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000110 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000111 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 socket.setdefaulttimeout(30)
113 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000114 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000116 socket.setdefaulttimeout(None)
117 self.assertTrue(smtp.sock.gettimeout() is None)
118 smtp.close()
119
120 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000121 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000122 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000124 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000125
126
Guido van Rossum04110fb2007-08-24 16:32:05 +0000127# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000128def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000129 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000130
131 try:
132 if hasattr(select, 'poll'):
133 poll_fun = asyncore.poll2
134 else:
135 poll_fun = asyncore.poll
136
137 n = 1000
138 while asyncore.socket_map and n > 0:
139 poll_fun(0.01, asyncore.socket_map)
140
141 # when the client conversation is finished, it will
142 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000143 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000144 serv.close()
145 break
146
147 n -= 1
148
149 except socket.timeout:
150 pass
151 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000152 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000153 # allow some time for the client to read the result
154 time.sleep(0.5)
155 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000156 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000157 serv_evt.set()
158
159MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
160MSG_END = '------------ END MESSAGE ------------\n'
161
Guido van Rossum04110fb2007-08-24 16:32:05 +0000162# NOTE: Some SMTP objects in the tests below are created with a non-default
163# local_hostname argument to the constructor, since (on some systems) the FQDN
164# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000165# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000166
167# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000168@unittest.skipUnless(threading, 'Threading required for this test.')
169class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000170
R. David Murray7dff9e02010-11-08 17:15:13 +0000171 maxDiff = None
172
Guido van Rossum806c2462007-08-06 23:33:07 +0000173 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000174 self.real_getfqdn = socket.getfqdn
175 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000176 # temporarily replace sys.stdout to capture DebuggingServer output
177 self.old_stdout = sys.stdout
178 self.output = io.StringIO()
179 sys.stdout = self.output
180
181 self.serv_evt = threading.Event()
182 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000183 # Capture SMTPChannel debug output
184 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
185 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000186 # Pick a random unused port by passing 0 for the port number
187 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
188 # Keep a note of what port was assigned
189 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000190 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000191 self.thread = threading.Thread(target=debugging_server, args=serv_args)
192 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000193
194 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000195 self.serv_evt.wait()
196 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000197
198 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000199 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000200 # indicate that the client is finished
201 self.client_evt.set()
202 # wait for the server thread to terminate
203 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000204 self.thread.join()
Guido van Rossum806c2462007-08-06 23:33:07 +0000205 # restore sys.stdout
206 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000207 # restore DEBUGSTREAM
208 smtpd.DEBUGSTREAM.close()
209 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000210
211 def testBasic(self):
212 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000213 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000214 smtp.quit()
215
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800216 def testSourceAddress(self):
217 # connect
Senthil Kumaranb351a482011-07-31 09:14:17 +0800218 port = support.find_unused_port()
219 try:
220 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
221 timeout=3, source_address=('127.0.0.1', port))
222 self.assertEqual(smtp.source_address, ('127.0.0.1', port))
223 self.assertEqual(smtp.local_hostname, 'localhost')
224 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200225 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800226 if e.errno == errno.EADDRINUSE:
227 self.skipTest("couldn't bind to port %d" % port)
228 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800229
Guido van Rossum04110fb2007-08-24 16:32:05 +0000230 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000231 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400232 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000233 self.assertEqual(smtp.noop(), expected)
234 smtp.quit()
235
236 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000237 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400238 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000239 self.assertEqual(smtp.rset(), expected)
240 smtp.quit()
241
242 def testNotImplemented(self):
243 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000244 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000245 expected = (502, b'Error: command "EHLO" not implemented')
246 self.assertEqual(smtp.ehlo(), expected)
247 smtp.quit()
248
R David Murrayd1a30c92012-05-26 14:33:59 -0400249 def testNotImplemented(self):
250 # EXPN isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000251 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400252 expected = (502, b'EXPN not implemented')
253 smtp.putcmd('EXPN')
254 self.assertEqual(smtp.getreply(), expected)
255 smtp.quit()
256
257 def testVRFY(self):
258 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
259 expected = (252, b'Cannot VRFY user, but will accept message ' + \
260 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000261 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
262 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
263 smtp.quit()
264
265 def testSecondHELO(self):
266 # check that a second HELO returns a message that it's a duplicate
267 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000268 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000269 smtp.helo()
270 expected = (503, b'Duplicate HELO/EHLO')
271 self.assertEqual(smtp.helo(), expected)
272 smtp.quit()
273
Guido van Rossum806c2462007-08-06 23:33:07 +0000274 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000275 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400276 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
277 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000278 smtp.quit()
279
280 def testSend(self):
281 # connect and send mail
282 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000283 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000284 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000285 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
286 # in asyncore. This sleep might help, but should really be fixed
287 # properly by using an Event variable.
288 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000289 smtp.quit()
290
291 self.client_evt.set()
292 self.serv_evt.wait()
293 self.output.flush()
294 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
295 self.assertEqual(self.output.getvalue(), mexpect)
296
R. David Murray7dff9e02010-11-08 17:15:13 +0000297 def testSendBinary(self):
298 m = b'A test message'
299 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
300 smtp.sendmail('John', 'Sally', m)
301 # XXX (see comment in testSend)
302 time.sleep(0.01)
303 smtp.quit()
304
305 self.client_evt.set()
306 self.serv_evt.wait()
307 self.output.flush()
308 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
309 self.assertEqual(self.output.getvalue(), mexpect)
310
R David Murray0f663d02011-06-09 15:05:57 -0400311 def testSendNeedingDotQuote(self):
312 # Issue 12283
313 m = '.A test\n.mes.sage.'
314 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
315 smtp.sendmail('John', 'Sally', m)
316 # XXX (see comment in testSend)
317 time.sleep(0.01)
318 smtp.quit()
319
320 self.client_evt.set()
321 self.serv_evt.wait()
322 self.output.flush()
323 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
324 self.assertEqual(self.output.getvalue(), mexpect)
325
R David Murray46346762011-07-18 21:38:54 -0400326 def testSendNullSender(self):
327 m = 'A test message'
328 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
329 smtp.sendmail('<>', 'Sally', m)
330 # XXX (see comment in testSend)
331 time.sleep(0.01)
332 smtp.quit()
333
334 self.client_evt.set()
335 self.serv_evt.wait()
336 self.output.flush()
337 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
338 self.assertEqual(self.output.getvalue(), mexpect)
339 debugout = smtpd.DEBUGSTREAM.getvalue()
340 sender = re.compile("^sender: <>$", re.MULTILINE)
341 self.assertRegex(debugout, sender)
342
R. David Murray7dff9e02010-11-08 17:15:13 +0000343 def testSendMessage(self):
344 m = email.mime.text.MIMEText('A test message')
345 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
346 smtp.send_message(m, from_addr='John', to_addrs='Sally')
347 # XXX (see comment in testSend)
348 time.sleep(0.01)
349 smtp.quit()
350
351 self.client_evt.set()
352 self.serv_evt.wait()
353 self.output.flush()
354 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400355 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000356 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
357 self.assertEqual(self.output.getvalue(), mexpect)
358
359 def testSendMessageWithAddresses(self):
360 m = email.mime.text.MIMEText('A test message')
361 m['From'] = 'foo@bar.com'
362 m['To'] = 'John'
363 m['CC'] = 'Sally, Fred'
364 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
365 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
366 smtp.send_message(m)
367 # XXX (see comment in testSend)
368 time.sleep(0.01)
369 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400370 # make sure the Bcc header is still in the message.
371 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
372 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000373
374 self.client_evt.set()
375 self.serv_evt.wait()
376 self.output.flush()
377 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400378 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400379 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000380 del m['Bcc']
381 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
382 self.assertEqual(self.output.getvalue(), mexpect)
383 debugout = smtpd.DEBUGSTREAM.getvalue()
384 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000385 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000386 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
387 'warped@silly.walks.com'):
388 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
389 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000390 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000391
392 def testSendMessageWithSomeAddresses(self):
393 # Make sure nothing breaks if not all of the three 'to' headers exist
394 m = email.mime.text.MIMEText('A test message')
395 m['From'] = 'foo@bar.com'
396 m['To'] = 'John, Dinsdale'
397 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
398 smtp.send_message(m)
399 # XXX (see comment in testSend)
400 time.sleep(0.01)
401 smtp.quit()
402
403 self.client_evt.set()
404 self.serv_evt.wait()
405 self.output.flush()
406 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400407 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000408 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
409 self.assertEqual(self.output.getvalue(), mexpect)
410 debugout = smtpd.DEBUGSTREAM.getvalue()
411 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000412 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000413 for addr in ('John', 'Dinsdale'):
414 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
415 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000416 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000417
R David Murrayac4e5ab2011-07-02 21:03:19 -0400418 def testSendMessageWithSpecifiedAddresses(self):
419 # Make sure addresses specified in call override those in message.
420 m = email.mime.text.MIMEText('A test message')
421 m['From'] = 'foo@bar.com'
422 m['To'] = 'John, Dinsdale'
423 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
424 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
425 # XXX (see comment in testSend)
426 time.sleep(0.01)
427 smtp.quit()
428
429 self.client_evt.set()
430 self.serv_evt.wait()
431 self.output.flush()
432 # Add the X-Peer header that DebuggingServer adds
433 m['X-Peer'] = socket.gethostbyname('localhost')
434 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
435 self.assertEqual(self.output.getvalue(), mexpect)
436 debugout = smtpd.DEBUGSTREAM.getvalue()
437 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
438 self.assertRegex(debugout, sender)
439 for addr in ('John', 'Dinsdale'):
440 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
441 re.MULTILINE)
442 self.assertNotRegex(debugout, to_addr)
443 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
444 self.assertRegex(debugout, recip)
445
446 def testSendMessageWithMultipleFrom(self):
447 # Sender overrides To
448 m = email.mime.text.MIMEText('A test message')
449 m['From'] = 'Bernard, Bianca'
450 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
451 m['To'] = 'John, Dinsdale'
452 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
453 smtp.send_message(m)
454 # XXX (see comment in testSend)
455 time.sleep(0.01)
456 smtp.quit()
457
458 self.client_evt.set()
459 self.serv_evt.wait()
460 self.output.flush()
461 # Add the X-Peer header that DebuggingServer adds
462 m['X-Peer'] = socket.gethostbyname('localhost')
463 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
464 self.assertEqual(self.output.getvalue(), mexpect)
465 debugout = smtpd.DEBUGSTREAM.getvalue()
466 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
467 self.assertRegex(debugout, sender)
468 for addr in ('John', 'Dinsdale'):
469 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
470 re.MULTILINE)
471 self.assertRegex(debugout, to_addr)
472
473 def testSendMessageResent(self):
474 m = email.mime.text.MIMEText('A test message')
475 m['From'] = 'foo@bar.com'
476 m['To'] = 'John'
477 m['CC'] = 'Sally, Fred'
478 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
479 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
480 m['Resent-From'] = 'holy@grail.net'
481 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
482 m['Resent-Bcc'] = 'doe@losthope.net'
483 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
484 smtp.send_message(m)
485 # XXX (see comment in testSend)
486 time.sleep(0.01)
487 smtp.quit()
488
489 self.client_evt.set()
490 self.serv_evt.wait()
491 self.output.flush()
492 # The Resent-Bcc headers are deleted before serialization.
493 del m['Bcc']
494 del m['Resent-Bcc']
495 # Add the X-Peer header that DebuggingServer adds
496 m['X-Peer'] = socket.gethostbyname('localhost')
497 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
498 self.assertEqual(self.output.getvalue(), mexpect)
499 debugout = smtpd.DEBUGSTREAM.getvalue()
500 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
501 self.assertRegex(debugout, sender)
502 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
503 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
504 re.MULTILINE)
505 self.assertRegex(debugout, to_addr)
506
507 def testSendMessageMultipleResentRaises(self):
508 m = email.mime.text.MIMEText('A test message')
509 m['From'] = 'foo@bar.com'
510 m['To'] = 'John'
511 m['CC'] = 'Sally, Fred'
512 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
513 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
514 m['Resent-From'] = 'holy@grail.net'
515 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
516 m['Resent-Bcc'] = 'doe@losthope.net'
517 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
518 m['Resent-To'] = 'holy@grail.net'
519 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
520 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
521 with self.assertRaises(ValueError):
522 smtp.send_message(m)
523 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000524
Victor Stinner45df8202010-04-28 22:31:17 +0000525class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000526
527 def testNotConnected(self):
528 # Test various operations on an unconnected SMTP object that
529 # should raise exceptions (at present the attempt in SMTP.send
530 # to reference the nonexistent 'sock' attribute of the SMTP object
531 # causes an AttributeError)
532 smtp = smtplib.SMTP()
533 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
534 self.assertRaises(smtplib.SMTPServerDisconnected,
535 smtp.send, 'test msg')
536
537 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200538 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200539 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000540 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200541 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000542 "localhost:bogus")
543
544
Guido van Rossum04110fb2007-08-24 16:32:05 +0000545# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000546@unittest.skipUnless(threading, 'Threading required for this test.')
547class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000548
549 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000550 smtplib.socket = mock_socket
551 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000552 self.old_stdout = sys.stdout
553 self.output = io.StringIO()
554 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000555 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000556
557 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000558 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000559 sys.stdout = self.old_stdout
560
561 def testFailingHELO(self):
562 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000563 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000564
Guido van Rossum04110fb2007-08-24 16:32:05 +0000565
566sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400567 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000568 'Mrs.C@somewhereesle.com':'Ruth C',
569 }
570
R. David Murraycaa27b72009-05-23 18:49:56 +0000571sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000572sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
573 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
574sim_auth_credentials = {
575 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
576 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
577 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
578 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
579 }
580sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murraycaa27b72009-05-23 18:49:56 +0000581
Guido van Rossum04110fb2007-08-24 16:32:05 +0000582sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400583 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000584 }
585
586# Simulated SMTP channel & server
587class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000588
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400589 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400590 mail_response = None
591 rcpt_response = None
592 data_response = None
593 rcpt_count = 0
594 rset_count = 0
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400595
R. David Murray23ddc0e2009-05-29 18:03:16 +0000596 def __init__(self, extra_features, *args, **kw):
597 self._extrafeatures = ''.join(
598 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000599 super(SimSMTPChannel, self).__init__(*args, **kw)
600
Guido van Rossum04110fb2007-08-24 16:32:05 +0000601 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000602 resp = ('250-testhost\r\n'
603 '250-EXPN\r\n'
604 '250-SIZE 20000000\r\n'
605 '250-STARTTLS\r\n'
606 '250-DELIVERBY\r\n')
607 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000608 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400609 self.seen_greeting = arg
610 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000611
612 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400613 # For max compatibility smtplib should be sending the raw address.
614 if arg in sim_users:
615 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000616 else:
617 self.push('550 No such user: %s' % arg)
618
619 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400620 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000621 if list_name in sim_lists:
622 user_list = sim_lists[list_name]
623 for n, user_email in enumerate(user_list):
624 quoted_addr = smtplib.quoteaddr(user_email)
625 if n < len(user_list) - 1:
626 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
627 else:
628 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
629 else:
630 self.push('550 No access for you!')
631
R. David Murraycaa27b72009-05-23 18:49:56 +0000632 def smtp_AUTH(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000633 if arg.strip().lower()=='cram-md5':
634 self.push('334 {}'.format(sim_cram_md5_challenge))
635 return
R. David Murraycaa27b72009-05-23 18:49:56 +0000636 mech, auth = arg.split()
R. David Murrayfb123912009-05-28 18:19:00 +0000637 mech = mech.lower()
638 if mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000639 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000640 return
641 if mech == 'plain' and auth==sim_auth_credentials['plain']:
642 self.push('235 plain auth ok')
643 elif mech=='login' and auth==sim_auth_credentials['login']:
644 self.push('334 Password:')
645 else:
646 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000647
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400648 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400649 if self.quit_response is None:
650 super(SimSMTPChannel, self).smtp_QUIT(arg)
651 else:
652 self.push(self.quit_response)
653 self.close_when_done()
654
R David Murrayd312c742013-03-20 20:36:14 -0400655 def smtp_MAIL(self, arg):
656 if self.mail_response is None:
657 super().smtp_MAIL(arg)
658 else:
659 self.push(self.mail_response)
660
661 def smtp_RCPT(self, arg):
662 if self.rcpt_response is None:
663 super().smtp_RCPT(arg)
664 return
R David Murrayd312c742013-03-20 20:36:14 -0400665 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400666 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400667
668 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400669 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400670 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400671
672 def smtp_DATA(self, arg):
673 if self.data_response is None:
674 super().smtp_DATA(arg)
675 else:
676 self.push(self.data_response)
677
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000678 def handle_error(self):
679 raise
680
Guido van Rossum04110fb2007-08-24 16:32:05 +0000681
682class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000683
R David Murrayd312c742013-03-20 20:36:14 -0400684 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400685
R. David Murray23ddc0e2009-05-29 18:03:16 +0000686 def __init__(self, *args, **kw):
687 self._extra_features = []
688 smtpd.SMTPServer.__init__(self, *args, **kw)
689
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000690 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400691 self._SMTPchannel = self.channel_class(
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400692 self._extra_features, self, conn, addr)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000693
694 def process_message(self, peer, mailfrom, rcpttos, data):
695 pass
696
R. David Murrayfb123912009-05-28 18:19:00 +0000697 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000698 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000699
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000700 def handle_error(self):
701 raise
702
Guido van Rossum04110fb2007-08-24 16:32:05 +0000703
704# Test various SMTP & ESMTP commands/behaviors that require a simulated server
705# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000706@unittest.skipUnless(threading, 'Threading required for this test.')
707class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000708
709 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000710 self.real_getfqdn = socket.getfqdn
711 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000712 self.serv_evt = threading.Event()
713 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000714 # Pick a random unused port by passing 0 for the port number
715 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
716 # Keep a note of what port was assigned
717 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000718 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000719 self.thread = threading.Thread(target=debugging_server, args=serv_args)
720 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000721
722 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000723 self.serv_evt.wait()
724 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000725
726 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000727 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000728 # indicate that the client is finished
729 self.client_evt.set()
730 # wait for the server thread to terminate
731 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000732 self.thread.join()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000733
734 def testBasic(self):
735 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000736 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000737 smtp.quit()
738
739 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000740 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000741
742 # no features should be present before the EHLO
743 self.assertEqual(smtp.esmtp_features, {})
744
745 # features expected from the test server
746 expected_features = {'expn':'',
747 'size': '20000000',
748 'starttls': '',
749 'deliverby': '',
750 'help': '',
751 }
752
753 smtp.ehlo()
754 self.assertEqual(smtp.esmtp_features, expected_features)
755 for k in expected_features:
756 self.assertTrue(smtp.has_extn(k))
757 self.assertFalse(smtp.has_extn('unsupported-feature'))
758 smtp.quit()
759
760 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000761 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000762
763 for email, name in sim_users.items():
764 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000765 (name, smtplib.quoteaddr(email)),
766 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000767 self.assertEqual(smtp.vrfy(email), expected_known)
768
769 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400770 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000771 self.assertEqual(smtp.vrfy(u), expected_unknown)
772 smtp.quit()
773
774 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000775 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000776
777 for listname, members in sim_lists.items():
778 users = []
779 for m in members:
780 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000781 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000782 self.assertEqual(smtp.expn(listname), expected_known)
783
784 u = 'PSU-Members-List'
785 expected_unknown = (550, b'No access for you!')
786 self.assertEqual(smtp.expn(u), expected_unknown)
787 smtp.quit()
788
R. David Murrayfb123912009-05-28 18:19:00 +0000789 def testAUTH_PLAIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000790 self.serv.add_feature("AUTH PLAIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000791 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murraycaa27b72009-05-23 18:49:56 +0000792
R. David Murrayfb123912009-05-28 18:19:00 +0000793 expected_auth_ok = (235, b'plain auth ok')
R. David Murraycaa27b72009-05-23 18:49:56 +0000794 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Benjamin Petersond094efd2010-10-31 17:15:42 +0000795 smtp.close()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000796
R. David Murrayfb123912009-05-28 18:19:00 +0000797 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
798 # require a synchronous read to obtain the credentials...so instead smtpd
799 # sees the credential sent by smtplib's login method as an unknown command,
800 # which results in smtplib raising an auth error. Fortunately the error
801 # message contains the encoded credential, so we can partially check that it
802 # was generated correctly (partially, because the 'word' is uppercased in
803 # the error message).
804
805 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000806 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000807 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000808 try: smtp.login(sim_auth[0], sim_auth[1])
809 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000810 self.assertIn(sim_auth_login_password, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000811 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000812
813 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000814 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000815 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000816
817 try: smtp.login(sim_auth[0], sim_auth[1])
818 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000819 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000820 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000821
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400822 def test_with_statement(self):
823 with smtplib.SMTP(HOST, self.port) as smtp:
824 code, message = smtp.noop()
825 self.assertEqual(code, 250)
826 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
827 with smtplib.SMTP(HOST, self.port) as smtp:
828 smtp.close()
829 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
830
831 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400832 with self.assertRaises(smtplib.SMTPResponseException) as error:
833 with smtplib.SMTP(HOST, self.port) as smtp:
834 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -0400835 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400836 self.assertEqual(error.exception.smtp_code, 421)
837 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400838
R. David Murrayfb123912009-05-28 18:19:00 +0000839 #TODO: add tests for correct AUTH method fallback now that the
840 #test infrastructure can support it.
841
R David Murrayd312c742013-03-20 20:36:14 -0400842 # Issue 5713: make sure close, not rset, is called if we get a 421 error
843 def test_421_from_mail_cmd(self):
844 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400845 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400846 self.serv._SMTPchannel.mail_response = '421 closing connection'
847 with self.assertRaises(smtplib.SMTPSenderRefused):
848 smtp.sendmail('John', 'Sally', 'test message')
849 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -0400850 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -0400851
852 def test_421_from_rcpt_cmd(self):
853 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400854 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400855 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
856 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
857 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
858 self.assertIsNone(smtp.sock)
859 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
860 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
861
862 def test_421_from_data_cmd(self):
863 class MySimSMTPChannel(SimSMTPChannel):
864 def found_terminator(self):
865 if self.smtp_state == self.DATA:
866 self.push('421 closing')
867 else:
868 super().found_terminator()
869 self.serv.channel_class = MySimSMTPChannel
870 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -0400871 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -0400872 with self.assertRaises(smtplib.SMTPDataError):
873 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
874 self.assertIsNone(smtp.sock)
875 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
876
Guido van Rossum04110fb2007-08-24 16:32:05 +0000877
Antoine Pitroud54fa552011-08-28 01:23:52 +0200878@support.reap_threads
Guido van Rossumd8faa362007-04-27 19:54:29 +0000879def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000880 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000881 NonConnectingTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000882 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000883
884if __name__ == '__main__':
885 test_main()