blob: 0c863ed7e2030ab53bf7c4cf9f4bacd261e738d7 [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
605
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200606class DefaultArgumentsTests(unittest.TestCase):
607
608 def setUp(self):
609 self.msg = EmailMessage()
610 self.msg['From'] = 'Páolo <főo@bar.com>'
611 self.smtp = smtplib.SMTP()
612 self.smtp.ehlo = Mock(return_value=(200, 'OK'))
613 self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
614
615 def testSendMessage(self):
616 expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
617 self.smtp.send_message(self.msg)
618 self.smtp.send_message(self.msg)
619 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
620 expected_mail_options)
621 self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
622 expected_mail_options)
623
624 def testSendMessageWithMailOptions(self):
625 mail_options = ['STARTTLS']
626 expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
627 self.smtp.send_message(self.msg, None, None, mail_options)
628 self.assertEqual(mail_options, ['STARTTLS'])
629 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
630 expected_mail_options)
631
632
Guido van Rossum04110fb2007-08-24 16:32:05 +0000633# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000634class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000635
636 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000637 smtplib.socket = mock_socket
638 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000639 self.old_stdout = sys.stdout
640 self.output = io.StringIO()
641 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000642 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000643
644 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000645 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000646 sys.stdout = self.old_stdout
647
648 def testFailingHELO(self):
649 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000650 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000651
Guido van Rossum04110fb2007-08-24 16:32:05 +0000652
Georg Brandlb38b5c42014-02-10 22:11:21 +0100653class TooLongLineTests(unittest.TestCase):
654 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
655
656 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100657 self.thread_key = threading_setup()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100658 self.old_stdout = sys.stdout
659 self.output = io.StringIO()
660 sys.stdout = self.output
661
662 self.evt = threading.Event()
663 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
664 self.sock.settimeout(15)
665 self.port = support.bind_port(self.sock)
666 servargs = (self.evt, self.respdata, self.sock)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100667 self.thread = threading.Thread(target=server, args=servargs)
668 self.thread.start()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100669 self.evt.wait()
670 self.evt.clear()
671
672 def tearDown(self):
673 self.evt.wait()
674 sys.stdout = self.old_stdout
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100675 join_thread(self.thread)
676 del self.thread
677 self.doCleanups()
678 threading_cleanup(*self.thread_key)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100679
680 def testLineTooLong(self):
681 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
682 HOST, self.port, 'localhost', 3)
683
684
Guido van Rossum04110fb2007-08-24 16:32:05 +0000685sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400686 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000687 'Mrs.C@somewhereesle.com':'Ruth C',
688 }
689
R. David Murraycaa27b72009-05-23 18:49:56 +0000690sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000691sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
692 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000693sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400694 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000695 }
696
697# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500698class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000699class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000700
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400701 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400702 mail_response = None
703 rcpt_response = None
704 data_response = None
705 rcpt_count = 0
706 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400707 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500708 AUTH = 99 # Add protocol state to enable auth testing.
709 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400710
R. David Murray23ddc0e2009-05-29 18:03:16 +0000711 def __init__(self, extra_features, *args, **kw):
712 self._extrafeatures = ''.join(
713 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000714 super(SimSMTPChannel, self).__init__(*args, **kw)
715
R David Murrayb0deeb42015-11-08 01:03:52 -0500716 # AUTH related stuff. It would be nice if support for this were in smtpd.
717 def found_terminator(self):
718 if self.smtp_state == self.AUTH:
719 line = self._emptystring.join(self.received_lines)
720 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
721 self.received_lines = []
722 try:
723 self.auth_object(line)
724 except ResponseException as e:
725 self.smtp_state = self.COMMAND
726 self.push('%s %s' % (e.smtp_code, e.smtp_error))
727 return
728 super().found_terminator()
729
730
731 def smtp_AUTH(self, arg):
732 if not self.seen_greeting:
733 self.push('503 Error: send EHLO first')
734 return
735 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
736 self.push('500 Error: command "AUTH" not recognized')
737 return
738 if self.authenticated_user is not None:
739 self.push(
740 '503 Bad sequence of commands: already authenticated')
741 return
742 args = arg.split()
743 if len(args) not in [1, 2]:
744 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
745 return
746 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
747 try:
748 self.auth_object = getattr(self, auth_object_name)
749 except AttributeError:
750 self.push('504 Command parameter not implemented: unsupported '
751 ' authentication mechanism {!r}'.format(auth_object_name))
752 return
753 self.smtp_state = self.AUTH
754 self.auth_object(args[1] if len(args) == 2 else None)
755
756 def _authenticated(self, user, valid):
757 if valid:
758 self.authenticated_user = user
759 self.push('235 Authentication Succeeded')
760 else:
761 self.push('535 Authentication credentials invalid')
762 self.smtp_state = self.COMMAND
763
764 def _decode_base64(self, string):
765 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
766
767 def _auth_plain(self, arg=None):
768 if arg is None:
769 self.push('334 ')
770 else:
771 logpass = self._decode_base64(arg)
772 try:
773 *_, user, password = logpass.split('\0')
774 except ValueError as e:
775 self.push('535 Splitting response {!r} into user and password'
776 ' failed: {}'.format(logpass, e))
777 return
778 self._authenticated(user, password == sim_auth[1])
779
780 def _auth_login(self, arg=None):
781 if arg is None:
782 # base64 encoded 'Username:'
783 self.push('334 VXNlcm5hbWU6')
784 elif not hasattr(self, '_auth_login_user'):
785 self._auth_login_user = self._decode_base64(arg)
786 # base64 encoded 'Password:'
787 self.push('334 UGFzc3dvcmQ6')
788 else:
789 password = self._decode_base64(arg)
790 self._authenticated(self._auth_login_user, password == sim_auth[1])
791 del self._auth_login_user
792
793 def _auth_cram_md5(self, arg=None):
794 if arg is None:
795 self.push('334 {}'.format(sim_cram_md5_challenge))
796 else:
797 logpass = self._decode_base64(arg)
798 try:
799 user, hashed_pass = logpass.split()
800 except ValueError as e:
801 self.push('535 Splitting response {!r} into user and password'
802 'failed: {}'.format(logpass, e))
803 return False
804 valid_hashed_pass = hmac.HMAC(
805 sim_auth[1].encode('ascii'),
806 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
807 'md5').hexdigest()
808 self._authenticated(user, hashed_pass == valid_hashed_pass)
809 # end AUTH related stuff.
810
Guido van Rossum04110fb2007-08-24 16:32:05 +0000811 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000812 resp = ('250-testhost\r\n'
813 '250-EXPN\r\n'
814 '250-SIZE 20000000\r\n'
815 '250-STARTTLS\r\n'
816 '250-DELIVERBY\r\n')
817 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000818 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400819 self.seen_greeting = arg
820 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000821
822 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400823 # For max compatibility smtplib should be sending the raw address.
824 if arg in sim_users:
825 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000826 else:
827 self.push('550 No such user: %s' % arg)
828
829 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400830 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000831 if list_name in sim_lists:
832 user_list = sim_lists[list_name]
833 for n, user_email in enumerate(user_list):
834 quoted_addr = smtplib.quoteaddr(user_email)
835 if n < len(user_list) - 1:
836 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
837 else:
838 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
839 else:
840 self.push('550 No access for you!')
841
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400842 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400843 if self.quit_response is None:
844 super(SimSMTPChannel, self).smtp_QUIT(arg)
845 else:
846 self.push(self.quit_response)
847 self.close_when_done()
848
R David Murrayd312c742013-03-20 20:36:14 -0400849 def smtp_MAIL(self, arg):
850 if self.mail_response is None:
851 super().smtp_MAIL(arg)
852 else:
853 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400854 if self.disconnect:
855 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400856
857 def smtp_RCPT(self, arg):
858 if self.rcpt_response is None:
859 super().smtp_RCPT(arg)
860 return
R David Murrayd312c742013-03-20 20:36:14 -0400861 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400862 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400863
864 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400865 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400866 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400867
868 def smtp_DATA(self, arg):
869 if self.data_response is None:
870 super().smtp_DATA(arg)
871 else:
872 self.push(self.data_response)
873
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000874 def handle_error(self):
875 raise
876
Guido van Rossum04110fb2007-08-24 16:32:05 +0000877
878class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000879
R David Murrayd312c742013-03-20 20:36:14 -0400880 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400881
R. David Murray23ddc0e2009-05-29 18:03:16 +0000882 def __init__(self, *args, **kw):
883 self._extra_features = []
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100884 self._addresses = {}
R. David Murray23ddc0e2009-05-29 18:03:16 +0000885 smtpd.SMTPServer.__init__(self, *args, **kw)
886
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000887 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400888 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400889 self._extra_features, self, conn, addr,
890 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000891
892 def process_message(self, peer, mailfrom, rcpttos, data):
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100893 self._addresses['from'] = mailfrom
894 self._addresses['tos'] = rcpttos
Guido van Rossum04110fb2007-08-24 16:32:05 +0000895
R. David Murrayfb123912009-05-28 18:19:00 +0000896 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000897 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000898
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000899 def handle_error(self):
900 raise
901
Guido van Rossum04110fb2007-08-24 16:32:05 +0000902
903# Test various SMTP & ESMTP commands/behaviors that require a simulated server
904# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000905class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000906
907 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100908 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000909 self.real_getfqdn = socket.getfqdn
910 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000911 self.serv_evt = threading.Event()
912 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000913 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400914 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000915 # Keep a note of what port was assigned
916 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000917 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000918 self.thread = threading.Thread(target=debugging_server, args=serv_args)
919 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000920
921 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000922 self.serv_evt.wait()
923 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000924
925 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000926 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000927 # indicate that the client is finished
928 self.client_evt.set()
929 # wait for the server thread to terminate
930 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100931 join_thread(self.thread)
932 del self.thread
933 self.doCleanups()
934 threading_cleanup(*self.thread_key)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000935
936 def testBasic(self):
937 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000938 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000939 smtp.quit()
940
941 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000942 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000943
944 # no features should be present before the EHLO
945 self.assertEqual(smtp.esmtp_features, {})
946
947 # features expected from the test server
948 expected_features = {'expn':'',
949 'size': '20000000',
950 'starttls': '',
951 'deliverby': '',
952 'help': '',
953 }
954
955 smtp.ehlo()
956 self.assertEqual(smtp.esmtp_features, expected_features)
957 for k in expected_features:
958 self.assertTrue(smtp.has_extn(k))
959 self.assertFalse(smtp.has_extn('unsupported-feature'))
960 smtp.quit()
961
962 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000963 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000964
Barry Warsawc5ea7542015-07-09 10:39:55 -0400965 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +0000966 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -0400967 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000968 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -0400969 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000970
971 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -0400972 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000973 self.assertEqual(smtp.vrfy(u), expected_unknown)
974 smtp.quit()
975
976 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000977 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000978
979 for listname, members in sim_lists.items():
980 users = []
981 for m in members:
982 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000983 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000984 self.assertEqual(smtp.expn(listname), expected_known)
985
986 u = 'PSU-Members-List'
987 expected_unknown = (550, b'No access for you!')
988 self.assertEqual(smtp.expn(u), expected_unknown)
989 smtp.quit()
990
R David Murray76e13c12014-07-03 14:47:46 -0400991 def testAUTH_PLAIN(self):
992 self.serv.add_feature("AUTH PLAIN")
993 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -0500994 resp = smtp.login(sim_auth[0], sim_auth[1])
995 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -0400996 smtp.close()
997
R. David Murrayfb123912009-05-28 18:19:00 +0000998 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000999 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +00001000 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'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001003 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001004
1005 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001006 self.serv.add_feature("AUTH CRAM-MD5")
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
Andrew Kuchling78591822013-11-11 14:03:23 -05001012 def testAUTH_multiple(self):
1013 # Test that multiple authentication methods are tried.
1014 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
1015 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001016 resp = smtp.login(sim_auth[0], sim_auth[1])
1017 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001018 smtp.close()
1019
1020 def test_auth_function(self):
R David Murrayb0deeb42015-11-08 01:03:52 -05001021 supported = {'CRAM-MD5', 'PLAIN', 'LOGIN'}
1022 for mechanism in supported:
1023 self.serv.add_feature("AUTH {}".format(mechanism))
1024 for mechanism in supported:
1025 with self.subTest(mechanism=mechanism):
1026 smtp = smtplib.SMTP(HOST, self.port,
1027 local_hostname='localhost', timeout=15)
1028 smtp.ehlo('foo')
1029 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
1030 method = 'auth_' + mechanism.lower().replace('-', '_')
1031 resp = smtp.auth(mechanism, getattr(smtp, method))
1032 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1033 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -05001034
R David Murray0cff49f2014-08-30 16:51:59 -04001035 def test_quit_resets_greeting(self):
1036 smtp = smtplib.SMTP(HOST, self.port,
1037 local_hostname='localhost',
1038 timeout=15)
1039 code, message = smtp.ehlo()
1040 self.assertEqual(code, 250)
1041 self.assertIn('size', smtp.esmtp_features)
1042 smtp.quit()
1043 self.assertNotIn('size', smtp.esmtp_features)
1044 smtp.connect(HOST, self.port)
1045 self.assertNotIn('size', smtp.esmtp_features)
1046 smtp.ehlo_or_helo_if_needed()
1047 self.assertIn('size', smtp.esmtp_features)
1048 smtp.quit()
1049
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001050 def test_with_statement(self):
1051 with smtplib.SMTP(HOST, self.port) as smtp:
1052 code, message = smtp.noop()
1053 self.assertEqual(code, 250)
1054 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1055 with smtplib.SMTP(HOST, self.port) as smtp:
1056 smtp.close()
1057 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1058
1059 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001060 with self.assertRaises(smtplib.SMTPResponseException) as error:
1061 with smtplib.SMTP(HOST, self.port) as smtp:
1062 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001063 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001064 self.assertEqual(error.exception.smtp_code, 421)
1065 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001066
R. David Murrayfb123912009-05-28 18:19:00 +00001067 #TODO: add tests for correct AUTH method fallback now that the
1068 #test infrastructure can support it.
1069
R David Murrayafb151a2014-04-14 18:21:38 -04001070 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1071 def test__rest_from_mail_cmd(self):
1072 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
1073 smtp.noop()
1074 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1075 self.serv._SMTPchannel.disconnect = True
1076 with self.assertRaises(smtplib.SMTPSenderRefused):
1077 smtp.sendmail('John', 'Sally', 'test message')
1078 self.assertIsNone(smtp.sock)
1079
R David Murrayd312c742013-03-20 20:36:14 -04001080 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1081 def test_421_from_mail_cmd(self):
1082 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001083 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001084 self.serv._SMTPchannel.mail_response = '421 closing connection'
1085 with self.assertRaises(smtplib.SMTPSenderRefused):
1086 smtp.sendmail('John', 'Sally', 'test message')
1087 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001088 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001089
1090 def test_421_from_rcpt_cmd(self):
1091 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001092 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001093 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1094 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1095 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1096 self.assertIsNone(smtp.sock)
1097 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1098 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1099
1100 def test_421_from_data_cmd(self):
1101 class MySimSMTPChannel(SimSMTPChannel):
1102 def found_terminator(self):
1103 if self.smtp_state == self.DATA:
1104 self.push('421 closing')
1105 else:
1106 super().found_terminator()
1107 self.serv.channel_class = MySimSMTPChannel
1108 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001109 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001110 with self.assertRaises(smtplib.SMTPDataError):
1111 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1112 self.assertIsNone(smtp.sock)
1113 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1114
R David Murraycee7cf62015-05-16 13:58:14 -04001115 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1116 smtp = smtplib.SMTP(
1117 HOST, self.port, local_hostname='localhost', timeout=3)
1118 self.addCleanup(smtp.close)
1119 smtp.ehlo()
1120 self.assertTrue(smtp.does_esmtp)
1121 self.assertFalse(smtp.has_extn('smtputf8'))
1122 self.assertRaises(
1123 smtplib.SMTPNotSupportedError,
1124 smtp.sendmail,
1125 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1126 self.assertRaises(
1127 smtplib.SMTPNotSupportedError,
1128 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1129
1130 def test_send_unicode_without_SMTPUTF8(self):
1131 smtp = smtplib.SMTP(
1132 HOST, self.port, local_hostname='localhost', timeout=3)
1133 self.addCleanup(smtp.close)
1134 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1135 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1136
chason48ed88a2018-07-26 04:01:28 +09001137 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1138 # This test is located here and not in the SMTPUTF8SimTests
1139 # class because it needs a "regular" SMTP server to work
1140 msg = EmailMessage()
1141 msg['From'] = "Páolo <főo@bar.com>"
1142 msg['To'] = 'Dinsdale'
1143 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1144 smtp = smtplib.SMTP(
1145 HOST, self.port, local_hostname='localhost', timeout=3)
1146 self.addCleanup(smtp.close)
1147 with self.assertRaises(smtplib.SMTPNotSupportedError):
1148 smtp.send_message(msg)
1149
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001150 def test_name_field_not_included_in_envelop_addresses(self):
1151 smtp = smtplib.SMTP(
1152 HOST, self.port, local_hostname='localhost', timeout=3
1153 )
1154 self.addCleanup(smtp.close)
1155
1156 message = EmailMessage()
1157 message['From'] = email.utils.formataddr(('Michaël', 'michael@example.com'))
1158 message['To'] = email.utils.formataddr(('René', 'rene@example.com'))
1159
1160 self.assertDictEqual(smtp.send_message(message), {})
1161
1162 self.assertEqual(self.serv._addresses['from'], 'michael@example.com')
1163 self.assertEqual(self.serv._addresses['tos'], ['rene@example.com'])
1164
R David Murraycee7cf62015-05-16 13:58:14 -04001165
1166class SimSMTPUTF8Server(SimSMTPServer):
1167
1168 def __init__(self, *args, **kw):
1169 # The base SMTP server turns these on automatically, but our test
1170 # server is set up to munge the EHLO response, so we need to provide
1171 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1172 self._extra_features = ['SMTPUTF8', '8BITMIME']
1173 smtpd.SMTPServer.__init__(self, *args, **kw)
1174
1175 def handle_accepted(self, conn, addr):
1176 self._SMTPchannel = self.channel_class(
1177 self._extra_features, self, conn, addr,
1178 decode_data=self._decode_data,
1179 enable_SMTPUTF8=self.enable_SMTPUTF8,
1180 )
1181
1182 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1183 rcpt_options=None):
1184 self.last_peer = peer
1185 self.last_mailfrom = mailfrom
1186 self.last_rcpttos = rcpttos
1187 self.last_message = data
1188 self.last_mail_options = mail_options
1189 self.last_rcpt_options = rcpt_options
1190
1191
R David Murraycee7cf62015-05-16 13:58:14 -04001192class SMTPUTF8SimTests(unittest.TestCase):
1193
R David Murray83084442015-05-17 19:27:22 -04001194 maxDiff = None
1195
R David Murraycee7cf62015-05-16 13:58:14 -04001196 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001197 self.thread_key = threading_setup()
R David Murraycee7cf62015-05-16 13:58:14 -04001198 self.real_getfqdn = socket.getfqdn
1199 socket.getfqdn = mock_socket.getfqdn
1200 self.serv_evt = threading.Event()
1201 self.client_evt = threading.Event()
1202 # Pick a random unused port by passing 0 for the port number
1203 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1204 decode_data=False,
1205 enable_SMTPUTF8=True)
1206 # Keep a note of what port was assigned
1207 self.port = self.serv.socket.getsockname()[1]
1208 serv_args = (self.serv, self.serv_evt, self.client_evt)
1209 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1210 self.thread.start()
1211
1212 # wait until server thread has assigned a port number
1213 self.serv_evt.wait()
1214 self.serv_evt.clear()
1215
1216 def tearDown(self):
1217 socket.getfqdn = self.real_getfqdn
1218 # indicate that the client is finished
1219 self.client_evt.set()
1220 # wait for the server thread to terminate
1221 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001222 join_thread(self.thread)
1223 del self.thread
1224 self.doCleanups()
1225 threading_cleanup(*self.thread_key)
R David Murraycee7cf62015-05-16 13:58:14 -04001226
1227 def test_test_server_supports_extensions(self):
1228 smtp = smtplib.SMTP(
1229 HOST, self.port, local_hostname='localhost', timeout=3)
1230 self.addCleanup(smtp.close)
1231 smtp.ehlo()
1232 self.assertTrue(smtp.does_esmtp)
1233 self.assertTrue(smtp.has_extn('smtputf8'))
1234
1235 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1236 m = '¡a test message containing unicode!'.encode('utf-8')
1237 smtp = smtplib.SMTP(
1238 HOST, self.port, local_hostname='localhost', timeout=3)
1239 self.addCleanup(smtp.close)
1240 smtp.sendmail('Jőhn', 'Sálly', m,
1241 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1242 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1243 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1244 self.assertEqual(self.serv.last_message, m)
1245 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1246 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1247 self.assertEqual(self.serv.last_rcpt_options, [])
1248
1249 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1250 m = '¡a test message containing unicode!'.encode('utf-8')
1251 smtp = smtplib.SMTP(
1252 HOST, self.port, local_hostname='localhost', timeout=3)
1253 self.addCleanup(smtp.close)
1254 smtp.ehlo()
1255 self.assertEqual(
1256 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1257 (250, b'OK'))
1258 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1259 self.assertEqual(smtp.data(m), (250, b'OK'))
1260 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1261 self.assertEqual(self.serv.last_rcpttos, ['János'])
1262 self.assertEqual(self.serv.last_message, m)
1263 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1264 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1265 self.assertEqual(self.serv.last_rcpt_options, [])
1266
R David Murray83084442015-05-17 19:27:22 -04001267 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1268 msg = EmailMessage()
1269 msg['From'] = "Páolo <főo@bar.com>"
1270 msg['To'] = 'Dinsdale'
1271 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1272 # XXX I don't know why I need two \n's here, but this is an existing
1273 # bug (if it is one) and not a problem with the new functionality.
1274 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1275 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1276 # we are successfully sending /r/n :(.
1277 expected = textwrap.dedent("""\
1278 From: Páolo <főo@bar.com>
1279 To: Dinsdale
1280 Subject: Nudge nudge, wink, wink \u1F609
1281 Content-Type: text/plain; charset="utf-8"
1282 Content-Transfer-Encoding: 8bit
1283 MIME-Version: 1.0
1284
1285 oh là là, know what I mean, know what I mean?
1286 """)
1287 smtp = smtplib.SMTP(
1288 HOST, self.port, local_hostname='localhost', timeout=3)
1289 self.addCleanup(smtp.close)
1290 self.assertEqual(smtp.send_message(msg), {})
1291 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1292 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1293 self.assertEqual(self.serv.last_message.decode(), expected)
1294 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1295 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1296 self.assertEqual(self.serv.last_rcpt_options, [])
1297
Guido van Rossum04110fb2007-08-24 16:32:05 +00001298
Barry Warsawc5ea7542015-07-09 10:39:55 -04001299EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1300
1301class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1302 def smtp_AUTH(self, arg):
1303 # RFC 4954's AUTH command allows for an optional initial-response.
1304 # Not all AUTH methods support this; some require a challenge. AUTH
1305 # PLAIN does those, so test that here. See issue #15014.
1306 args = arg.split()
1307 if args[0].lower() == 'plain':
1308 if len(args) == 2:
1309 # AUTH PLAIN <initial-response> with the response base 64
1310 # encoded. Hard code the expected response for the test.
1311 if args[1] == EXPECTED_RESPONSE:
1312 self.push('235 Ok')
1313 return
1314 self.push('571 Bad authentication')
1315
1316class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1317 channel_class = SimSMTPAUTHInitialResponseChannel
1318
1319
Barry Warsawc5ea7542015-07-09 10:39:55 -04001320class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1321 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001322 self.thread_key = threading_setup()
Barry Warsawc5ea7542015-07-09 10:39:55 -04001323 self.real_getfqdn = socket.getfqdn
1324 socket.getfqdn = mock_socket.getfqdn
1325 self.serv_evt = threading.Event()
1326 self.client_evt = threading.Event()
1327 # Pick a random unused port by passing 0 for the port number
1328 self.serv = SimSMTPAUTHInitialResponseServer(
1329 (HOST, 0), ('nowhere', -1), decode_data=True)
1330 # Keep a note of what port was assigned
1331 self.port = self.serv.socket.getsockname()[1]
1332 serv_args = (self.serv, self.serv_evt, self.client_evt)
1333 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1334 self.thread.start()
1335
1336 # wait until server thread has assigned a port number
1337 self.serv_evt.wait()
1338 self.serv_evt.clear()
1339
1340 def tearDown(self):
1341 socket.getfqdn = self.real_getfqdn
1342 # indicate that the client is finished
1343 self.client_evt.set()
1344 # wait for the server thread to terminate
1345 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001346 join_thread(self.thread)
1347 del self.thread
1348 self.doCleanups()
1349 threading_cleanup(*self.thread_key)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001350
1351 def testAUTH_PLAIN_initial_response_login(self):
1352 self.serv.add_feature('AUTH PLAIN')
1353 smtp = smtplib.SMTP(HOST, self.port,
1354 local_hostname='localhost', timeout=15)
1355 smtp.login('psu', 'doesnotexist')
1356 smtp.close()
1357
1358 def testAUTH_PLAIN_initial_response_auth(self):
1359 self.serv.add_feature('AUTH PLAIN')
1360 smtp = smtplib.SMTP(HOST, self.port,
1361 local_hostname='localhost', timeout=15)
1362 smtp.user = 'psu'
1363 smtp.password = 'doesnotexist'
1364 code, response = smtp.auth('plain', smtp.auth_plain)
1365 smtp.close()
1366 self.assertEqual(code, 235)
1367
1368
Guido van Rossumd8faa362007-04-27 19:54:29 +00001369if __name__ == '__main__':
chason48ed88a2018-07-26 04:01:28 +09001370 unittest.main()