blob: 040ad4e05962ba5e31fc7ab2439e81dc7e02b8e6 [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
R David Murrayb0deeb42015-11-08 01:03:52 -05002import base64
R. David Murray7dff9e02010-11-08 17:15:13 +00003import email.mime.text
R David Murray83084442015-05-17 19:27:22 -04004from email.message import EmailMessage
Barry Warsawc5ea7542015-07-09 10:39:55 -04005from email.base64mime import body_encode as encode_base64
Guido van Rossum04110fb2007-08-24 16:32:05 +00006import email.utils
R David Murrayb0deeb42015-11-08 01:03:52 -05007import hmac
Guido van Rossumd8faa362007-04-27 19:54:29 +00008import socket
Guido van Rossum806c2462007-08-06 23:33:07 +00009import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +000011import io
R. David Murray7dff9e02010-11-08 17:15:13 +000012import re
Guido van Rossum806c2462007-08-06 23:33:07 +000013import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000014import time
Guido van Rossum806c2462007-08-06 23:33:07 +000015import select
Ross Lagerwall86407432012-03-29 18:08:48 +020016import errno
R David Murray83084442015-05-17 19:27:22 -040017import textwrap
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020018import threading
Guido van Rossumd8faa362007-04-27 19:54:29 +000019
Victor Stinner45df8202010-04-28 22:31:17 +000020import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000021from test import support, mock_socket
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -070022from test.support import HOST, HOSTv4, HOSTv6
Guido van Rossumd8faa362007-04-27 19:54:29 +000023
Victor Stinner45df8202010-04-28 22:31:17 +000024
Josiah Carlsond74900e2008-07-07 04:15:08 +000025if sys.platform == 'darwin':
26 # select.poll returns a select.POLLHUP at the end of the tests
27 # on darwin, so just ignore it
28 def handle_expt(self):
29 pass
30 smtpd.SMTPChannel.handle_expt = handle_expt
31
32
Christian Heimes5e696852008-04-09 08:37:03 +000033def server(evt, buf, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +010034 serv.listen()
Christian Heimes380f7f22008-02-28 11:19:05 +000035 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000036 try:
37 conn, addr = serv.accept()
38 except socket.timeout:
39 pass
40 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000041 n = 500
42 while buf and n > 0:
43 r, w, e = select.select([], [conn], [])
44 if w:
45 sent = conn.send(buf)
46 buf = buf[sent:]
47
48 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000049
Guido van Rossumd8faa362007-04-27 19:54:29 +000050 conn.close()
51 finally:
52 serv.close()
53 evt.set()
54
Victor Stinner45df8202010-04-28 22:31:17 +000055class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000056
57 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000058 smtplib.socket = mock_socket
59 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000060
61 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000062 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000063
R. David Murray7dff9e02010-11-08 17:15:13 +000064 # This method is no longer used but is retained for backward compatibility,
65 # so test to make sure it still works.
66 def testQuoteData(self):
67 teststr = "abc\n.jkl\rfoo\r\n..blue"
68 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
69 self.assertEqual(expected, smtplib.quotedata(teststr))
70
Guido van Rossum806c2462007-08-06 23:33:07 +000071 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000072 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000073 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000074 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000075 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000076
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080077 def testSourceAddress(self):
78 mock_socket.reply_with(b"220 Hola mundo")
79 # connects
80 smtp = smtplib.SMTP(HOST, self.port,
81 source_address=('127.0.0.1',19876))
82 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
83 smtp.close()
84
Guido van Rossum806c2462007-08-06 23:33:07 +000085 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000086 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000087 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000088 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000089 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000090
91 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000092 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000093 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000094 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000095 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000096 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000097
Guido van Rossumd8faa362007-04-27 19:54:29 +000098 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000099 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200100 self.assertIsNone(mock_socket.getdefaulttimeout())
Richard Jones64b02de2010-08-03 06:39:33 +0000101 mock_socket.setdefaulttimeout(30)
102 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000103 try:
104 smtp = smtplib.SMTP(HOST, self.port)
105 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000106 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000108 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000109
110 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000111 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200112 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113 socket.setdefaulttimeout(30)
114 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000115 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000116 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000117 socket.setdefaulttimeout(None)
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200118 self.assertIsNone(smtp.sock.gettimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000119 smtp.close()
120
121 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000122 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000123 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000125 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126
R David Murray0c49b892015-04-16 17:14:42 -0400127 def test_debuglevel(self):
128 mock_socket.reply_with(b"220 Hello world")
129 smtp = smtplib.SMTP()
130 smtp.set_debuglevel(1)
131 with support.captured_stderr() as stderr:
132 smtp.connect(HOST, self.port)
133 smtp.close()
134 expected = re.compile(r"^connect:", re.MULTILINE)
135 self.assertRegex(stderr.getvalue(), expected)
136
137 def test_debuglevel_2(self):
138 mock_socket.reply_with(b"220 Hello world")
139 smtp = smtplib.SMTP()
140 smtp.set_debuglevel(2)
141 with support.captured_stderr() as stderr:
142 smtp.connect(HOST, self.port)
143 smtp.close()
144 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
145 re.MULTILINE)
146 self.assertRegex(stderr.getvalue(), expected)
147
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148
Guido van Rossum04110fb2007-08-24 16:32:05 +0000149# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000150def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000151 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000152
153 try:
154 if hasattr(select, 'poll'):
155 poll_fun = asyncore.poll2
156 else:
157 poll_fun = asyncore.poll
158
159 n = 1000
160 while asyncore.socket_map and n > 0:
161 poll_fun(0.01, asyncore.socket_map)
162
163 # when the client conversation is finished, it will
164 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000165 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000166 serv.close()
167 break
168
169 n -= 1
170
171 except socket.timeout:
172 pass
173 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000174 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000175 # allow some time for the client to read the result
176 time.sleep(0.5)
177 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000178 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000179 serv_evt.set()
180
181MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
182MSG_END = '------------ END MESSAGE ------------\n'
183
Guido van Rossum04110fb2007-08-24 16:32:05 +0000184# NOTE: Some SMTP objects in the tests below are created with a non-default
185# local_hostname argument to the constructor, since (on some systems) the FQDN
186# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000187# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000188
189# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000190class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000191
R. David Murray7dff9e02010-11-08 17:15:13 +0000192 maxDiff = None
193
Guido van Rossum806c2462007-08-06 23:33:07 +0000194 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000195 self.real_getfqdn = socket.getfqdn
196 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000197 # temporarily replace sys.stdout to capture DebuggingServer output
198 self.old_stdout = sys.stdout
199 self.output = io.StringIO()
200 sys.stdout = self.output
201
202 self.serv_evt = threading.Event()
203 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000204 # Capture SMTPChannel debug output
205 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
206 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000207 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400208 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
209 decode_data=True)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700210 # Keep a note of what server host and port were assigned
211 self.host, self.port = self.serv.socket.getsockname()[:2]
Christian Heimes5e696852008-04-09 08:37:03 +0000212 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000213 self.thread = threading.Thread(target=debugging_server, args=serv_args)
214 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000215
216 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000217 self.serv_evt.wait()
218 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000219
220 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000221 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000222 # indicate that the client is finished
223 self.client_evt.set()
224 # wait for the server thread to terminate
225 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000226 self.thread.join()
Guido van Rossum806c2462007-08-06 23:33:07 +0000227 # restore sys.stdout
228 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000229 # restore DEBUGSTREAM
230 smtpd.DEBUGSTREAM.close()
231 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000232
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700233 def get_output_without_xpeer(self):
234 test_output = self.output.getvalue()
235 return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2',
236 test_output, flags=re.MULTILINE|re.DOTALL)
237
Guido van Rossum806c2462007-08-06 23:33:07 +0000238 def testBasic(self):
239 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000240 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000241 smtp.quit()
242
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800243 def testSourceAddress(self):
244 # connect
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700245 src_port = support.find_unused_port()
Senthil Kumaranb351a482011-07-31 09:14:17 +0800246 try:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700247 smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost',
248 timeout=3, source_address=(self.host, src_port))
249 self.assertEqual(smtp.source_address, (self.host, src_port))
Senthil Kumaranb351a482011-07-31 09:14:17 +0800250 self.assertEqual(smtp.local_hostname, 'localhost')
251 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200252 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800253 if e.errno == errno.EADDRINUSE:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700254 self.skipTest("couldn't bind to source port %d" % src_port)
Senthil Kumaranb351a482011-07-31 09:14:17 +0800255 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800256
Guido van Rossum04110fb2007-08-24 16:32:05 +0000257 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000258 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400259 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000260 self.assertEqual(smtp.noop(), expected)
261 smtp.quit()
262
263 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000264 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400265 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000266 self.assertEqual(smtp.rset(), expected)
267 smtp.quit()
268
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400269 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000270 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000271 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400272 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000273 self.assertEqual(smtp.ehlo(), expected)
274 smtp.quit()
275
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400276 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400277 # EXPN isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000278 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400279 expected = (502, b'EXPN not implemented')
280 smtp.putcmd('EXPN')
281 self.assertEqual(smtp.getreply(), expected)
282 smtp.quit()
283
284 def testVRFY(self):
285 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
286 expected = (252, b'Cannot VRFY user, but will accept message ' + \
287 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000288 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
289 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
290 smtp.quit()
291
292 def testSecondHELO(self):
293 # check that a second HELO returns a message that it's a duplicate
294 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000295 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000296 smtp.helo()
297 expected = (503, b'Duplicate HELO/EHLO')
298 self.assertEqual(smtp.helo(), expected)
299 smtp.quit()
300
Guido van Rossum806c2462007-08-06 23:33:07 +0000301 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000302 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
R David Murrayd1a30c92012-05-26 14:33:59 -0400303 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
304 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000305 smtp.quit()
306
307 def testSend(self):
308 # connect and send mail
309 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000310 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000311 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000312 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
313 # in asyncore. This sleep might help, but should really be fixed
314 # properly by using an Event variable.
315 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000316 smtp.quit()
317
318 self.client_evt.set()
319 self.serv_evt.wait()
320 self.output.flush()
321 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
322 self.assertEqual(self.output.getvalue(), mexpect)
323
R. David Murray7dff9e02010-11-08 17:15:13 +0000324 def testSendBinary(self):
325 m = b'A test message'
326 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
327 smtp.sendmail('John', 'Sally', m)
328 # XXX (see comment in testSend)
329 time.sleep(0.01)
330 smtp.quit()
331
332 self.client_evt.set()
333 self.serv_evt.wait()
334 self.output.flush()
335 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
336 self.assertEqual(self.output.getvalue(), mexpect)
337
R David Murray0f663d02011-06-09 15:05:57 -0400338 def testSendNeedingDotQuote(self):
339 # Issue 12283
340 m = '.A test\n.mes.sage.'
341 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
342 smtp.sendmail('John', 'Sally', m)
343 # XXX (see comment in testSend)
344 time.sleep(0.01)
345 smtp.quit()
346
347 self.client_evt.set()
348 self.serv_evt.wait()
349 self.output.flush()
350 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
351 self.assertEqual(self.output.getvalue(), mexpect)
352
R David Murray46346762011-07-18 21:38:54 -0400353 def testSendNullSender(self):
354 m = 'A test message'
355 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
356 smtp.sendmail('<>', 'Sally', m)
357 # XXX (see comment in testSend)
358 time.sleep(0.01)
359 smtp.quit()
360
361 self.client_evt.set()
362 self.serv_evt.wait()
363 self.output.flush()
364 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
365 self.assertEqual(self.output.getvalue(), mexpect)
366 debugout = smtpd.DEBUGSTREAM.getvalue()
367 sender = re.compile("^sender: <>$", re.MULTILINE)
368 self.assertRegex(debugout, sender)
369
R. David Murray7dff9e02010-11-08 17:15:13 +0000370 def testSendMessage(self):
371 m = email.mime.text.MIMEText('A test message')
372 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
373 smtp.send_message(m, from_addr='John', to_addrs='Sally')
374 # XXX (see comment in testSend)
375 time.sleep(0.01)
376 smtp.quit()
377
378 self.client_evt.set()
379 self.serv_evt.wait()
380 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700381 # Remove the X-Peer header that DebuggingServer adds as figuring out
382 # exactly what IP address format is put there is not easy (and
383 # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is
384 # not always the same as socket.gethostbyname(HOST). :(
385 test_output = self.get_output_without_xpeer()
386 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000387 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700388 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000389
390 def testSendMessageWithAddresses(self):
391 m = email.mime.text.MIMEText('A test message')
392 m['From'] = 'foo@bar.com'
393 m['To'] = 'John'
394 m['CC'] = 'Sally, Fred'
395 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
396 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
397 smtp.send_message(m)
398 # XXX (see comment in testSend)
399 time.sleep(0.01)
400 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400401 # make sure the Bcc header is still in the message.
402 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
403 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000404
405 self.client_evt.set()
406 self.serv_evt.wait()
407 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700408 # Remove the X-Peer header that DebuggingServer adds.
409 test_output = self.get_output_without_xpeer()
410 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400411 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000412 del m['Bcc']
413 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700414 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000415 debugout = smtpd.DEBUGSTREAM.getvalue()
416 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000417 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000418 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
419 'warped@silly.walks.com'):
420 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
421 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000422 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000423
424 def testSendMessageWithSomeAddresses(self):
425 # Make sure nothing breaks if not all of the three 'to' headers exist
426 m = email.mime.text.MIMEText('A test message')
427 m['From'] = 'foo@bar.com'
428 m['To'] = 'John, Dinsdale'
429 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
430 smtp.send_message(m)
431 # XXX (see comment in testSend)
432 time.sleep(0.01)
433 smtp.quit()
434
435 self.client_evt.set()
436 self.serv_evt.wait()
437 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700438 # Remove the X-Peer header that DebuggingServer adds.
439 test_output = self.get_output_without_xpeer()
440 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000441 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700442 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000443 debugout = smtpd.DEBUGSTREAM.getvalue()
444 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000445 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000446 for addr in ('John', 'Dinsdale'):
447 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
448 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000449 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000450
R David Murrayac4e5ab2011-07-02 21:03:19 -0400451 def testSendMessageWithSpecifiedAddresses(self):
452 # Make sure addresses specified in call override those in message.
453 m = email.mime.text.MIMEText('A test message')
454 m['From'] = 'foo@bar.com'
455 m['To'] = 'John, Dinsdale'
456 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
457 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
458 # XXX (see comment in testSend)
459 time.sleep(0.01)
460 smtp.quit()
461
462 self.client_evt.set()
463 self.serv_evt.wait()
464 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700465 # Remove the X-Peer header that DebuggingServer adds.
466 test_output = self.get_output_without_xpeer()
467 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400468 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700469 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400470 debugout = smtpd.DEBUGSTREAM.getvalue()
471 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
472 self.assertRegex(debugout, sender)
473 for addr in ('John', 'Dinsdale'):
474 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
475 re.MULTILINE)
476 self.assertNotRegex(debugout, to_addr)
477 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
478 self.assertRegex(debugout, recip)
479
480 def testSendMessageWithMultipleFrom(self):
481 # Sender overrides To
482 m = email.mime.text.MIMEText('A test message')
483 m['From'] = 'Bernard, Bianca'
484 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
485 m['To'] = 'John, Dinsdale'
486 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
487 smtp.send_message(m)
488 # XXX (see comment in testSend)
489 time.sleep(0.01)
490 smtp.quit()
491
492 self.client_evt.set()
493 self.serv_evt.wait()
494 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700495 # Remove the X-Peer header that DebuggingServer adds.
496 test_output = self.get_output_without_xpeer()
497 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400498 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700499 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400500 debugout = smtpd.DEBUGSTREAM.getvalue()
501 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
502 self.assertRegex(debugout, sender)
503 for addr in ('John', 'Dinsdale'):
504 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
505 re.MULTILINE)
506 self.assertRegex(debugout, to_addr)
507
508 def testSendMessageResent(self):
509 m = email.mime.text.MIMEText('A test message')
510 m['From'] = 'foo@bar.com'
511 m['To'] = 'John'
512 m['CC'] = 'Sally, Fred'
513 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
514 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
515 m['Resent-From'] = 'holy@grail.net'
516 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
517 m['Resent-Bcc'] = 'doe@losthope.net'
518 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
519 smtp.send_message(m)
520 # XXX (see comment in testSend)
521 time.sleep(0.01)
522 smtp.quit()
523
524 self.client_evt.set()
525 self.serv_evt.wait()
526 self.output.flush()
527 # The Resent-Bcc headers are deleted before serialization.
528 del m['Bcc']
529 del m['Resent-Bcc']
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700530 # Remove the X-Peer header that DebuggingServer adds.
531 test_output = self.get_output_without_xpeer()
532 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400533 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700534 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400535 debugout = smtpd.DEBUGSTREAM.getvalue()
536 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
537 self.assertRegex(debugout, sender)
538 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
539 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
540 re.MULTILINE)
541 self.assertRegex(debugout, to_addr)
542
543 def testSendMessageMultipleResentRaises(self):
544 m = email.mime.text.MIMEText('A test message')
545 m['From'] = 'foo@bar.com'
546 m['To'] = 'John'
547 m['CC'] = 'Sally, Fred'
548 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
549 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
550 m['Resent-From'] = 'holy@grail.net'
551 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
552 m['Resent-Bcc'] = 'doe@losthope.net'
553 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
554 m['Resent-To'] = 'holy@grail.net'
555 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
556 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
557 with self.assertRaises(ValueError):
558 smtp.send_message(m)
559 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000560
Victor Stinner45df8202010-04-28 22:31:17 +0000561class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000562
563 def testNotConnected(self):
564 # Test various operations on an unconnected SMTP object that
565 # should raise exceptions (at present the attempt in SMTP.send
566 # to reference the nonexistent 'sock' attribute of the SMTP object
567 # causes an AttributeError)
568 smtp = smtplib.SMTP()
569 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
570 self.assertRaises(smtplib.SMTPServerDisconnected,
571 smtp.send, 'test msg')
572
573 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200574 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200575 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000576 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200577 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000578 "localhost:bogus")
579
580
Guido van Rossum04110fb2007-08-24 16:32:05 +0000581# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000582class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000583
584 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000585 smtplib.socket = mock_socket
586 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000587 self.old_stdout = sys.stdout
588 self.output = io.StringIO()
589 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000590 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000591
592 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000593 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000594 sys.stdout = self.old_stdout
595
596 def testFailingHELO(self):
597 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000598 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000599
Guido van Rossum04110fb2007-08-24 16:32:05 +0000600
Georg Brandlb38b5c42014-02-10 22:11:21 +0100601class TooLongLineTests(unittest.TestCase):
602 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
603
604 def setUp(self):
605 self.old_stdout = sys.stdout
606 self.output = io.StringIO()
607 sys.stdout = self.output
608
609 self.evt = threading.Event()
610 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
611 self.sock.settimeout(15)
612 self.port = support.bind_port(self.sock)
613 servargs = (self.evt, self.respdata, self.sock)
Victor Stinner18e95b42017-09-14 08:43:04 -0700614 thread = threading.Thread(target=server, args=servargs)
615 thread.start()
616 self.addCleanup(thread.join)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100617 self.evt.wait()
618 self.evt.clear()
619
620 def tearDown(self):
621 self.evt.wait()
622 sys.stdout = self.old_stdout
623
624 def testLineTooLong(self):
625 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
626 HOST, self.port, 'localhost', 3)
627
628
Guido van Rossum04110fb2007-08-24 16:32:05 +0000629sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400630 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000631 'Mrs.C@somewhereesle.com':'Ruth C',
632 }
633
R. David Murraycaa27b72009-05-23 18:49:56 +0000634sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000635sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
636 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000637sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400638 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000639 }
640
641# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500642class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000643class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000644
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400645 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400646 mail_response = None
647 rcpt_response = None
648 data_response = None
649 rcpt_count = 0
650 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400651 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500652 AUTH = 99 # Add protocol state to enable auth testing.
653 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400654
R. David Murray23ddc0e2009-05-29 18:03:16 +0000655 def __init__(self, extra_features, *args, **kw):
656 self._extrafeatures = ''.join(
657 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000658 super(SimSMTPChannel, self).__init__(*args, **kw)
659
R David Murrayb0deeb42015-11-08 01:03:52 -0500660 # AUTH related stuff. It would be nice if support for this were in smtpd.
661 def found_terminator(self):
662 if self.smtp_state == self.AUTH:
663 line = self._emptystring.join(self.received_lines)
664 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
665 self.received_lines = []
666 try:
667 self.auth_object(line)
668 except ResponseException as e:
669 self.smtp_state = self.COMMAND
670 self.push('%s %s' % (e.smtp_code, e.smtp_error))
671 return
672 super().found_terminator()
673
674
675 def smtp_AUTH(self, arg):
676 if not self.seen_greeting:
677 self.push('503 Error: send EHLO first')
678 return
679 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
680 self.push('500 Error: command "AUTH" not recognized')
681 return
682 if self.authenticated_user is not None:
683 self.push(
684 '503 Bad sequence of commands: already authenticated')
685 return
686 args = arg.split()
687 if len(args) not in [1, 2]:
688 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
689 return
690 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
691 try:
692 self.auth_object = getattr(self, auth_object_name)
693 except AttributeError:
694 self.push('504 Command parameter not implemented: unsupported '
695 ' authentication mechanism {!r}'.format(auth_object_name))
696 return
697 self.smtp_state = self.AUTH
698 self.auth_object(args[1] if len(args) == 2 else None)
699
700 def _authenticated(self, user, valid):
701 if valid:
702 self.authenticated_user = user
703 self.push('235 Authentication Succeeded')
704 else:
705 self.push('535 Authentication credentials invalid')
706 self.smtp_state = self.COMMAND
707
708 def _decode_base64(self, string):
709 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
710
711 def _auth_plain(self, arg=None):
712 if arg is None:
713 self.push('334 ')
714 else:
715 logpass = self._decode_base64(arg)
716 try:
717 *_, user, password = logpass.split('\0')
718 except ValueError as e:
719 self.push('535 Splitting response {!r} into user and password'
720 ' failed: {}'.format(logpass, e))
721 return
722 self._authenticated(user, password == sim_auth[1])
723
724 def _auth_login(self, arg=None):
725 if arg is None:
726 # base64 encoded 'Username:'
727 self.push('334 VXNlcm5hbWU6')
728 elif not hasattr(self, '_auth_login_user'):
729 self._auth_login_user = self._decode_base64(arg)
730 # base64 encoded 'Password:'
731 self.push('334 UGFzc3dvcmQ6')
732 else:
733 password = self._decode_base64(arg)
734 self._authenticated(self._auth_login_user, password == sim_auth[1])
735 del self._auth_login_user
736
737 def _auth_cram_md5(self, arg=None):
738 if arg is None:
739 self.push('334 {}'.format(sim_cram_md5_challenge))
740 else:
741 logpass = self._decode_base64(arg)
742 try:
743 user, hashed_pass = logpass.split()
744 except ValueError as e:
745 self.push('535 Splitting response {!r} into user and password'
746 'failed: {}'.format(logpass, e))
747 return False
748 valid_hashed_pass = hmac.HMAC(
749 sim_auth[1].encode('ascii'),
750 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
751 'md5').hexdigest()
752 self._authenticated(user, hashed_pass == valid_hashed_pass)
753 # end AUTH related stuff.
754
Guido van Rossum04110fb2007-08-24 16:32:05 +0000755 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000756 resp = ('250-testhost\r\n'
757 '250-EXPN\r\n'
758 '250-SIZE 20000000\r\n'
759 '250-STARTTLS\r\n'
760 '250-DELIVERBY\r\n')
761 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000762 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400763 self.seen_greeting = arg
764 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000765
766 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400767 # For max compatibility smtplib should be sending the raw address.
768 if arg in sim_users:
769 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000770 else:
771 self.push('550 No such user: %s' % arg)
772
773 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400774 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000775 if list_name in sim_lists:
776 user_list = sim_lists[list_name]
777 for n, user_email in enumerate(user_list):
778 quoted_addr = smtplib.quoteaddr(user_email)
779 if n < len(user_list) - 1:
780 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
781 else:
782 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
783 else:
784 self.push('550 No access for you!')
785
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400786 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400787 if self.quit_response is None:
788 super(SimSMTPChannel, self).smtp_QUIT(arg)
789 else:
790 self.push(self.quit_response)
791 self.close_when_done()
792
R David Murrayd312c742013-03-20 20:36:14 -0400793 def smtp_MAIL(self, arg):
794 if self.mail_response is None:
795 super().smtp_MAIL(arg)
796 else:
797 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400798 if self.disconnect:
799 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400800
801 def smtp_RCPT(self, arg):
802 if self.rcpt_response is None:
803 super().smtp_RCPT(arg)
804 return
R David Murrayd312c742013-03-20 20:36:14 -0400805 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400806 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400807
808 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400809 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400810 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400811
812 def smtp_DATA(self, arg):
813 if self.data_response is None:
814 super().smtp_DATA(arg)
815 else:
816 self.push(self.data_response)
817
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000818 def handle_error(self):
819 raise
820
Guido van Rossum04110fb2007-08-24 16:32:05 +0000821
822class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000823
R David Murrayd312c742013-03-20 20:36:14 -0400824 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400825
R. David Murray23ddc0e2009-05-29 18:03:16 +0000826 def __init__(self, *args, **kw):
827 self._extra_features = []
828 smtpd.SMTPServer.__init__(self, *args, **kw)
829
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000830 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400831 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400832 self._extra_features, self, conn, addr,
833 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000834
835 def process_message(self, peer, mailfrom, rcpttos, data):
836 pass
837
R. David Murrayfb123912009-05-28 18:19:00 +0000838 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000839 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000840
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000841 def handle_error(self):
842 raise
843
Guido van Rossum04110fb2007-08-24 16:32:05 +0000844
845# Test various SMTP & ESMTP commands/behaviors that require a simulated server
846# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000847class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000848
849 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000850 self.real_getfqdn = socket.getfqdn
851 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000852 self.serv_evt = threading.Event()
853 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000854 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400855 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000856 # Keep a note of what port was assigned
857 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000858 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000859 self.thread = threading.Thread(target=debugging_server, args=serv_args)
860 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000861
862 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000863 self.serv_evt.wait()
864 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000865
866 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000867 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000868 # indicate that the client is finished
869 self.client_evt.set()
870 # wait for the server thread to terminate
871 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000872 self.thread.join()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000873
874 def testBasic(self):
875 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000876 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000877 smtp.quit()
878
879 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000880 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000881
882 # no features should be present before the EHLO
883 self.assertEqual(smtp.esmtp_features, {})
884
885 # features expected from the test server
886 expected_features = {'expn':'',
887 'size': '20000000',
888 'starttls': '',
889 'deliverby': '',
890 'help': '',
891 }
892
893 smtp.ehlo()
894 self.assertEqual(smtp.esmtp_features, expected_features)
895 for k in expected_features:
896 self.assertTrue(smtp.has_extn(k))
897 self.assertFalse(smtp.has_extn('unsupported-feature'))
898 smtp.quit()
899
900 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000901 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000902
Barry Warsawc5ea7542015-07-09 10:39:55 -0400903 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +0000904 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -0400905 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000906 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -0400907 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000908
909 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400910 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000911 self.assertEqual(smtp.vrfy(u), expected_unknown)
912 smtp.quit()
913
914 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000915 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000916
917 for listname, members in sim_lists.items():
918 users = []
919 for m in members:
920 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000921 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000922 self.assertEqual(smtp.expn(listname), expected_known)
923
924 u = 'PSU-Members-List'
925 expected_unknown = (550, b'No access for you!')
926 self.assertEqual(smtp.expn(u), expected_unknown)
927 smtp.quit()
928
R David Murray76e13c12014-07-03 14:47:46 -0400929 def testAUTH_PLAIN(self):
930 self.serv.add_feature("AUTH PLAIN")
931 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -0500932 resp = smtp.login(sim_auth[0], sim_auth[1])
933 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -0400934 smtp.close()
935
R. David Murrayfb123912009-05-28 18:19:00 +0000936 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000937 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000938 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -0500939 resp = smtp.login(sim_auth[0], sim_auth[1])
940 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000941 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000942
943 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000944 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000945 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -0500946 resp = smtp.login(sim_auth[0], sim_auth[1])
947 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000948 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000949
Andrew Kuchling78591822013-11-11 14:03:23 -0500950 def testAUTH_multiple(self):
951 # Test that multiple authentication methods are tried.
952 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
953 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -0500954 resp = smtp.login(sim_auth[0], sim_auth[1])
955 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -0400956 smtp.close()
957
958 def test_auth_function(self):
R David Murrayb0deeb42015-11-08 01:03:52 -0500959 supported = {'CRAM-MD5', 'PLAIN', 'LOGIN'}
960 for mechanism in supported:
961 self.serv.add_feature("AUTH {}".format(mechanism))
962 for mechanism in supported:
963 with self.subTest(mechanism=mechanism):
964 smtp = smtplib.SMTP(HOST, self.port,
965 local_hostname='localhost', timeout=15)
966 smtp.ehlo('foo')
967 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
968 method = 'auth_' + mechanism.lower().replace('-', '_')
969 resp = smtp.auth(mechanism, getattr(smtp, method))
970 self.assertEqual(resp, (235, b'Authentication Succeeded'))
971 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -0500972
R David Murray0cff49f2014-08-30 16:51:59 -0400973 def test_quit_resets_greeting(self):
974 smtp = smtplib.SMTP(HOST, self.port,
975 local_hostname='localhost',
976 timeout=15)
977 code, message = smtp.ehlo()
978 self.assertEqual(code, 250)
979 self.assertIn('size', smtp.esmtp_features)
980 smtp.quit()
981 self.assertNotIn('size', smtp.esmtp_features)
982 smtp.connect(HOST, self.port)
983 self.assertNotIn('size', smtp.esmtp_features)
984 smtp.ehlo_or_helo_if_needed()
985 self.assertIn('size', smtp.esmtp_features)
986 smtp.quit()
987
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400988 def test_with_statement(self):
989 with smtplib.SMTP(HOST, self.port) as smtp:
990 code, message = smtp.noop()
991 self.assertEqual(code, 250)
992 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
993 with smtplib.SMTP(HOST, self.port) as smtp:
994 smtp.close()
995 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
996
997 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400998 with self.assertRaises(smtplib.SMTPResponseException) as error:
999 with smtplib.SMTP(HOST, self.port) as smtp:
1000 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001001 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001002 self.assertEqual(error.exception.smtp_code, 421)
1003 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001004
R. David Murrayfb123912009-05-28 18:19:00 +00001005 #TODO: add tests for correct AUTH method fallback now that the
1006 #test infrastructure can support it.
1007
R David Murrayafb151a2014-04-14 18:21:38 -04001008 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1009 def test__rest_from_mail_cmd(self):
1010 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
1011 smtp.noop()
1012 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1013 self.serv._SMTPchannel.disconnect = True
1014 with self.assertRaises(smtplib.SMTPSenderRefused):
1015 smtp.sendmail('John', 'Sally', 'test message')
1016 self.assertIsNone(smtp.sock)
1017
R David Murrayd312c742013-03-20 20:36:14 -04001018 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1019 def test_421_from_mail_cmd(self):
1020 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001021 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001022 self.serv._SMTPchannel.mail_response = '421 closing connection'
1023 with self.assertRaises(smtplib.SMTPSenderRefused):
1024 smtp.sendmail('John', 'Sally', 'test message')
1025 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001026 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001027
1028 def test_421_from_rcpt_cmd(self):
1029 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001030 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001031 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1032 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1033 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1034 self.assertIsNone(smtp.sock)
1035 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1036 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1037
1038 def test_421_from_data_cmd(self):
1039 class MySimSMTPChannel(SimSMTPChannel):
1040 def found_terminator(self):
1041 if self.smtp_state == self.DATA:
1042 self.push('421 closing')
1043 else:
1044 super().found_terminator()
1045 self.serv.channel_class = MySimSMTPChannel
1046 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001047 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001048 with self.assertRaises(smtplib.SMTPDataError):
1049 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1050 self.assertIsNone(smtp.sock)
1051 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1052
R David Murraycee7cf62015-05-16 13:58:14 -04001053 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1054 smtp = smtplib.SMTP(
1055 HOST, self.port, local_hostname='localhost', timeout=3)
1056 self.addCleanup(smtp.close)
1057 smtp.ehlo()
1058 self.assertTrue(smtp.does_esmtp)
1059 self.assertFalse(smtp.has_extn('smtputf8'))
1060 self.assertRaises(
1061 smtplib.SMTPNotSupportedError,
1062 smtp.sendmail,
1063 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1064 self.assertRaises(
1065 smtplib.SMTPNotSupportedError,
1066 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1067
1068 def test_send_unicode_without_SMTPUTF8(self):
1069 smtp = smtplib.SMTP(
1070 HOST, self.port, local_hostname='localhost', timeout=3)
1071 self.addCleanup(smtp.close)
1072 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1073 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1074
1075
1076class SimSMTPUTF8Server(SimSMTPServer):
1077
1078 def __init__(self, *args, **kw):
1079 # The base SMTP server turns these on automatically, but our test
1080 # server is set up to munge the EHLO response, so we need to provide
1081 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1082 self._extra_features = ['SMTPUTF8', '8BITMIME']
1083 smtpd.SMTPServer.__init__(self, *args, **kw)
1084
1085 def handle_accepted(self, conn, addr):
1086 self._SMTPchannel = self.channel_class(
1087 self._extra_features, self, conn, addr,
1088 decode_data=self._decode_data,
1089 enable_SMTPUTF8=self.enable_SMTPUTF8,
1090 )
1091
1092 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1093 rcpt_options=None):
1094 self.last_peer = peer
1095 self.last_mailfrom = mailfrom
1096 self.last_rcpttos = rcpttos
1097 self.last_message = data
1098 self.last_mail_options = mail_options
1099 self.last_rcpt_options = rcpt_options
1100
1101
R David Murraycee7cf62015-05-16 13:58:14 -04001102class SMTPUTF8SimTests(unittest.TestCase):
1103
R David Murray83084442015-05-17 19:27:22 -04001104 maxDiff = None
1105
R David Murraycee7cf62015-05-16 13:58:14 -04001106 def setUp(self):
1107 self.real_getfqdn = socket.getfqdn
1108 socket.getfqdn = mock_socket.getfqdn
1109 self.serv_evt = threading.Event()
1110 self.client_evt = threading.Event()
1111 # Pick a random unused port by passing 0 for the port number
1112 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1113 decode_data=False,
1114 enable_SMTPUTF8=True)
1115 # Keep a note of what port was assigned
1116 self.port = self.serv.socket.getsockname()[1]
1117 serv_args = (self.serv, self.serv_evt, self.client_evt)
1118 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1119 self.thread.start()
1120
1121 # wait until server thread has assigned a port number
1122 self.serv_evt.wait()
1123 self.serv_evt.clear()
1124
1125 def tearDown(self):
1126 socket.getfqdn = self.real_getfqdn
1127 # indicate that the client is finished
1128 self.client_evt.set()
1129 # wait for the server thread to terminate
1130 self.serv_evt.wait()
1131 self.thread.join()
1132
1133 def test_test_server_supports_extensions(self):
1134 smtp = smtplib.SMTP(
1135 HOST, self.port, local_hostname='localhost', timeout=3)
1136 self.addCleanup(smtp.close)
1137 smtp.ehlo()
1138 self.assertTrue(smtp.does_esmtp)
1139 self.assertTrue(smtp.has_extn('smtputf8'))
1140
1141 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1142 m = '¡a test message containing unicode!'.encode('utf-8')
1143 smtp = smtplib.SMTP(
1144 HOST, self.port, local_hostname='localhost', timeout=3)
1145 self.addCleanup(smtp.close)
1146 smtp.sendmail('Jőhn', 'Sálly', m,
1147 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1148 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1149 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1150 self.assertEqual(self.serv.last_message, m)
1151 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1152 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1153 self.assertEqual(self.serv.last_rcpt_options, [])
1154
1155 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1156 m = '¡a test message containing unicode!'.encode('utf-8')
1157 smtp = smtplib.SMTP(
1158 HOST, self.port, local_hostname='localhost', timeout=3)
1159 self.addCleanup(smtp.close)
1160 smtp.ehlo()
1161 self.assertEqual(
1162 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1163 (250, b'OK'))
1164 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1165 self.assertEqual(smtp.data(m), (250, b'OK'))
1166 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1167 self.assertEqual(self.serv.last_rcpttos, ['János'])
1168 self.assertEqual(self.serv.last_message, m)
1169 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1170 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1171 self.assertEqual(self.serv.last_rcpt_options, [])
1172
R David Murray83084442015-05-17 19:27:22 -04001173 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1174 msg = EmailMessage()
1175 msg['From'] = "Páolo <főo@bar.com>"
1176 msg['To'] = 'Dinsdale'
1177 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1178 # XXX I don't know why I need two \n's here, but this is an existing
1179 # bug (if it is one) and not a problem with the new functionality.
1180 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1181 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1182 # we are successfully sending /r/n :(.
1183 expected = textwrap.dedent("""\
1184 From: Páolo <főo@bar.com>
1185 To: Dinsdale
1186 Subject: Nudge nudge, wink, wink \u1F609
1187 Content-Type: text/plain; charset="utf-8"
1188 Content-Transfer-Encoding: 8bit
1189 MIME-Version: 1.0
1190
1191 oh là là, know what I mean, know what I mean?
1192 """)
1193 smtp = smtplib.SMTP(
1194 HOST, self.port, local_hostname='localhost', timeout=3)
1195 self.addCleanup(smtp.close)
1196 self.assertEqual(smtp.send_message(msg), {})
1197 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1198 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1199 self.assertEqual(self.serv.last_message.decode(), expected)
1200 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1201 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1202 self.assertEqual(self.serv.last_rcpt_options, [])
1203
1204 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1205 msg = EmailMessage()
1206 msg['From'] = "Páolo <főo@bar.com>"
1207 msg['To'] = 'Dinsdale'
1208 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1209 smtp = smtplib.SMTP(
1210 HOST, self.port, local_hostname='localhost', timeout=3)
1211 self.addCleanup(smtp.close)
1212 self.assertRaises(smtplib.SMTPNotSupportedError,
1213 smtp.send_message(msg))
1214
Guido van Rossum04110fb2007-08-24 16:32:05 +00001215
Barry Warsawc5ea7542015-07-09 10:39:55 -04001216EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1217
1218class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1219 def smtp_AUTH(self, arg):
1220 # RFC 4954's AUTH command allows for an optional initial-response.
1221 # Not all AUTH methods support this; some require a challenge. AUTH
1222 # PLAIN does those, so test that here. See issue #15014.
1223 args = arg.split()
1224 if args[0].lower() == 'plain':
1225 if len(args) == 2:
1226 # AUTH PLAIN <initial-response> with the response base 64
1227 # encoded. Hard code the expected response for the test.
1228 if args[1] == EXPECTED_RESPONSE:
1229 self.push('235 Ok')
1230 return
1231 self.push('571 Bad authentication')
1232
1233class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1234 channel_class = SimSMTPAUTHInitialResponseChannel
1235
1236
Barry Warsawc5ea7542015-07-09 10:39:55 -04001237class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1238 def setUp(self):
1239 self.real_getfqdn = socket.getfqdn
1240 socket.getfqdn = mock_socket.getfqdn
1241 self.serv_evt = threading.Event()
1242 self.client_evt = threading.Event()
1243 # Pick a random unused port by passing 0 for the port number
1244 self.serv = SimSMTPAUTHInitialResponseServer(
1245 (HOST, 0), ('nowhere', -1), decode_data=True)
1246 # Keep a note of what port was assigned
1247 self.port = self.serv.socket.getsockname()[1]
1248 serv_args = (self.serv, self.serv_evt, self.client_evt)
1249 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1250 self.thread.start()
1251
1252 # wait until server thread has assigned a port number
1253 self.serv_evt.wait()
1254 self.serv_evt.clear()
1255
1256 def tearDown(self):
1257 socket.getfqdn = self.real_getfqdn
1258 # indicate that the client is finished
1259 self.client_evt.set()
1260 # wait for the server thread to terminate
1261 self.serv_evt.wait()
1262 self.thread.join()
1263
1264 def testAUTH_PLAIN_initial_response_login(self):
1265 self.serv.add_feature('AUTH PLAIN')
1266 smtp = smtplib.SMTP(HOST, self.port,
1267 local_hostname='localhost', timeout=15)
1268 smtp.login('psu', 'doesnotexist')
1269 smtp.close()
1270
1271 def testAUTH_PLAIN_initial_response_auth(self):
1272 self.serv.add_feature('AUTH PLAIN')
1273 smtp = smtplib.SMTP(HOST, self.port,
1274 local_hostname='localhost', timeout=15)
1275 smtp.user = 'psu'
1276 smtp.password = 'doesnotexist'
1277 code, response = smtp.auth('plain', smtp.auth_plain)
1278 smtp.close()
1279 self.assertEqual(code, 235)
1280
1281
Antoine Pitroud54fa552011-08-28 01:23:52 +02001282@support.reap_threads
Guido van Rossumd8faa362007-04-27 19:54:29 +00001283def test_main(verbose=None):
Barry Warsawc5ea7542015-07-09 10:39:55 -04001284 support.run_unittest(
1285 BadHELOServerTests,
1286 DebuggingServerTests,
1287 GeneralTests,
1288 NonConnectingTests,
1289 SMTPAUTHInitialResponseSimTests,
1290 SMTPSimTests,
1291 TooLongLineTests,
1292 )
1293
Guido van Rossumd8faa362007-04-27 19:54:29 +00001294
1295if __name__ == '__main__':
1296 test_main()