blob: fdcf6f21925645c8eb353b51214b4ddb4e38dc53 [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
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +010023from test.support import threading_setup, threading_cleanup, join_thread
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +020024from unittest.mock import Mock
Guido van Rossumd8faa362007-04-27 19:54:29 +000025
Victor Stinner45df8202010-04-28 22:31:17 +000026
Josiah Carlsond74900e2008-07-07 04:15:08 +000027if sys.platform == 'darwin':
28 # select.poll returns a select.POLLHUP at the end of the tests
29 # on darwin, so just ignore it
30 def handle_expt(self):
31 pass
32 smtpd.SMTPChannel.handle_expt = handle_expt
33
34
Christian Heimes5e696852008-04-09 08:37:03 +000035def server(evt, buf, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +010036 serv.listen()
Christian Heimes380f7f22008-02-28 11:19:05 +000037 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000038 try:
39 conn, addr = serv.accept()
40 except socket.timeout:
41 pass
42 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000043 n = 500
44 while buf and n > 0:
45 r, w, e = select.select([], [conn], [])
46 if w:
47 sent = conn.send(buf)
48 buf = buf[sent:]
49
50 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000051
Guido van Rossumd8faa362007-04-27 19:54:29 +000052 conn.close()
53 finally:
54 serv.close()
55 evt.set()
56
Victor Stinner45df8202010-04-28 22:31:17 +000057class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000058
59 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000060 smtplib.socket = mock_socket
61 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000062
63 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000064 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000065
R. David Murray7dff9e02010-11-08 17:15:13 +000066 # This method is no longer used but is retained for backward compatibility,
67 # so test to make sure it still works.
68 def testQuoteData(self):
69 teststr = "abc\n.jkl\rfoo\r\n..blue"
70 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
71 self.assertEqual(expected, smtplib.quotedata(teststr))
72
Guido van Rossum806c2462007-08-06 23:33:07 +000073 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000074 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000075 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000076 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000077 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000078
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080079 def testSourceAddress(self):
80 mock_socket.reply_with(b"220 Hola mundo")
81 # connects
82 smtp = smtplib.SMTP(HOST, self.port,
83 source_address=('127.0.0.1',19876))
84 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
85 smtp.close()
86
Guido van Rossum806c2462007-08-06 23:33:07 +000087 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000088 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000089 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000090 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000091 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000092
93 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000094 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000095 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000096 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000097 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000098 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000099
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000101 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200102 self.assertIsNone(mock_socket.getdefaulttimeout())
Richard Jones64b02de2010-08-03 06:39:33 +0000103 mock_socket.setdefaulttimeout(30)
104 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000105 try:
106 smtp = smtplib.SMTP(HOST, self.port)
107 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000108 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000109 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000110 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111
112 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000113 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200114 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115 socket.setdefaulttimeout(30)
116 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000117 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000119 socket.setdefaulttimeout(None)
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200120 self.assertIsNone(smtp.sock.gettimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000121 smtp.close()
122
123 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000124 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000125 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000127 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128
R David Murray0c49b892015-04-16 17:14:42 -0400129 def test_debuglevel(self):
130 mock_socket.reply_with(b"220 Hello world")
131 smtp = smtplib.SMTP()
132 smtp.set_debuglevel(1)
133 with support.captured_stderr() as stderr:
134 smtp.connect(HOST, self.port)
135 smtp.close()
136 expected = re.compile(r"^connect:", re.MULTILINE)
137 self.assertRegex(stderr.getvalue(), expected)
138
139 def test_debuglevel_2(self):
140 mock_socket.reply_with(b"220 Hello world")
141 smtp = smtplib.SMTP()
142 smtp.set_debuglevel(2)
143 with support.captured_stderr() as stderr:
144 smtp.connect(HOST, self.port)
145 smtp.close()
146 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
147 re.MULTILINE)
148 self.assertRegex(stderr.getvalue(), expected)
149
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150
Guido van Rossum04110fb2007-08-24 16:32:05 +0000151# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000152def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000153 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000154
155 try:
156 if hasattr(select, 'poll'):
157 poll_fun = asyncore.poll2
158 else:
159 poll_fun = asyncore.poll
160
161 n = 1000
162 while asyncore.socket_map and n > 0:
163 poll_fun(0.01, asyncore.socket_map)
164
165 # when the client conversation is finished, it will
166 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000167 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000168 serv.close()
169 break
170
171 n -= 1
172
173 except socket.timeout:
174 pass
175 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000176 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000177 # allow some time for the client to read the result
178 time.sleep(0.5)
179 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000180 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000181 serv_evt.set()
182
183MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
184MSG_END = '------------ END MESSAGE ------------\n'
185
Guido van Rossum04110fb2007-08-24 16:32:05 +0000186# NOTE: Some SMTP objects in the tests below are created with a non-default
187# local_hostname argument to the constructor, since (on some systems) the FQDN
188# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000189# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000190
191# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000192class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000193
R. David Murray7dff9e02010-11-08 17:15:13 +0000194 maxDiff = None
195
Guido van Rossum806c2462007-08-06 23:33:07 +0000196 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100197 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000198 self.real_getfqdn = socket.getfqdn
199 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000200 # temporarily replace sys.stdout to capture DebuggingServer output
201 self.old_stdout = sys.stdout
202 self.output = io.StringIO()
203 sys.stdout = self.output
204
205 self.serv_evt = threading.Event()
206 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000207 # Capture SMTPChannel debug output
208 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
209 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000210 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400211 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
212 decode_data=True)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700213 # Keep a note of what server host and port were assigned
214 self.host, self.port = self.serv.socket.getsockname()[:2]
Christian Heimes5e696852008-04-09 08:37:03 +0000215 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000216 self.thread = threading.Thread(target=debugging_server, args=serv_args)
217 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000218
219 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000220 self.serv_evt.wait()
221 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000222
223 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000224 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000225 # indicate that the client is finished
226 self.client_evt.set()
227 # wait for the server thread to terminate
228 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100229 join_thread(self.thread)
Guido van Rossum806c2462007-08-06 23:33:07 +0000230 # restore sys.stdout
231 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000232 # restore DEBUGSTREAM
233 smtpd.DEBUGSTREAM.close()
234 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100235 del self.thread
236 self.doCleanups()
237 threading_cleanup(*self.thread_key)
Guido van Rossum806c2462007-08-06 23:33:07 +0000238
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700239 def get_output_without_xpeer(self):
240 test_output = self.output.getvalue()
241 return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2',
242 test_output, flags=re.MULTILINE|re.DOTALL)
243
Guido van Rossum806c2462007-08-06 23:33:07 +0000244 def testBasic(self):
245 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000246 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000247 smtp.quit()
248
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800249 def testSourceAddress(self):
250 # connect
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700251 src_port = support.find_unused_port()
Senthil Kumaranb351a482011-07-31 09:14:17 +0800252 try:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700253 smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost',
254 timeout=3, source_address=(self.host, src_port))
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100255 self.addCleanup(smtp.close)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700256 self.assertEqual(smtp.source_address, (self.host, src_port))
Senthil Kumaranb351a482011-07-31 09:14:17 +0800257 self.assertEqual(smtp.local_hostname, 'localhost')
258 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200259 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800260 if e.errno == errno.EADDRINUSE:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700261 self.skipTest("couldn't bind to source port %d" % src_port)
Senthil Kumaranb351a482011-07-31 09:14:17 +0800262 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800263
Guido van Rossum04110fb2007-08-24 16:32:05 +0000264 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000265 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100266 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400267 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000268 self.assertEqual(smtp.noop(), expected)
269 smtp.quit()
270
271 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000272 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100273 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400274 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000275 self.assertEqual(smtp.rset(), expected)
276 smtp.quit()
277
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400278 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000279 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000280 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100281 self.addCleanup(smtp.close)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400282 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000283 self.assertEqual(smtp.ehlo(), expected)
284 smtp.quit()
285
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400286 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400287 # EXPN isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000288 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100289 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400290 expected = (502, b'EXPN not implemented')
291 smtp.putcmd('EXPN')
292 self.assertEqual(smtp.getreply(), expected)
293 smtp.quit()
294
295 def testVRFY(self):
296 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100297 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400298 expected = (252, b'Cannot VRFY user, but will accept message ' + \
299 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000300 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
301 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
302 smtp.quit()
303
304 def testSecondHELO(self):
305 # check that a second HELO returns a message that it's a duplicate
306 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000307 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100308 self.addCleanup(smtp.close)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000309 smtp.helo()
310 expected = (503, b'Duplicate HELO/EHLO')
311 self.assertEqual(smtp.helo(), expected)
312 smtp.quit()
313
Guido van Rossum806c2462007-08-06 23:33:07 +0000314 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000315 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100316 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400317 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
318 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000319 smtp.quit()
320
321 def testSend(self):
322 # connect and send mail
323 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000324 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100325 self.addCleanup(smtp.close)
Guido van Rossum806c2462007-08-06 23:33:07 +0000326 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000327 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
328 # in asyncore. This sleep might help, but should really be fixed
329 # properly by using an Event variable.
330 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000331 smtp.quit()
332
333 self.client_evt.set()
334 self.serv_evt.wait()
335 self.output.flush()
336 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
337 self.assertEqual(self.output.getvalue(), mexpect)
338
R. David Murray7dff9e02010-11-08 17:15:13 +0000339 def testSendBinary(self):
340 m = b'A test message'
341 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100342 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000343 smtp.sendmail('John', 'Sally', m)
344 # XXX (see comment in testSend)
345 time.sleep(0.01)
346 smtp.quit()
347
348 self.client_evt.set()
349 self.serv_evt.wait()
350 self.output.flush()
351 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
352 self.assertEqual(self.output.getvalue(), mexpect)
353
R David Murray0f663d02011-06-09 15:05:57 -0400354 def testSendNeedingDotQuote(self):
355 # Issue 12283
356 m = '.A test\n.mes.sage.'
357 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100358 self.addCleanup(smtp.close)
R David Murray0f663d02011-06-09 15:05:57 -0400359 smtp.sendmail('John', 'Sally', m)
360 # XXX (see comment in testSend)
361 time.sleep(0.01)
362 smtp.quit()
363
364 self.client_evt.set()
365 self.serv_evt.wait()
366 self.output.flush()
367 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
368 self.assertEqual(self.output.getvalue(), mexpect)
369
R David Murray46346762011-07-18 21:38:54 -0400370 def testSendNullSender(self):
371 m = 'A test message'
372 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100373 self.addCleanup(smtp.close)
R David Murray46346762011-07-18 21:38:54 -0400374 smtp.sendmail('<>', 'Sally', m)
375 # XXX (see comment in testSend)
376 time.sleep(0.01)
377 smtp.quit()
378
379 self.client_evt.set()
380 self.serv_evt.wait()
381 self.output.flush()
382 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
383 self.assertEqual(self.output.getvalue(), mexpect)
384 debugout = smtpd.DEBUGSTREAM.getvalue()
385 sender = re.compile("^sender: <>$", re.MULTILINE)
386 self.assertRegex(debugout, sender)
387
R. David Murray7dff9e02010-11-08 17:15:13 +0000388 def testSendMessage(self):
389 m = email.mime.text.MIMEText('A test message')
390 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100391 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000392 smtp.send_message(m, from_addr='John', to_addrs='Sally')
393 # XXX (see comment in testSend)
394 time.sleep(0.01)
395 smtp.quit()
396
397 self.client_evt.set()
398 self.serv_evt.wait()
399 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700400 # Remove the X-Peer header that DebuggingServer adds as figuring out
401 # exactly what IP address format is put there is not easy (and
402 # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is
403 # not always the same as socket.gethostbyname(HOST). :(
404 test_output = self.get_output_without_xpeer()
405 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000406 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700407 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000408
409 def testSendMessageWithAddresses(self):
410 m = email.mime.text.MIMEText('A test message')
411 m['From'] = 'foo@bar.com'
412 m['To'] = 'John'
413 m['CC'] = 'Sally, Fred'
414 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
415 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100416 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000417 smtp.send_message(m)
418 # XXX (see comment in testSend)
419 time.sleep(0.01)
420 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400421 # make sure the Bcc header is still in the message.
422 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
423 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000424
425 self.client_evt.set()
426 self.serv_evt.wait()
427 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700428 # Remove the X-Peer header that DebuggingServer adds.
429 test_output = self.get_output_without_xpeer()
430 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400431 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000432 del m['Bcc']
433 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700434 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000435 debugout = smtpd.DEBUGSTREAM.getvalue()
436 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000437 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000438 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
439 'warped@silly.walks.com'):
440 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
441 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000442 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000443
444 def testSendMessageWithSomeAddresses(self):
445 # Make sure nothing breaks if not all of the three 'to' headers exist
446 m = email.mime.text.MIMEText('A test message')
447 m['From'] = 'foo@bar.com'
448 m['To'] = 'John, Dinsdale'
449 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100450 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000451 smtp.send_message(m)
452 # XXX (see comment in testSend)
453 time.sleep(0.01)
454 smtp.quit()
455
456 self.client_evt.set()
457 self.serv_evt.wait()
458 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700459 # Remove the X-Peer header that DebuggingServer adds.
460 test_output = self.get_output_without_xpeer()
461 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000462 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700463 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000464 debugout = smtpd.DEBUGSTREAM.getvalue()
465 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000466 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000467 for addr in ('John', 'Dinsdale'):
468 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
469 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000470 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000471
R David Murrayac4e5ab2011-07-02 21:03:19 -0400472 def testSendMessageWithSpecifiedAddresses(self):
473 # Make sure addresses specified in call override those in message.
474 m = email.mime.text.MIMEText('A test message')
475 m['From'] = 'foo@bar.com'
476 m['To'] = 'John, Dinsdale'
477 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100478 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400479 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
480 # XXX (see comment in testSend)
481 time.sleep(0.01)
482 smtp.quit()
483
484 self.client_evt.set()
485 self.serv_evt.wait()
486 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700487 # Remove the X-Peer header that DebuggingServer adds.
488 test_output = self.get_output_without_xpeer()
489 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400490 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700491 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400492 debugout = smtpd.DEBUGSTREAM.getvalue()
493 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
494 self.assertRegex(debugout, sender)
495 for addr in ('John', 'Dinsdale'):
496 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
497 re.MULTILINE)
498 self.assertNotRegex(debugout, to_addr)
499 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
500 self.assertRegex(debugout, recip)
501
502 def testSendMessageWithMultipleFrom(self):
503 # Sender overrides To
504 m = email.mime.text.MIMEText('A test message')
505 m['From'] = 'Bernard, Bianca'
506 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
507 m['To'] = 'John, Dinsdale'
508 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100509 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400510 smtp.send_message(m)
511 # XXX (see comment in testSend)
512 time.sleep(0.01)
513 smtp.quit()
514
515 self.client_evt.set()
516 self.serv_evt.wait()
517 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700518 # Remove the X-Peer header that DebuggingServer adds.
519 test_output = self.get_output_without_xpeer()
520 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400521 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700522 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400523 debugout = smtpd.DEBUGSTREAM.getvalue()
524 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
525 self.assertRegex(debugout, sender)
526 for addr in ('John', 'Dinsdale'):
527 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
528 re.MULTILINE)
529 self.assertRegex(debugout, to_addr)
530
531 def testSendMessageResent(self):
532 m = email.mime.text.MIMEText('A test message')
533 m['From'] = 'foo@bar.com'
534 m['To'] = 'John'
535 m['CC'] = 'Sally, Fred'
536 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
537 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
538 m['Resent-From'] = 'holy@grail.net'
539 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
540 m['Resent-Bcc'] = 'doe@losthope.net'
541 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100542 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400543 smtp.send_message(m)
544 # XXX (see comment in testSend)
545 time.sleep(0.01)
546 smtp.quit()
547
548 self.client_evt.set()
549 self.serv_evt.wait()
550 self.output.flush()
551 # The Resent-Bcc headers are deleted before serialization.
552 del m['Bcc']
553 del m['Resent-Bcc']
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700554 # Remove the X-Peer header that DebuggingServer adds.
555 test_output = self.get_output_without_xpeer()
556 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400557 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700558 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400559 debugout = smtpd.DEBUGSTREAM.getvalue()
560 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
561 self.assertRegex(debugout, sender)
562 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
563 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
564 re.MULTILINE)
565 self.assertRegex(debugout, to_addr)
566
567 def testSendMessageMultipleResentRaises(self):
568 m = email.mime.text.MIMEText('A test message')
569 m['From'] = 'foo@bar.com'
570 m['To'] = 'John'
571 m['CC'] = 'Sally, Fred'
572 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
573 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
574 m['Resent-From'] = 'holy@grail.net'
575 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
576 m['Resent-Bcc'] = 'doe@losthope.net'
577 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
578 m['Resent-To'] = 'holy@grail.net'
579 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
580 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100581 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400582 with self.assertRaises(ValueError):
583 smtp.send_message(m)
584 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000585
Victor Stinner45df8202010-04-28 22:31:17 +0000586class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000587
588 def testNotConnected(self):
589 # Test various operations on an unconnected SMTP object that
590 # should raise exceptions (at present the attempt in SMTP.send
591 # to reference the nonexistent 'sock' attribute of the SMTP object
592 # causes an AttributeError)
593 smtp = smtplib.SMTP()
594 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
595 self.assertRaises(smtplib.SMTPServerDisconnected,
596 smtp.send, 'test msg')
597
598 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200599 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200600 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000601 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200602 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000603 "localhost:bogus")
604
Romuald Brunet7b313972018-10-09 16:31:55 +0200605 def testSockAttributeExists(self):
606 # check that sock attribute is present outside of a connect() call
607 # (regression test, the previous behavior raised an
608 # AttributeError: 'SMTP' object has no attribute 'sock')
609 with smtplib.SMTP() as smtp:
610 self.assertIsNone(smtp.sock)
611
Christian Heimes380f7f22008-02-28 11:19:05 +0000612
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200613class DefaultArgumentsTests(unittest.TestCase):
614
615 def setUp(self):
616 self.msg = EmailMessage()
617 self.msg['From'] = 'Páolo <főo@bar.com>'
618 self.smtp = smtplib.SMTP()
619 self.smtp.ehlo = Mock(return_value=(200, 'OK'))
620 self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
621
622 def testSendMessage(self):
623 expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
624 self.smtp.send_message(self.msg)
625 self.smtp.send_message(self.msg)
626 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
627 expected_mail_options)
628 self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
629 expected_mail_options)
630
631 def testSendMessageWithMailOptions(self):
632 mail_options = ['STARTTLS']
633 expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
634 self.smtp.send_message(self.msg, None, None, mail_options)
635 self.assertEqual(mail_options, ['STARTTLS'])
636 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
637 expected_mail_options)
638
639
Guido van Rossum04110fb2007-08-24 16:32:05 +0000640# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000641class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000642
643 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000644 smtplib.socket = mock_socket
645 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000646 self.old_stdout = sys.stdout
647 self.output = io.StringIO()
648 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000649 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000650
651 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000652 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000653 sys.stdout = self.old_stdout
654
655 def testFailingHELO(self):
656 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000657 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000658
Guido van Rossum04110fb2007-08-24 16:32:05 +0000659
Georg Brandlb38b5c42014-02-10 22:11:21 +0100660class TooLongLineTests(unittest.TestCase):
661 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
662
663 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100664 self.thread_key = threading_setup()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100665 self.old_stdout = sys.stdout
666 self.output = io.StringIO()
667 sys.stdout = self.output
668
669 self.evt = threading.Event()
670 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
671 self.sock.settimeout(15)
672 self.port = support.bind_port(self.sock)
673 servargs = (self.evt, self.respdata, self.sock)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100674 self.thread = threading.Thread(target=server, args=servargs)
675 self.thread.start()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100676 self.evt.wait()
677 self.evt.clear()
678
679 def tearDown(self):
680 self.evt.wait()
681 sys.stdout = self.old_stdout
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100682 join_thread(self.thread)
683 del self.thread
684 self.doCleanups()
685 threading_cleanup(*self.thread_key)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100686
687 def testLineTooLong(self):
688 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
689 HOST, self.port, 'localhost', 3)
690
691
Guido van Rossum04110fb2007-08-24 16:32:05 +0000692sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400693 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000694 'Mrs.C@somewhereesle.com':'Ruth C',
695 }
696
R. David Murraycaa27b72009-05-23 18:49:56 +0000697sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000698sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
699 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000700sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400701 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000702 }
703
704# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500705class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000706class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000707
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400708 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400709 mail_response = None
710 rcpt_response = None
711 data_response = None
712 rcpt_count = 0
713 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400714 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500715 AUTH = 99 # Add protocol state to enable auth testing.
716 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400717
R. David Murray23ddc0e2009-05-29 18:03:16 +0000718 def __init__(self, extra_features, *args, **kw):
719 self._extrafeatures = ''.join(
720 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000721 super(SimSMTPChannel, self).__init__(*args, **kw)
722
R David Murrayb0deeb42015-11-08 01:03:52 -0500723 # AUTH related stuff. It would be nice if support for this were in smtpd.
724 def found_terminator(self):
725 if self.smtp_state == self.AUTH:
726 line = self._emptystring.join(self.received_lines)
727 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
728 self.received_lines = []
729 try:
730 self.auth_object(line)
731 except ResponseException as e:
732 self.smtp_state = self.COMMAND
733 self.push('%s %s' % (e.smtp_code, e.smtp_error))
734 return
735 super().found_terminator()
736
737
738 def smtp_AUTH(self, arg):
739 if not self.seen_greeting:
740 self.push('503 Error: send EHLO first')
741 return
742 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
743 self.push('500 Error: command "AUTH" not recognized')
744 return
745 if self.authenticated_user is not None:
746 self.push(
747 '503 Bad sequence of commands: already authenticated')
748 return
749 args = arg.split()
750 if len(args) not in [1, 2]:
751 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
752 return
753 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
754 try:
755 self.auth_object = getattr(self, auth_object_name)
756 except AttributeError:
757 self.push('504 Command parameter not implemented: unsupported '
758 ' authentication mechanism {!r}'.format(auth_object_name))
759 return
760 self.smtp_state = self.AUTH
761 self.auth_object(args[1] if len(args) == 2 else None)
762
763 def _authenticated(self, user, valid):
764 if valid:
765 self.authenticated_user = user
766 self.push('235 Authentication Succeeded')
767 else:
768 self.push('535 Authentication credentials invalid')
769 self.smtp_state = self.COMMAND
770
771 def _decode_base64(self, string):
772 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
773
774 def _auth_plain(self, arg=None):
775 if arg is None:
776 self.push('334 ')
777 else:
778 logpass = self._decode_base64(arg)
779 try:
780 *_, user, password = logpass.split('\0')
781 except ValueError as e:
782 self.push('535 Splitting response {!r} into user and password'
783 ' failed: {}'.format(logpass, e))
784 return
785 self._authenticated(user, password == sim_auth[1])
786
787 def _auth_login(self, arg=None):
788 if arg is None:
789 # base64 encoded 'Username:'
790 self.push('334 VXNlcm5hbWU6')
791 elif not hasattr(self, '_auth_login_user'):
792 self._auth_login_user = self._decode_base64(arg)
793 # base64 encoded 'Password:'
794 self.push('334 UGFzc3dvcmQ6')
795 else:
796 password = self._decode_base64(arg)
797 self._authenticated(self._auth_login_user, password == sim_auth[1])
798 del self._auth_login_user
799
800 def _auth_cram_md5(self, arg=None):
801 if arg is None:
802 self.push('334 {}'.format(sim_cram_md5_challenge))
803 else:
804 logpass = self._decode_base64(arg)
805 try:
806 user, hashed_pass = logpass.split()
807 except ValueError as e:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200808 self.push('535 Splitting response {!r} into user and password '
R David Murrayb0deeb42015-11-08 01:03:52 -0500809 'failed: {}'.format(logpass, e))
810 return False
811 valid_hashed_pass = hmac.HMAC(
812 sim_auth[1].encode('ascii'),
813 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
814 'md5').hexdigest()
815 self._authenticated(user, hashed_pass == valid_hashed_pass)
816 # end AUTH related stuff.
817
Guido van Rossum04110fb2007-08-24 16:32:05 +0000818 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000819 resp = ('250-testhost\r\n'
820 '250-EXPN\r\n'
821 '250-SIZE 20000000\r\n'
822 '250-STARTTLS\r\n'
823 '250-DELIVERBY\r\n')
824 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000825 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400826 self.seen_greeting = arg
827 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000828
829 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400830 # For max compatibility smtplib should be sending the raw address.
831 if arg in sim_users:
832 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000833 else:
834 self.push('550 No such user: %s' % arg)
835
836 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400837 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000838 if list_name in sim_lists:
839 user_list = sim_lists[list_name]
840 for n, user_email in enumerate(user_list):
841 quoted_addr = smtplib.quoteaddr(user_email)
842 if n < len(user_list) - 1:
843 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
844 else:
845 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
846 else:
847 self.push('550 No access for you!')
848
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400849 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400850 if self.quit_response is None:
851 super(SimSMTPChannel, self).smtp_QUIT(arg)
852 else:
853 self.push(self.quit_response)
854 self.close_when_done()
855
R David Murrayd312c742013-03-20 20:36:14 -0400856 def smtp_MAIL(self, arg):
857 if self.mail_response is None:
858 super().smtp_MAIL(arg)
859 else:
860 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400861 if self.disconnect:
862 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400863
864 def smtp_RCPT(self, arg):
865 if self.rcpt_response is None:
866 super().smtp_RCPT(arg)
867 return
R David Murrayd312c742013-03-20 20:36:14 -0400868 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400869 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400870
871 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400872 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400873 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400874
875 def smtp_DATA(self, arg):
876 if self.data_response is None:
877 super().smtp_DATA(arg)
878 else:
879 self.push(self.data_response)
880
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000881 def handle_error(self):
882 raise
883
Guido van Rossum04110fb2007-08-24 16:32:05 +0000884
885class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000886
R David Murrayd312c742013-03-20 20:36:14 -0400887 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400888
R. David Murray23ddc0e2009-05-29 18:03:16 +0000889 def __init__(self, *args, **kw):
890 self._extra_features = []
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100891 self._addresses = {}
R. David Murray23ddc0e2009-05-29 18:03:16 +0000892 smtpd.SMTPServer.__init__(self, *args, **kw)
893
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000894 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400895 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400896 self._extra_features, self, conn, addr,
897 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000898
899 def process_message(self, peer, mailfrom, rcpttos, data):
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100900 self._addresses['from'] = mailfrom
901 self._addresses['tos'] = rcpttos
Guido van Rossum04110fb2007-08-24 16:32:05 +0000902
R. David Murrayfb123912009-05-28 18:19:00 +0000903 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000904 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000905
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000906 def handle_error(self):
907 raise
908
Guido van Rossum04110fb2007-08-24 16:32:05 +0000909
910# Test various SMTP & ESMTP commands/behaviors that require a simulated server
911# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000912class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000913
914 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100915 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000916 self.real_getfqdn = socket.getfqdn
917 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000918 self.serv_evt = threading.Event()
919 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000920 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400921 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000922 # Keep a note of what port was assigned
923 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000924 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000925 self.thread = threading.Thread(target=debugging_server, args=serv_args)
926 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000927
928 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000929 self.serv_evt.wait()
930 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000931
932 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000933 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000934 # indicate that the client is finished
935 self.client_evt.set()
936 # wait for the server thread to terminate
937 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100938 join_thread(self.thread)
939 del self.thread
940 self.doCleanups()
941 threading_cleanup(*self.thread_key)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000942
943 def testBasic(self):
944 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000945 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000946 smtp.quit()
947
948 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000949 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000950
951 # no features should be present before the EHLO
952 self.assertEqual(smtp.esmtp_features, {})
953
954 # features expected from the test server
955 expected_features = {'expn':'',
956 'size': '20000000',
957 'starttls': '',
958 'deliverby': '',
959 'help': '',
960 }
961
962 smtp.ehlo()
963 self.assertEqual(smtp.esmtp_features, expected_features)
964 for k in expected_features:
965 self.assertTrue(smtp.has_extn(k))
966 self.assertFalse(smtp.has_extn('unsupported-feature'))
967 smtp.quit()
968
969 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000970 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000971
Barry Warsawc5ea7542015-07-09 10:39:55 -0400972 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +0000973 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -0400974 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000975 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -0400976 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000977
978 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400979 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000980 self.assertEqual(smtp.vrfy(u), expected_unknown)
981 smtp.quit()
982
983 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000984 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000985
986 for listname, members in sim_lists.items():
987 users = []
988 for m in members:
989 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000990 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000991 self.assertEqual(smtp.expn(listname), expected_known)
992
993 u = 'PSU-Members-List'
994 expected_unknown = (550, b'No access for you!')
995 self.assertEqual(smtp.expn(u), expected_unknown)
996 smtp.quit()
997
R David Murray76e13c12014-07-03 14:47:46 -0400998 def testAUTH_PLAIN(self):
999 self.serv.add_feature("AUTH PLAIN")
1000 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001001 resp = smtp.login(sim_auth[0], sim_auth[1])
1002 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001003 smtp.close()
1004
R. David Murrayfb123912009-05-28 18:19:00 +00001005 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001006 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +00001007 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001008 resp = smtp.login(sim_auth[0], sim_auth[1])
1009 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001010 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001011
1012 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001013 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +00001014 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001015 resp = smtp.login(sim_auth[0], sim_auth[1])
1016 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001017 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001018
Andrew Kuchling78591822013-11-11 14:03:23 -05001019 def testAUTH_multiple(self):
1020 # Test that multiple authentication methods are tried.
1021 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
1022 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001023 resp = smtp.login(sim_auth[0], sim_auth[1])
1024 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001025 smtp.close()
1026
1027 def test_auth_function(self):
R David Murrayb0deeb42015-11-08 01:03:52 -05001028 supported = {'CRAM-MD5', 'PLAIN', 'LOGIN'}
1029 for mechanism in supported:
1030 self.serv.add_feature("AUTH {}".format(mechanism))
1031 for mechanism in supported:
1032 with self.subTest(mechanism=mechanism):
1033 smtp = smtplib.SMTP(HOST, self.port,
1034 local_hostname='localhost', timeout=15)
1035 smtp.ehlo('foo')
1036 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
1037 method = 'auth_' + mechanism.lower().replace('-', '_')
1038 resp = smtp.auth(mechanism, getattr(smtp, method))
1039 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1040 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -05001041
R David Murray0cff49f2014-08-30 16:51:59 -04001042 def test_quit_resets_greeting(self):
1043 smtp = smtplib.SMTP(HOST, self.port,
1044 local_hostname='localhost',
1045 timeout=15)
1046 code, message = smtp.ehlo()
1047 self.assertEqual(code, 250)
1048 self.assertIn('size', smtp.esmtp_features)
1049 smtp.quit()
1050 self.assertNotIn('size', smtp.esmtp_features)
1051 smtp.connect(HOST, self.port)
1052 self.assertNotIn('size', smtp.esmtp_features)
1053 smtp.ehlo_or_helo_if_needed()
1054 self.assertIn('size', smtp.esmtp_features)
1055 smtp.quit()
1056
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001057 def test_with_statement(self):
1058 with smtplib.SMTP(HOST, self.port) as smtp:
1059 code, message = smtp.noop()
1060 self.assertEqual(code, 250)
1061 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1062 with smtplib.SMTP(HOST, self.port) as smtp:
1063 smtp.close()
1064 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1065
1066 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001067 with self.assertRaises(smtplib.SMTPResponseException) as error:
1068 with smtplib.SMTP(HOST, self.port) as smtp:
1069 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001070 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001071 self.assertEqual(error.exception.smtp_code, 421)
1072 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001073
R. David Murrayfb123912009-05-28 18:19:00 +00001074 #TODO: add tests for correct AUTH method fallback now that the
1075 #test infrastructure can support it.
1076
R David Murrayafb151a2014-04-14 18:21:38 -04001077 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1078 def test__rest_from_mail_cmd(self):
1079 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
1080 smtp.noop()
1081 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1082 self.serv._SMTPchannel.disconnect = True
1083 with self.assertRaises(smtplib.SMTPSenderRefused):
1084 smtp.sendmail('John', 'Sally', 'test message')
1085 self.assertIsNone(smtp.sock)
1086
R David Murrayd312c742013-03-20 20:36:14 -04001087 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1088 def test_421_from_mail_cmd(self):
1089 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001090 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001091 self.serv._SMTPchannel.mail_response = '421 closing connection'
1092 with self.assertRaises(smtplib.SMTPSenderRefused):
1093 smtp.sendmail('John', 'Sally', 'test message')
1094 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001095 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001096
1097 def test_421_from_rcpt_cmd(self):
1098 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001099 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001100 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1101 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1102 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1103 self.assertIsNone(smtp.sock)
1104 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1105 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1106
1107 def test_421_from_data_cmd(self):
1108 class MySimSMTPChannel(SimSMTPChannel):
1109 def found_terminator(self):
1110 if self.smtp_state == self.DATA:
1111 self.push('421 closing')
1112 else:
1113 super().found_terminator()
1114 self.serv.channel_class = MySimSMTPChannel
1115 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001116 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001117 with self.assertRaises(smtplib.SMTPDataError):
1118 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1119 self.assertIsNone(smtp.sock)
1120 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1121
R David Murraycee7cf62015-05-16 13:58:14 -04001122 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1123 smtp = smtplib.SMTP(
1124 HOST, self.port, local_hostname='localhost', timeout=3)
1125 self.addCleanup(smtp.close)
1126 smtp.ehlo()
1127 self.assertTrue(smtp.does_esmtp)
1128 self.assertFalse(smtp.has_extn('smtputf8'))
1129 self.assertRaises(
1130 smtplib.SMTPNotSupportedError,
1131 smtp.sendmail,
1132 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1133 self.assertRaises(
1134 smtplib.SMTPNotSupportedError,
1135 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1136
1137 def test_send_unicode_without_SMTPUTF8(self):
1138 smtp = smtplib.SMTP(
1139 HOST, self.port, local_hostname='localhost', timeout=3)
1140 self.addCleanup(smtp.close)
1141 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1142 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1143
chason48ed88a2018-07-26 04:01:28 +09001144 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1145 # This test is located here and not in the SMTPUTF8SimTests
1146 # class because it needs a "regular" SMTP server to work
1147 msg = EmailMessage()
1148 msg['From'] = "Páolo <főo@bar.com>"
1149 msg['To'] = 'Dinsdale'
1150 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1151 smtp = smtplib.SMTP(
1152 HOST, self.port, local_hostname='localhost', timeout=3)
1153 self.addCleanup(smtp.close)
1154 with self.assertRaises(smtplib.SMTPNotSupportedError):
1155 smtp.send_message(msg)
1156
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001157 def test_name_field_not_included_in_envelop_addresses(self):
1158 smtp = smtplib.SMTP(
1159 HOST, self.port, local_hostname='localhost', timeout=3
1160 )
1161 self.addCleanup(smtp.close)
1162
1163 message = EmailMessage()
1164 message['From'] = email.utils.formataddr(('Michaël', 'michael@example.com'))
1165 message['To'] = email.utils.formataddr(('René', 'rene@example.com'))
1166
1167 self.assertDictEqual(smtp.send_message(message), {})
1168
1169 self.assertEqual(self.serv._addresses['from'], 'michael@example.com')
1170 self.assertEqual(self.serv._addresses['tos'], ['rene@example.com'])
1171
R David Murraycee7cf62015-05-16 13:58:14 -04001172
1173class SimSMTPUTF8Server(SimSMTPServer):
1174
1175 def __init__(self, *args, **kw):
1176 # The base SMTP server turns these on automatically, but our test
1177 # server is set up to munge the EHLO response, so we need to provide
1178 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1179 self._extra_features = ['SMTPUTF8', '8BITMIME']
1180 smtpd.SMTPServer.__init__(self, *args, **kw)
1181
1182 def handle_accepted(self, conn, addr):
1183 self._SMTPchannel = self.channel_class(
1184 self._extra_features, self, conn, addr,
1185 decode_data=self._decode_data,
1186 enable_SMTPUTF8=self.enable_SMTPUTF8,
1187 )
1188
1189 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1190 rcpt_options=None):
1191 self.last_peer = peer
1192 self.last_mailfrom = mailfrom
1193 self.last_rcpttos = rcpttos
1194 self.last_message = data
1195 self.last_mail_options = mail_options
1196 self.last_rcpt_options = rcpt_options
1197
1198
R David Murraycee7cf62015-05-16 13:58:14 -04001199class SMTPUTF8SimTests(unittest.TestCase):
1200
R David Murray83084442015-05-17 19:27:22 -04001201 maxDiff = None
1202
R David Murraycee7cf62015-05-16 13:58:14 -04001203 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001204 self.thread_key = threading_setup()
R David Murraycee7cf62015-05-16 13:58:14 -04001205 self.real_getfqdn = socket.getfqdn
1206 socket.getfqdn = mock_socket.getfqdn
1207 self.serv_evt = threading.Event()
1208 self.client_evt = threading.Event()
1209 # Pick a random unused port by passing 0 for the port number
1210 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1211 decode_data=False,
1212 enable_SMTPUTF8=True)
1213 # Keep a note of what port was assigned
1214 self.port = self.serv.socket.getsockname()[1]
1215 serv_args = (self.serv, self.serv_evt, self.client_evt)
1216 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1217 self.thread.start()
1218
1219 # wait until server thread has assigned a port number
1220 self.serv_evt.wait()
1221 self.serv_evt.clear()
1222
1223 def tearDown(self):
1224 socket.getfqdn = self.real_getfqdn
1225 # indicate that the client is finished
1226 self.client_evt.set()
1227 # wait for the server thread to terminate
1228 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001229 join_thread(self.thread)
1230 del self.thread
1231 self.doCleanups()
1232 threading_cleanup(*self.thread_key)
R David Murraycee7cf62015-05-16 13:58:14 -04001233
1234 def test_test_server_supports_extensions(self):
1235 smtp = smtplib.SMTP(
1236 HOST, self.port, local_hostname='localhost', timeout=3)
1237 self.addCleanup(smtp.close)
1238 smtp.ehlo()
1239 self.assertTrue(smtp.does_esmtp)
1240 self.assertTrue(smtp.has_extn('smtputf8'))
1241
1242 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1243 m = '¡a test message containing unicode!'.encode('utf-8')
1244 smtp = smtplib.SMTP(
1245 HOST, self.port, local_hostname='localhost', timeout=3)
1246 self.addCleanup(smtp.close)
1247 smtp.sendmail('Jőhn', 'Sálly', m,
1248 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1249 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1250 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1251 self.assertEqual(self.serv.last_message, m)
1252 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1253 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1254 self.assertEqual(self.serv.last_rcpt_options, [])
1255
1256 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1257 m = '¡a test message containing unicode!'.encode('utf-8')
1258 smtp = smtplib.SMTP(
1259 HOST, self.port, local_hostname='localhost', timeout=3)
1260 self.addCleanup(smtp.close)
1261 smtp.ehlo()
1262 self.assertEqual(
1263 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1264 (250, b'OK'))
1265 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1266 self.assertEqual(smtp.data(m), (250, b'OK'))
1267 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1268 self.assertEqual(self.serv.last_rcpttos, ['János'])
1269 self.assertEqual(self.serv.last_message, m)
1270 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1271 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1272 self.assertEqual(self.serv.last_rcpt_options, [])
1273
R David Murray83084442015-05-17 19:27:22 -04001274 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1275 msg = EmailMessage()
1276 msg['From'] = "Páolo <főo@bar.com>"
1277 msg['To'] = 'Dinsdale'
1278 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1279 # XXX I don't know why I need two \n's here, but this is an existing
1280 # bug (if it is one) and not a problem with the new functionality.
1281 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1282 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1283 # we are successfully sending /r/n :(.
1284 expected = textwrap.dedent("""\
1285 From: Páolo <főo@bar.com>
1286 To: Dinsdale
1287 Subject: Nudge nudge, wink, wink \u1F609
1288 Content-Type: text/plain; charset="utf-8"
1289 Content-Transfer-Encoding: 8bit
1290 MIME-Version: 1.0
1291
1292 oh là là, know what I mean, know what I mean?
1293 """)
1294 smtp = smtplib.SMTP(
1295 HOST, self.port, local_hostname='localhost', timeout=3)
1296 self.addCleanup(smtp.close)
1297 self.assertEqual(smtp.send_message(msg), {})
1298 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1299 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1300 self.assertEqual(self.serv.last_message.decode(), expected)
1301 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1302 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1303 self.assertEqual(self.serv.last_rcpt_options, [])
1304
Guido van Rossum04110fb2007-08-24 16:32:05 +00001305
Barry Warsawc5ea7542015-07-09 10:39:55 -04001306EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1307
1308class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1309 def smtp_AUTH(self, arg):
1310 # RFC 4954's AUTH command allows for an optional initial-response.
1311 # Not all AUTH methods support this; some require a challenge. AUTH
1312 # PLAIN does those, so test that here. See issue #15014.
1313 args = arg.split()
1314 if args[0].lower() == 'plain':
1315 if len(args) == 2:
1316 # AUTH PLAIN <initial-response> with the response base 64
1317 # encoded. Hard code the expected response for the test.
1318 if args[1] == EXPECTED_RESPONSE:
1319 self.push('235 Ok')
1320 return
1321 self.push('571 Bad authentication')
1322
1323class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1324 channel_class = SimSMTPAUTHInitialResponseChannel
1325
1326
Barry Warsawc5ea7542015-07-09 10:39:55 -04001327class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1328 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001329 self.thread_key = threading_setup()
Barry Warsawc5ea7542015-07-09 10:39:55 -04001330 self.real_getfqdn = socket.getfqdn
1331 socket.getfqdn = mock_socket.getfqdn
1332 self.serv_evt = threading.Event()
1333 self.client_evt = threading.Event()
1334 # Pick a random unused port by passing 0 for the port number
1335 self.serv = SimSMTPAUTHInitialResponseServer(
1336 (HOST, 0), ('nowhere', -1), decode_data=True)
1337 # Keep a note of what port was assigned
1338 self.port = self.serv.socket.getsockname()[1]
1339 serv_args = (self.serv, self.serv_evt, self.client_evt)
1340 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1341 self.thread.start()
1342
1343 # wait until server thread has assigned a port number
1344 self.serv_evt.wait()
1345 self.serv_evt.clear()
1346
1347 def tearDown(self):
1348 socket.getfqdn = self.real_getfqdn
1349 # indicate that the client is finished
1350 self.client_evt.set()
1351 # wait for the server thread to terminate
1352 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001353 join_thread(self.thread)
1354 del self.thread
1355 self.doCleanups()
1356 threading_cleanup(*self.thread_key)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001357
1358 def testAUTH_PLAIN_initial_response_login(self):
1359 self.serv.add_feature('AUTH PLAIN')
1360 smtp = smtplib.SMTP(HOST, self.port,
1361 local_hostname='localhost', timeout=15)
1362 smtp.login('psu', 'doesnotexist')
1363 smtp.close()
1364
1365 def testAUTH_PLAIN_initial_response_auth(self):
1366 self.serv.add_feature('AUTH PLAIN')
1367 smtp = smtplib.SMTP(HOST, self.port,
1368 local_hostname='localhost', timeout=15)
1369 smtp.user = 'psu'
1370 smtp.password = 'doesnotexist'
1371 code, response = smtp.auth('plain', smtp.auth_plain)
1372 smtp.close()
1373 self.assertEqual(code, 235)
1374
1375
Guido van Rossumd8faa362007-04-27 19:54:29 +00001376if __name__ == '__main__':
chason48ed88a2018-07-26 04:01:28 +09001377 unittest.main()