blob: 483d747ee6a49557d1623b12013a9838217b50a1 [file] [log] [blame]
R David Murrayb0deeb42015-11-08 01:03:52 -05001import base64
R. David Murray7dff9e02010-11-08 17:15:13 +00002import email.mime.text
R David Murray83084442015-05-17 19:27:22 -04003from email.message import EmailMessage
Barry Warsawc5ea7542015-07-09 10:39:55 -04004from email.base64mime import body_encode as encode_base64
Guido van Rossum04110fb2007-08-24 16:32:05 +00005import email.utils
Christian Heimesc64a1a62019-09-25 16:30:20 +02006import hashlib
R David Murrayb0deeb42015-11-08 01:03:52 -05007import hmac
Guido van Rossumd8faa362007-04-27 19:54:29 +00008import socket
Guido van Rossumd8faa362007-04-27 19:54:29 +00009import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +000010import io
R. David Murray7dff9e02010-11-08 17:15:13 +000011import re
Guido van Rossum806c2462007-08-06 23:33:07 +000012import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000013import time
Guido van Rossum806c2462007-08-06 23:33:07 +000014import select
Ross Lagerwall86407432012-03-29 18:08:48 +020015import errno
R David Murray83084442015-05-17 19:27:22 -040016import textwrap
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020017import threading
Guido van Rossumd8faa362007-04-27 19:54:29 +000018
Victor Stinner45df8202010-04-28 22:31:17 +000019import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000020from test import support, mock_socket
Hai Shi66abe982020-04-29 09:11:29 +080021from test.support import hashlib_helper
Serhiy Storchaka16994912020-04-25 10:06:29 +030022from test.support import socket_helper
Hai Shie80697d2020-05-28 06:10:27 +080023from test.support import threading_helper
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +020024from unittest.mock import Mock
Guido van Rossumd8faa362007-04-27 19:54:29 +000025
Miss Islington (bot)8bec9fb2021-06-24 16:38:01 -070026import warnings
27with warnings.catch_warnings():
28 warnings.simplefilter('ignore', DeprecationWarning)
29 import asyncore
30 import smtpd
31
Serhiy Storchaka16994912020-04-25 10:06:29 +030032HOST = socket_helper.HOST
Victor Stinner45df8202010-04-28 22:31:17 +000033
Josiah Carlsond74900e2008-07-07 04:15:08 +000034if sys.platform == 'darwin':
35 # select.poll returns a select.POLLHUP at the end of the tests
36 # on darwin, so just ignore it
37 def handle_expt(self):
38 pass
39 smtpd.SMTPChannel.handle_expt = handle_expt
40
41
Christian Heimes5e696852008-04-09 08:37:03 +000042def server(evt, buf, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +010043 serv.listen()
Christian Heimes380f7f22008-02-28 11:19:05 +000044 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000045 try:
46 conn, addr = serv.accept()
Christian Heimes03c8ddd2020-11-20 09:26:07 +010047 except TimeoutError:
Guido van Rossumd8faa362007-04-27 19:54:29 +000048 pass
49 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000050 n = 500
51 while buf and n > 0:
52 r, w, e = select.select([], [conn], [])
53 if w:
54 sent = conn.send(buf)
55 buf = buf[sent:]
56
57 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000058
Guido van Rossumd8faa362007-04-27 19:54:29 +000059 conn.close()
60 finally:
61 serv.close()
62 evt.set()
63
Dong-hee Na65a5ce22020-01-15 06:42:09 +090064class GeneralTests:
Guido van Rossumd8faa362007-04-27 19:54:29 +000065
66 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000067 smtplib.socket = mock_socket
68 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000069
70 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000071 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000072
R. David Murray7dff9e02010-11-08 17:15:13 +000073 # This method is no longer used but is retained for backward compatibility,
74 # so test to make sure it still works.
75 def testQuoteData(self):
76 teststr = "abc\n.jkl\rfoo\r\n..blue"
77 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
78 self.assertEqual(expected, smtplib.quotedata(teststr))
79
Guido van Rossum806c2462007-08-06 23:33:07 +000080 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000081 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000082 # connects
Dong-hee Na65a5ce22020-01-15 06:42:09 +090083 client = self.client(HOST, self.port)
84 client.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000085
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080086 def testSourceAddress(self):
87 mock_socket.reply_with(b"220 Hola mundo")
88 # connects
Dong-hee Na65a5ce22020-01-15 06:42:09 +090089 client = self.client(HOST, self.port,
90 source_address=('127.0.0.1',19876))
91 self.assertEqual(client.source_address, ('127.0.0.1', 19876))
92 client.close()
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080093
Guido van Rossum806c2462007-08-06 23:33:07 +000094 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000095 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000096 # connects, include port in host name
Dong-hee Na65a5ce22020-01-15 06:42:09 +090097 client = self.client("%s:%s" % (HOST, self.port))
98 client.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000099
100 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000101 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +0000102 # check that supplied local_hostname is used
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900103 client = self.client(HOST, self.port, local_hostname="testhost")
104 self.assertEqual(client.local_hostname, "testhost")
105 client.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000106
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000108 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200109 self.assertIsNone(mock_socket.getdefaulttimeout())
Richard Jones64b02de2010-08-03 06:39:33 +0000110 mock_socket.setdefaulttimeout(30)
111 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000112 try:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900113 client = self.client(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000114 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000115 mock_socket.setdefaulttimeout(None)
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900116 self.assertEqual(client.sock.gettimeout(), 30)
117 client.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118
119 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000120 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200121 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000122 socket.setdefaulttimeout(30)
123 try:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900124 client = self.client(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000125 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000126 socket.setdefaulttimeout(None)
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900127 self.assertIsNone(client.sock.gettimeout())
128 client.close()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000129
Dong-hee Na62e39732020-01-14 16:49:59 +0900130 def testTimeoutZero(self):
131 mock_socket.reply_with(b"220 Hola mundo")
132 with self.assertRaises(ValueError):
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900133 self.client(HOST, self.port, timeout=0)
Dong-hee Na62e39732020-01-14 16:49:59 +0900134
Georg Brandlf78e02b2008-06-10 17:40:04 +0000135 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000136 mock_socket.reply_with(b"220 Hola mundo")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900137 client = self.client(HOST, self.port, timeout=30)
138 self.assertEqual(client.sock.gettimeout(), 30)
139 client.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140
R David Murray0c49b892015-04-16 17:14:42 -0400141 def test_debuglevel(self):
142 mock_socket.reply_with(b"220 Hello world")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900143 client = self.client()
144 client.set_debuglevel(1)
R David Murray0c49b892015-04-16 17:14:42 -0400145 with support.captured_stderr() as stderr:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900146 client.connect(HOST, self.port)
147 client.close()
R David Murray0c49b892015-04-16 17:14:42 -0400148 expected = re.compile(r"^connect:", re.MULTILINE)
149 self.assertRegex(stderr.getvalue(), expected)
150
151 def test_debuglevel_2(self):
152 mock_socket.reply_with(b"220 Hello world")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900153 client = self.client()
154 client.set_debuglevel(2)
R David Murray0c49b892015-04-16 17:14:42 -0400155 with support.captured_stderr() as stderr:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900156 client.connect(HOST, self.port)
157 client.close()
R David Murray0c49b892015-04-16 17:14:42 -0400158 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
159 re.MULTILINE)
160 self.assertRegex(stderr.getvalue(), expected)
161
Guido van Rossumd8faa362007-04-27 19:54:29 +0000162
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900163class SMTPGeneralTests(GeneralTests, unittest.TestCase):
164
165 client = smtplib.SMTP
166
167
168class LMTPGeneralTests(GeneralTests, unittest.TestCase):
169
170 client = smtplib.LMTP
171
Ross3bf05322021-01-01 17:20:25 +0000172 @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), "test requires Unix domain socket")
173 def testUnixDomainSocketTimeoutDefault(self):
174 local_host = '/some/local/lmtp/delivery/program'
175 mock_socket.reply_with(b"220 Hello world")
176 try:
177 client = self.client(local_host, self.port)
178 finally:
179 mock_socket.setdefaulttimeout(None)
180 self.assertIsNone(client.sock.gettimeout())
181 client.close()
182
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900183 def testTimeoutZero(self):
184 super().testTimeoutZero()
185 local_host = '/some/local/lmtp/delivery/program'
186 with self.assertRaises(ValueError):
187 self.client(local_host, timeout=0)
188
Guido van Rossum04110fb2007-08-24 16:32:05 +0000189# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000190def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000191 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000192
193 try:
194 if hasattr(select, 'poll'):
195 poll_fun = asyncore.poll2
196 else:
197 poll_fun = asyncore.poll
198
199 n = 1000
200 while asyncore.socket_map and n > 0:
201 poll_fun(0.01, asyncore.socket_map)
202
203 # when the client conversation is finished, it will
204 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000205 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000206 serv.close()
207 break
208
209 n -= 1
210
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100211 except TimeoutError:
Guido van Rossum806c2462007-08-06 23:33:07 +0000212 pass
213 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000214 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000215 # allow some time for the client to read the result
216 time.sleep(0.5)
217 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000218 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000219 serv_evt.set()
220
221MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
222MSG_END = '------------ END MESSAGE ------------\n'
223
Guido van Rossum04110fb2007-08-24 16:32:05 +0000224# NOTE: Some SMTP objects in the tests below are created with a non-default
225# local_hostname argument to the constructor, since (on some systems) the FQDN
226# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000227# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000228
229# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000230class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000231
R. David Murray7dff9e02010-11-08 17:15:13 +0000232 maxDiff = None
233
Guido van Rossum806c2462007-08-06 23:33:07 +0000234 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +0800235 self.thread_key = threading_helper.threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000236 self.real_getfqdn = socket.getfqdn
237 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000238 # temporarily replace sys.stdout to capture DebuggingServer output
239 self.old_stdout = sys.stdout
240 self.output = io.StringIO()
241 sys.stdout = self.output
242
243 self.serv_evt = threading.Event()
244 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000245 # Capture SMTPChannel debug output
246 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
247 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000248 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400249 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
250 decode_data=True)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700251 # Keep a note of what server host and port were assigned
252 self.host, self.port = self.serv.socket.getsockname()[:2]
Christian Heimes5e696852008-04-09 08:37:03 +0000253 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000254 self.thread = threading.Thread(target=debugging_server, args=serv_args)
255 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000256
257 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000258 self.serv_evt.wait()
259 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000260
261 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000262 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000263 # indicate that the client is finished
264 self.client_evt.set()
265 # wait for the server thread to terminate
266 self.serv_evt.wait()
Hai Shie80697d2020-05-28 06:10:27 +0800267 threading_helper.join_thread(self.thread)
Guido van Rossum806c2462007-08-06 23:33:07 +0000268 # restore sys.stdout
269 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000270 # restore DEBUGSTREAM
271 smtpd.DEBUGSTREAM.close()
272 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100273 del self.thread
274 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +0800275 threading_helper.threading_cleanup(*self.thread_key)
Guido van Rossum806c2462007-08-06 23:33:07 +0000276
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700277 def get_output_without_xpeer(self):
278 test_output = self.output.getvalue()
279 return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2',
280 test_output, flags=re.MULTILINE|re.DOTALL)
281
Guido van Rossum806c2462007-08-06 23:33:07 +0000282 def testBasic(self):
283 # connect
Victor Stinner07871b22019-12-10 20:32:59 +0100284 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
285 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum806c2462007-08-06 23:33:07 +0000286 smtp.quit()
287
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800288 def testSourceAddress(self):
289 # connect
Serhiy Storchaka16994912020-04-25 10:06:29 +0300290 src_port = socket_helper.find_unused_port()
Senthil Kumaranb351a482011-07-31 09:14:17 +0800291 try:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700292 smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost',
Victor Stinner07871b22019-12-10 20:32:59 +0100293 timeout=support.LOOPBACK_TIMEOUT,
294 source_address=(self.host, src_port))
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100295 self.addCleanup(smtp.close)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700296 self.assertEqual(smtp.source_address, (self.host, src_port))
Senthil Kumaranb351a482011-07-31 09:14:17 +0800297 self.assertEqual(smtp.local_hostname, 'localhost')
298 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200299 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800300 if e.errno == errno.EADDRINUSE:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700301 self.skipTest("couldn't bind to source port %d" % src_port)
Senthil Kumaranb351a482011-07-31 09:14:17 +0800302 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800303
Guido van Rossum04110fb2007-08-24 16:32:05 +0000304 def testNOOP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100305 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
306 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100307 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400308 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000309 self.assertEqual(smtp.noop(), expected)
310 smtp.quit()
311
312 def testRSET(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100313 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
314 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100315 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400316 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000317 self.assertEqual(smtp.rset(), expected)
318 smtp.quit()
319
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400320 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000321 # EHLO isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100322 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
323 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100324 self.addCleanup(smtp.close)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400325 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000326 self.assertEqual(smtp.ehlo(), expected)
327 smtp.quit()
328
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400329 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400330 # EXPN isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100331 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
332 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100333 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400334 expected = (502, b'EXPN not implemented')
335 smtp.putcmd('EXPN')
336 self.assertEqual(smtp.getreply(), expected)
337 smtp.quit()
338
339 def testVRFY(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100340 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
341 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100342 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400343 expected = (252, b'Cannot VRFY user, but will accept message ' + \
344 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000345 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
346 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
347 smtp.quit()
348
349 def testSecondHELO(self):
350 # check that a second HELO returns a message that it's a duplicate
351 # (this behavior is specific to smtpd.SMTPChannel)
Victor Stinner07871b22019-12-10 20:32:59 +0100352 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
353 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100354 self.addCleanup(smtp.close)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000355 smtp.helo()
356 expected = (503, b'Duplicate HELO/EHLO')
357 self.assertEqual(smtp.helo(), expected)
358 smtp.quit()
359
Guido van Rossum806c2462007-08-06 23:33:07 +0000360 def testHELP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100361 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
362 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100363 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400364 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
365 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000366 smtp.quit()
367
368 def testSend(self):
369 # connect and send mail
370 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100371 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
372 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100373 self.addCleanup(smtp.close)
Guido van Rossum806c2462007-08-06 23:33:07 +0000374 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000375 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
376 # in asyncore. This sleep might help, but should really be fixed
377 # properly by using an Event variable.
378 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000379 smtp.quit()
380
381 self.client_evt.set()
382 self.serv_evt.wait()
383 self.output.flush()
384 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
385 self.assertEqual(self.output.getvalue(), mexpect)
386
R. David Murray7dff9e02010-11-08 17:15:13 +0000387 def testSendBinary(self):
388 m = b'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100389 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
390 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100391 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000392 smtp.sendmail('John', 'Sally', m)
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()
400 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
401 self.assertEqual(self.output.getvalue(), mexpect)
402
R David Murray0f663d02011-06-09 15:05:57 -0400403 def testSendNeedingDotQuote(self):
404 # Issue 12283
405 m = '.A test\n.mes.sage.'
Victor Stinner07871b22019-12-10 20:32:59 +0100406 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
407 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100408 self.addCleanup(smtp.close)
R David Murray0f663d02011-06-09 15:05:57 -0400409 smtp.sendmail('John', 'Sally', m)
410 # XXX (see comment in testSend)
411 time.sleep(0.01)
412 smtp.quit()
413
414 self.client_evt.set()
415 self.serv_evt.wait()
416 self.output.flush()
417 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
418 self.assertEqual(self.output.getvalue(), mexpect)
419
R David Murray46346762011-07-18 21:38:54 -0400420 def testSendNullSender(self):
421 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100422 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
423 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100424 self.addCleanup(smtp.close)
R David Murray46346762011-07-18 21:38:54 -0400425 smtp.sendmail('<>', 'Sally', m)
426 # XXX (see comment in testSend)
427 time.sleep(0.01)
428 smtp.quit()
429
430 self.client_evt.set()
431 self.serv_evt.wait()
432 self.output.flush()
433 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
434 self.assertEqual(self.output.getvalue(), mexpect)
435 debugout = smtpd.DEBUGSTREAM.getvalue()
436 sender = re.compile("^sender: <>$", re.MULTILINE)
437 self.assertRegex(debugout, sender)
438
R. David Murray7dff9e02010-11-08 17:15:13 +0000439 def testSendMessage(self):
440 m = email.mime.text.MIMEText('A test message')
Victor Stinner07871b22019-12-10 20:32:59 +0100441 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
442 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100443 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000444 smtp.send_message(m, from_addr='John', to_addrs='Sally')
445 # XXX (see comment in testSend)
446 time.sleep(0.01)
447 smtp.quit()
448
449 self.client_evt.set()
450 self.serv_evt.wait()
451 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700452 # Remove the X-Peer header that DebuggingServer adds as figuring out
453 # exactly what IP address format is put there is not easy (and
454 # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is
455 # not always the same as socket.gethostbyname(HOST). :(
456 test_output = self.get_output_without_xpeer()
457 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000458 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700459 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000460
461 def testSendMessageWithAddresses(self):
462 m = email.mime.text.MIMEText('A test message')
463 m['From'] = 'foo@bar.com'
464 m['To'] = 'John'
465 m['CC'] = 'Sally, Fred'
466 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
Victor Stinner07871b22019-12-10 20:32:59 +0100467 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
468 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100469 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000470 smtp.send_message(m)
471 # XXX (see comment in testSend)
472 time.sleep(0.01)
473 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400474 # make sure the Bcc header is still in the message.
475 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
476 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000477
478 self.client_evt.set()
479 self.serv_evt.wait()
480 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700481 # Remove the X-Peer header that DebuggingServer adds.
482 test_output = self.get_output_without_xpeer()
483 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400484 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000485 del m['Bcc']
486 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700487 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000488 debugout = smtpd.DEBUGSTREAM.getvalue()
489 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000490 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000491 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
492 'warped@silly.walks.com'):
493 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
494 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000495 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000496
497 def testSendMessageWithSomeAddresses(self):
498 # Make sure nothing breaks if not all of the three 'to' headers exist
499 m = email.mime.text.MIMEText('A test message')
500 m['From'] = 'foo@bar.com'
501 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100502 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
503 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100504 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000505 smtp.send_message(m)
506 # XXX (see comment in testSend)
507 time.sleep(0.01)
508 smtp.quit()
509
510 self.client_evt.set()
511 self.serv_evt.wait()
512 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700513 # Remove the X-Peer header that DebuggingServer adds.
514 test_output = self.get_output_without_xpeer()
515 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000516 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700517 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000518 debugout = smtpd.DEBUGSTREAM.getvalue()
519 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000520 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000521 for addr in ('John', 'Dinsdale'):
522 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
523 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000524 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000525
R David Murrayac4e5ab2011-07-02 21:03:19 -0400526 def testSendMessageWithSpecifiedAddresses(self):
527 # Make sure addresses specified in call override those in message.
528 m = email.mime.text.MIMEText('A test message')
529 m['From'] = 'foo@bar.com'
530 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100531 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
532 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100533 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400534 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
535 # XXX (see comment in testSend)
536 time.sleep(0.01)
537 smtp.quit()
538
539 self.client_evt.set()
540 self.serv_evt.wait()
541 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700542 # Remove the X-Peer header that DebuggingServer adds.
543 test_output = self.get_output_without_xpeer()
544 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400545 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700546 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400547 debugout = smtpd.DEBUGSTREAM.getvalue()
548 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
549 self.assertRegex(debugout, sender)
550 for addr in ('John', 'Dinsdale'):
551 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
552 re.MULTILINE)
553 self.assertNotRegex(debugout, to_addr)
554 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
555 self.assertRegex(debugout, recip)
556
557 def testSendMessageWithMultipleFrom(self):
558 # Sender overrides To
559 m = email.mime.text.MIMEText('A test message')
560 m['From'] = 'Bernard, Bianca'
561 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
562 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100563 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
564 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100565 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400566 smtp.send_message(m)
567 # XXX (see comment in testSend)
568 time.sleep(0.01)
569 smtp.quit()
570
571 self.client_evt.set()
572 self.serv_evt.wait()
573 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700574 # Remove the X-Peer header that DebuggingServer adds.
575 test_output = self.get_output_without_xpeer()
576 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400577 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700578 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400579 debugout = smtpd.DEBUGSTREAM.getvalue()
580 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
581 self.assertRegex(debugout, sender)
582 for addr in ('John', 'Dinsdale'):
583 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
584 re.MULTILINE)
585 self.assertRegex(debugout, to_addr)
586
587 def testSendMessageResent(self):
588 m = email.mime.text.MIMEText('A test message')
589 m['From'] = 'foo@bar.com'
590 m['To'] = 'John'
591 m['CC'] = 'Sally, Fred'
592 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
593 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
594 m['Resent-From'] = 'holy@grail.net'
595 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
596 m['Resent-Bcc'] = 'doe@losthope.net'
Victor Stinner07871b22019-12-10 20:32:59 +0100597 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
598 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100599 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400600 smtp.send_message(m)
601 # XXX (see comment in testSend)
602 time.sleep(0.01)
603 smtp.quit()
604
605 self.client_evt.set()
606 self.serv_evt.wait()
607 self.output.flush()
608 # The Resent-Bcc headers are deleted before serialization.
609 del m['Bcc']
610 del m['Resent-Bcc']
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700611 # Remove the X-Peer header that DebuggingServer adds.
612 test_output = self.get_output_without_xpeer()
613 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400614 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700615 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400616 debugout = smtpd.DEBUGSTREAM.getvalue()
617 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
618 self.assertRegex(debugout, sender)
619 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
620 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
621 re.MULTILINE)
622 self.assertRegex(debugout, to_addr)
623
624 def testSendMessageMultipleResentRaises(self):
625 m = email.mime.text.MIMEText('A test message')
626 m['From'] = 'foo@bar.com'
627 m['To'] = 'John'
628 m['CC'] = 'Sally, Fred'
629 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
630 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
631 m['Resent-From'] = 'holy@grail.net'
632 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
633 m['Resent-Bcc'] = 'doe@losthope.net'
634 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
635 m['Resent-To'] = 'holy@grail.net'
636 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
Victor Stinner07871b22019-12-10 20:32:59 +0100637 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
638 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100639 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400640 with self.assertRaises(ValueError):
641 smtp.send_message(m)
642 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000643
Victor Stinner45df8202010-04-28 22:31:17 +0000644class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000645
646 def testNotConnected(self):
647 # Test various operations on an unconnected SMTP object that
648 # should raise exceptions (at present the attempt in SMTP.send
649 # to reference the nonexistent 'sock' attribute of the SMTP object
650 # causes an AttributeError)
651 smtp = smtplib.SMTP()
652 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
653 self.assertRaises(smtplib.SMTPServerDisconnected,
654 smtp.send, 'test msg')
655
656 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200657 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200658 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000659 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200660 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000661 "localhost:bogus")
662
Romuald Brunet7b313972018-10-09 16:31:55 +0200663 def testSockAttributeExists(self):
664 # check that sock attribute is present outside of a connect() call
665 # (regression test, the previous behavior raised an
666 # AttributeError: 'SMTP' object has no attribute 'sock')
667 with smtplib.SMTP() as smtp:
668 self.assertIsNone(smtp.sock)
669
Christian Heimes380f7f22008-02-28 11:19:05 +0000670
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200671class DefaultArgumentsTests(unittest.TestCase):
672
673 def setUp(self):
674 self.msg = EmailMessage()
675 self.msg['From'] = 'Páolo <főo@bar.com>'
676 self.smtp = smtplib.SMTP()
677 self.smtp.ehlo = Mock(return_value=(200, 'OK'))
678 self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
679
680 def testSendMessage(self):
681 expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
682 self.smtp.send_message(self.msg)
683 self.smtp.send_message(self.msg)
684 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
685 expected_mail_options)
686 self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
687 expected_mail_options)
688
689 def testSendMessageWithMailOptions(self):
690 mail_options = ['STARTTLS']
691 expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
692 self.smtp.send_message(self.msg, None, None, mail_options)
693 self.assertEqual(mail_options, ['STARTTLS'])
694 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
695 expected_mail_options)
696
697
Guido van Rossum04110fb2007-08-24 16:32:05 +0000698# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000699class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000700
701 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000702 smtplib.socket = mock_socket
703 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000704 self.old_stdout = sys.stdout
705 self.output = io.StringIO()
706 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000707 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000708
709 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000710 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000711 sys.stdout = self.old_stdout
712
713 def testFailingHELO(self):
714 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000715 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000716
Guido van Rossum04110fb2007-08-24 16:32:05 +0000717
Georg Brandlb38b5c42014-02-10 22:11:21 +0100718class TooLongLineTests(unittest.TestCase):
719 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
720
721 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +0800722 self.thread_key = threading_helper.threading_setup()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100723 self.old_stdout = sys.stdout
724 self.output = io.StringIO()
725 sys.stdout = self.output
726
727 self.evt = threading.Event()
728 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
729 self.sock.settimeout(15)
Serhiy Storchaka16994912020-04-25 10:06:29 +0300730 self.port = socket_helper.bind_port(self.sock)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100731 servargs = (self.evt, self.respdata, self.sock)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100732 self.thread = threading.Thread(target=server, args=servargs)
733 self.thread.start()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100734 self.evt.wait()
735 self.evt.clear()
736
737 def tearDown(self):
738 self.evt.wait()
739 sys.stdout = self.old_stdout
Hai Shie80697d2020-05-28 06:10:27 +0800740 threading_helper.join_thread(self.thread)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100741 del self.thread
742 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +0800743 threading_helper.threading_cleanup(*self.thread_key)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100744
745 def testLineTooLong(self):
746 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
747 HOST, self.port, 'localhost', 3)
748
749
Guido van Rossum04110fb2007-08-24 16:32:05 +0000750sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400751 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000752 'Mrs.C@somewhereesle.com':'Ruth C',
753 }
754
R. David Murraycaa27b72009-05-23 18:49:56 +0000755sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000756sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
757 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000758sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400759 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000760 }
761
762# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500763class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000764class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000765
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400766 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400767 mail_response = None
768 rcpt_response = None
769 data_response = None
770 rcpt_count = 0
771 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400772 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500773 AUTH = 99 # Add protocol state to enable auth testing.
774 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400775
R. David Murray23ddc0e2009-05-29 18:03:16 +0000776 def __init__(self, extra_features, *args, **kw):
777 self._extrafeatures = ''.join(
778 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000779 super(SimSMTPChannel, self).__init__(*args, **kw)
780
R David Murrayb0deeb42015-11-08 01:03:52 -0500781 # AUTH related stuff. It would be nice if support for this were in smtpd.
782 def found_terminator(self):
783 if self.smtp_state == self.AUTH:
784 line = self._emptystring.join(self.received_lines)
785 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
786 self.received_lines = []
787 try:
788 self.auth_object(line)
789 except ResponseException as e:
790 self.smtp_state = self.COMMAND
791 self.push('%s %s' % (e.smtp_code, e.smtp_error))
Pandu E POLUAN7591d942021-03-13 06:25:49 +0700792 return
R David Murrayb0deeb42015-11-08 01:03:52 -0500793 super().found_terminator()
794
795
796 def smtp_AUTH(self, arg):
797 if not self.seen_greeting:
798 self.push('503 Error: send EHLO first')
799 return
800 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
801 self.push('500 Error: command "AUTH" not recognized')
802 return
803 if self.authenticated_user is not None:
804 self.push(
805 '503 Bad sequence of commands: already authenticated')
806 return
807 args = arg.split()
808 if len(args) not in [1, 2]:
809 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
810 return
811 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
812 try:
813 self.auth_object = getattr(self, auth_object_name)
814 except AttributeError:
815 self.push('504 Command parameter not implemented: unsupported '
816 ' authentication mechanism {!r}'.format(auth_object_name))
817 return
818 self.smtp_state = self.AUTH
819 self.auth_object(args[1] if len(args) == 2 else None)
820
821 def _authenticated(self, user, valid):
822 if valid:
823 self.authenticated_user = user
824 self.push('235 Authentication Succeeded')
825 else:
826 self.push('535 Authentication credentials invalid')
827 self.smtp_state = self.COMMAND
828
829 def _decode_base64(self, string):
830 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
831
832 def _auth_plain(self, arg=None):
833 if arg is None:
834 self.push('334 ')
835 else:
836 logpass = self._decode_base64(arg)
837 try:
838 *_, user, password = logpass.split('\0')
839 except ValueError as e:
840 self.push('535 Splitting response {!r} into user and password'
841 ' failed: {}'.format(logpass, e))
842 return
843 self._authenticated(user, password == sim_auth[1])
844
845 def _auth_login(self, arg=None):
846 if arg is None:
847 # base64 encoded 'Username:'
848 self.push('334 VXNlcm5hbWU6')
849 elif not hasattr(self, '_auth_login_user'):
850 self._auth_login_user = self._decode_base64(arg)
851 # base64 encoded 'Password:'
852 self.push('334 UGFzc3dvcmQ6')
853 else:
854 password = self._decode_base64(arg)
855 self._authenticated(self._auth_login_user, password == sim_auth[1])
856 del self._auth_login_user
857
Pandu E POLUAN7591d942021-03-13 06:25:49 +0700858 def _auth_buggy(self, arg=None):
859 # This AUTH mechanism will 'trap' client in a neverending 334
860 # base64 encoded 'BuGgYbUgGy'
861 self.push('334 QnVHZ1liVWdHeQ==')
862
R David Murrayb0deeb42015-11-08 01:03:52 -0500863 def _auth_cram_md5(self, arg=None):
864 if arg is None:
865 self.push('334 {}'.format(sim_cram_md5_challenge))
866 else:
867 logpass = self._decode_base64(arg)
868 try:
869 user, hashed_pass = logpass.split()
870 except ValueError as e:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200871 self.push('535 Splitting response {!r} into user and password '
R David Murrayb0deeb42015-11-08 01:03:52 -0500872 'failed: {}'.format(logpass, e))
873 return False
874 valid_hashed_pass = hmac.HMAC(
875 sim_auth[1].encode('ascii'),
876 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
877 'md5').hexdigest()
878 self._authenticated(user, hashed_pass == valid_hashed_pass)
879 # end AUTH related stuff.
880
Guido van Rossum04110fb2007-08-24 16:32:05 +0000881 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000882 resp = ('250-testhost\r\n'
883 '250-EXPN\r\n'
884 '250-SIZE 20000000\r\n'
885 '250-STARTTLS\r\n'
886 '250-DELIVERBY\r\n')
887 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000888 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400889 self.seen_greeting = arg
890 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000891
892 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400893 # For max compatibility smtplib should be sending the raw address.
894 if arg in sim_users:
895 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000896 else:
897 self.push('550 No such user: %s' % arg)
898
899 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400900 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000901 if list_name in sim_lists:
902 user_list = sim_lists[list_name]
903 for n, user_email in enumerate(user_list):
904 quoted_addr = smtplib.quoteaddr(user_email)
905 if n < len(user_list) - 1:
906 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
907 else:
908 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
909 else:
910 self.push('550 No access for you!')
911
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400912 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400913 if self.quit_response is None:
914 super(SimSMTPChannel, self).smtp_QUIT(arg)
915 else:
916 self.push(self.quit_response)
917 self.close_when_done()
918
R David Murrayd312c742013-03-20 20:36:14 -0400919 def smtp_MAIL(self, arg):
920 if self.mail_response is None:
921 super().smtp_MAIL(arg)
922 else:
923 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400924 if self.disconnect:
925 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400926
927 def smtp_RCPT(self, arg):
928 if self.rcpt_response is None:
929 super().smtp_RCPT(arg)
930 return
R David Murrayd312c742013-03-20 20:36:14 -0400931 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400932 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400933
934 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400935 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400936 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400937
938 def smtp_DATA(self, arg):
939 if self.data_response is None:
940 super().smtp_DATA(arg)
941 else:
942 self.push(self.data_response)
943
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000944 def handle_error(self):
945 raise
946
Guido van Rossum04110fb2007-08-24 16:32:05 +0000947
948class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000949
R David Murrayd312c742013-03-20 20:36:14 -0400950 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400951
R. David Murray23ddc0e2009-05-29 18:03:16 +0000952 def __init__(self, *args, **kw):
953 self._extra_features = []
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100954 self._addresses = {}
R. David Murray23ddc0e2009-05-29 18:03:16 +0000955 smtpd.SMTPServer.__init__(self, *args, **kw)
956
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000957 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400958 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400959 self._extra_features, self, conn, addr,
960 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000961
962 def process_message(self, peer, mailfrom, rcpttos, data):
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100963 self._addresses['from'] = mailfrom
964 self._addresses['tos'] = rcpttos
Guido van Rossum04110fb2007-08-24 16:32:05 +0000965
R. David Murrayfb123912009-05-28 18:19:00 +0000966 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000967 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000968
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000969 def handle_error(self):
970 raise
971
Guido van Rossum04110fb2007-08-24 16:32:05 +0000972
973# Test various SMTP & ESMTP commands/behaviors that require a simulated server
974# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000975class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000976
977 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +0800978 self.thread_key = threading_helper.threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000979 self.real_getfqdn = socket.getfqdn
980 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000981 self.serv_evt = threading.Event()
982 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000983 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400984 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000985 # Keep a note of what port was assigned
986 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000987 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000988 self.thread = threading.Thread(target=debugging_server, args=serv_args)
989 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000990
991 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000992 self.serv_evt.wait()
993 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000994
995 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000996 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000997 # indicate that the client is finished
998 self.client_evt.set()
999 # wait for the server thread to terminate
1000 self.serv_evt.wait()
Hai Shie80697d2020-05-28 06:10:27 +08001001 threading_helper.join_thread(self.thread)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001002 del self.thread
1003 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +08001004 threading_helper.threading_cleanup(*self.thread_key)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001005
1006 def testBasic(self):
1007 # smoke test
Victor Stinner7772b1a2019-12-11 22:17:04 +01001008 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1009 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001010 smtp.quit()
1011
1012 def testEHLO(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001013 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1014 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001015
1016 # no features should be present before the EHLO
1017 self.assertEqual(smtp.esmtp_features, {})
1018
1019 # features expected from the test server
1020 expected_features = {'expn':'',
1021 'size': '20000000',
1022 'starttls': '',
1023 'deliverby': '',
1024 'help': '',
1025 }
1026
1027 smtp.ehlo()
1028 self.assertEqual(smtp.esmtp_features, expected_features)
1029 for k in expected_features:
1030 self.assertTrue(smtp.has_extn(k))
1031 self.assertFalse(smtp.has_extn('unsupported-feature'))
1032 smtp.quit()
1033
1034 def testVRFY(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001035 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1036 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001037
Barry Warsawc5ea7542015-07-09 10:39:55 -04001038 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +00001039 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -04001040 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001041 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -04001042 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001043
1044 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -04001045 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001046 self.assertEqual(smtp.vrfy(u), expected_unknown)
1047 smtp.quit()
1048
1049 def testEXPN(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001050 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1051 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001052
1053 for listname, members in sim_lists.items():
1054 users = []
1055 for m in members:
1056 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001057 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001058 self.assertEqual(smtp.expn(listname), expected_known)
1059
1060 u = 'PSU-Members-List'
1061 expected_unknown = (550, b'No access for you!')
1062 self.assertEqual(smtp.expn(u), expected_unknown)
1063 smtp.quit()
1064
R David Murray76e13c12014-07-03 14:47:46 -04001065 def testAUTH_PLAIN(self):
1066 self.serv.add_feature("AUTH PLAIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001067 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1068 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001069 resp = smtp.login(sim_auth[0], sim_auth[1])
1070 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001071 smtp.close()
1072
R. David Murrayfb123912009-05-28 18:19:00 +00001073 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001074 self.serv.add_feature("AUTH LOGIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001075 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1076 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001077 resp = smtp.login(sim_auth[0], sim_auth[1])
1078 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001079 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001080
Pandu E POLUAN7591d942021-03-13 06:25:49 +07001081 def testAUTH_LOGIN_initial_response_ok(self):
1082 self.serv.add_feature("AUTH LOGIN")
1083 with smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1084 timeout=support.LOOPBACK_TIMEOUT) as smtp:
1085 smtp.user, smtp.password = sim_auth
1086 smtp.ehlo("test_auth_login")
1087 resp = smtp.auth("LOGIN", smtp.auth_login, initial_response_ok=True)
1088 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1089
1090 def testAUTH_LOGIN_initial_response_notok(self):
1091 self.serv.add_feature("AUTH LOGIN")
1092 with smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1093 timeout=support.LOOPBACK_TIMEOUT) as smtp:
1094 smtp.user, smtp.password = sim_auth
1095 smtp.ehlo("test_auth_login")
1096 resp = smtp.auth("LOGIN", smtp.auth_login, initial_response_ok=False)
1097 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1098
1099 def testAUTH_BUGGY(self):
1100 self.serv.add_feature("AUTH BUGGY")
1101
1102 def auth_buggy(challenge=None):
1103 self.assertEqual(b"BuGgYbUgGy", challenge)
1104 return "\0"
1105
1106 smtp = smtplib.SMTP(
1107 HOST, self.port, local_hostname='localhost',
1108 timeout=support.LOOPBACK_TIMEOUT
1109 )
1110 try:
1111 smtp.user, smtp.password = sim_auth
1112 smtp.ehlo("test_auth_buggy")
1113 expect = r"^Server AUTH mechanism infinite loop.*"
1114 with self.assertRaisesRegex(smtplib.SMTPException, expect) as cm:
1115 smtp.auth("BUGGY", auth_buggy, initial_response_ok=False)
1116 finally:
1117 smtp.close()
1118
Hai Shi66abe982020-04-29 09:11:29 +08001119 @hashlib_helper.requires_hashdigest('md5')
R. David Murrayfb123912009-05-28 18:19:00 +00001120 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001121 self.serv.add_feature("AUTH CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001122 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1123 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001124 resp = smtp.login(sim_auth[0], sim_auth[1])
1125 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001126 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001127
Christian Heimes909b5712020-05-22 20:04:33 +02001128 @hashlib_helper.requires_hashdigest('md5')
Andrew Kuchling78591822013-11-11 14:03:23 -05001129 def testAUTH_multiple(self):
1130 # Test that multiple authentication methods are tried.
1131 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001132 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1133 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001134 resp = smtp.login(sim_auth[0], sim_auth[1])
1135 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001136 smtp.close()
1137
1138 def test_auth_function(self):
Christian Heimesc64a1a62019-09-25 16:30:20 +02001139 supported = {'PLAIN', 'LOGIN'}
1140 try:
1141 hashlib.md5()
1142 except ValueError:
1143 pass
1144 else:
1145 supported.add('CRAM-MD5')
R David Murrayb0deeb42015-11-08 01:03:52 -05001146 for mechanism in supported:
1147 self.serv.add_feature("AUTH {}".format(mechanism))
1148 for mechanism in supported:
1149 with self.subTest(mechanism=mechanism):
1150 smtp = smtplib.SMTP(HOST, self.port,
Victor Stinner7772b1a2019-12-11 22:17:04 +01001151 local_hostname='localhost',
1152 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001153 smtp.ehlo('foo')
1154 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
1155 method = 'auth_' + mechanism.lower().replace('-', '_')
1156 resp = smtp.auth(mechanism, getattr(smtp, method))
1157 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1158 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -05001159
R David Murray0cff49f2014-08-30 16:51:59 -04001160 def test_quit_resets_greeting(self):
1161 smtp = smtplib.SMTP(HOST, self.port,
1162 local_hostname='localhost',
Victor Stinner7772b1a2019-12-11 22:17:04 +01001163 timeout=support.LOOPBACK_TIMEOUT)
R David Murray0cff49f2014-08-30 16:51:59 -04001164 code, message = smtp.ehlo()
1165 self.assertEqual(code, 250)
1166 self.assertIn('size', smtp.esmtp_features)
1167 smtp.quit()
1168 self.assertNotIn('size', smtp.esmtp_features)
1169 smtp.connect(HOST, self.port)
1170 self.assertNotIn('size', smtp.esmtp_features)
1171 smtp.ehlo_or_helo_if_needed()
1172 self.assertIn('size', smtp.esmtp_features)
1173 smtp.quit()
1174
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001175 def test_with_statement(self):
1176 with smtplib.SMTP(HOST, self.port) as smtp:
1177 code, message = smtp.noop()
1178 self.assertEqual(code, 250)
1179 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1180 with smtplib.SMTP(HOST, self.port) as smtp:
1181 smtp.close()
1182 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1183
1184 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001185 with self.assertRaises(smtplib.SMTPResponseException) as error:
1186 with smtplib.SMTP(HOST, self.port) as smtp:
1187 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001188 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001189 self.assertEqual(error.exception.smtp_code, 421)
1190 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001191
R. David Murrayfb123912009-05-28 18:19:00 +00001192 #TODO: add tests for correct AUTH method fallback now that the
1193 #test infrastructure can support it.
1194
R David Murrayafb151a2014-04-14 18:21:38 -04001195 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1196 def test__rest_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001197 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1198 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayafb151a2014-04-14 18:21:38 -04001199 smtp.noop()
1200 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1201 self.serv._SMTPchannel.disconnect = True
1202 with self.assertRaises(smtplib.SMTPSenderRefused):
1203 smtp.sendmail('John', 'Sally', 'test message')
1204 self.assertIsNone(smtp.sock)
1205
R David Murrayd312c742013-03-20 20:36:14 -04001206 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1207 def test_421_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001208 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1209 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001210 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001211 self.serv._SMTPchannel.mail_response = '421 closing connection'
1212 with self.assertRaises(smtplib.SMTPSenderRefused):
1213 smtp.sendmail('John', 'Sally', 'test message')
1214 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001215 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001216
1217 def test_421_from_rcpt_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001218 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1219 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001220 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001221 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1222 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1223 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1224 self.assertIsNone(smtp.sock)
1225 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1226 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1227
1228 def test_421_from_data_cmd(self):
1229 class MySimSMTPChannel(SimSMTPChannel):
1230 def found_terminator(self):
1231 if self.smtp_state == self.DATA:
1232 self.push('421 closing')
1233 else:
1234 super().found_terminator()
1235 self.serv.channel_class = MySimSMTPChannel
Victor Stinner7772b1a2019-12-11 22:17:04 +01001236 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1237 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001238 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001239 with self.assertRaises(smtplib.SMTPDataError):
1240 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1241 self.assertIsNone(smtp.sock)
1242 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1243
R David Murraycee7cf62015-05-16 13:58:14 -04001244 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1245 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001246 HOST, self.port, local_hostname='localhost',
1247 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001248 self.addCleanup(smtp.close)
1249 smtp.ehlo()
1250 self.assertTrue(smtp.does_esmtp)
1251 self.assertFalse(smtp.has_extn('smtputf8'))
1252 self.assertRaises(
1253 smtplib.SMTPNotSupportedError,
1254 smtp.sendmail,
1255 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1256 self.assertRaises(
1257 smtplib.SMTPNotSupportedError,
1258 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1259
1260 def test_send_unicode_without_SMTPUTF8(self):
1261 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001262 HOST, self.port, local_hostname='localhost',
1263 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001264 self.addCleanup(smtp.close)
1265 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1266 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1267
chason48ed88a2018-07-26 04:01:28 +09001268 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1269 # This test is located here and not in the SMTPUTF8SimTests
1270 # class because it needs a "regular" SMTP server to work
1271 msg = EmailMessage()
1272 msg['From'] = "Páolo <főo@bar.com>"
1273 msg['To'] = 'Dinsdale'
1274 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1275 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001276 HOST, self.port, local_hostname='localhost',
1277 timeout=support.LOOPBACK_TIMEOUT)
chason48ed88a2018-07-26 04:01:28 +09001278 self.addCleanup(smtp.close)
1279 with self.assertRaises(smtplib.SMTPNotSupportedError):
1280 smtp.send_message(msg)
1281
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001282 def test_name_field_not_included_in_envelop_addresses(self):
1283 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001284 HOST, self.port, local_hostname='localhost',
1285 timeout=support.LOOPBACK_TIMEOUT)
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001286 self.addCleanup(smtp.close)
1287
1288 message = EmailMessage()
1289 message['From'] = email.utils.formataddr(('Michaël', 'michael@example.com'))
1290 message['To'] = email.utils.formataddr(('René', 'rene@example.com'))
1291
1292 self.assertDictEqual(smtp.send_message(message), {})
1293
1294 self.assertEqual(self.serv._addresses['from'], 'michael@example.com')
1295 self.assertEqual(self.serv._addresses['tos'], ['rene@example.com'])
1296
R David Murraycee7cf62015-05-16 13:58:14 -04001297
1298class SimSMTPUTF8Server(SimSMTPServer):
1299
1300 def __init__(self, *args, **kw):
1301 # The base SMTP server turns these on automatically, but our test
1302 # server is set up to munge the EHLO response, so we need to provide
1303 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1304 self._extra_features = ['SMTPUTF8', '8BITMIME']
1305 smtpd.SMTPServer.__init__(self, *args, **kw)
1306
1307 def handle_accepted(self, conn, addr):
1308 self._SMTPchannel = self.channel_class(
1309 self._extra_features, self, conn, addr,
1310 decode_data=self._decode_data,
1311 enable_SMTPUTF8=self.enable_SMTPUTF8,
1312 )
1313
1314 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1315 rcpt_options=None):
1316 self.last_peer = peer
1317 self.last_mailfrom = mailfrom
1318 self.last_rcpttos = rcpttos
1319 self.last_message = data
1320 self.last_mail_options = mail_options
1321 self.last_rcpt_options = rcpt_options
1322
1323
R David Murraycee7cf62015-05-16 13:58:14 -04001324class SMTPUTF8SimTests(unittest.TestCase):
1325
R David Murray83084442015-05-17 19:27:22 -04001326 maxDiff = None
1327
R David Murraycee7cf62015-05-16 13:58:14 -04001328 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +08001329 self.thread_key = threading_helper.threading_setup()
R David Murraycee7cf62015-05-16 13:58:14 -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 = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1336 decode_data=False,
1337 enable_SMTPUTF8=True)
1338 # Keep a note of what port was assigned
1339 self.port = self.serv.socket.getsockname()[1]
1340 serv_args = (self.serv, self.serv_evt, self.client_evt)
1341 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1342 self.thread.start()
1343
1344 # wait until server thread has assigned a port number
1345 self.serv_evt.wait()
1346 self.serv_evt.clear()
1347
1348 def tearDown(self):
1349 socket.getfqdn = self.real_getfqdn
1350 # indicate that the client is finished
1351 self.client_evt.set()
1352 # wait for the server thread to terminate
1353 self.serv_evt.wait()
Hai Shie80697d2020-05-28 06:10:27 +08001354 threading_helper.join_thread(self.thread)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001355 del self.thread
1356 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +08001357 threading_helper.threading_cleanup(*self.thread_key)
R David Murraycee7cf62015-05-16 13:58:14 -04001358
1359 def test_test_server_supports_extensions(self):
1360 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001361 HOST, self.port, local_hostname='localhost',
1362 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001363 self.addCleanup(smtp.close)
1364 smtp.ehlo()
1365 self.assertTrue(smtp.does_esmtp)
1366 self.assertTrue(smtp.has_extn('smtputf8'))
1367
1368 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1369 m = '¡a test message containing unicode!'.encode('utf-8')
1370 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001371 HOST, self.port, local_hostname='localhost',
1372 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001373 self.addCleanup(smtp.close)
1374 smtp.sendmail('Jőhn', 'Sálly', m,
1375 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1376 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1377 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1378 self.assertEqual(self.serv.last_message, m)
1379 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1380 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1381 self.assertEqual(self.serv.last_rcpt_options, [])
1382
1383 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1384 m = '¡a test message containing unicode!'.encode('utf-8')
1385 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001386 HOST, self.port, local_hostname='localhost',
1387 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001388 self.addCleanup(smtp.close)
1389 smtp.ehlo()
1390 self.assertEqual(
1391 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1392 (250, b'OK'))
1393 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1394 self.assertEqual(smtp.data(m), (250, b'OK'))
1395 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1396 self.assertEqual(self.serv.last_rcpttos, ['János'])
1397 self.assertEqual(self.serv.last_message, m)
1398 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1399 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1400 self.assertEqual(self.serv.last_rcpt_options, [])
1401
R David Murray83084442015-05-17 19:27:22 -04001402 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1403 msg = EmailMessage()
1404 msg['From'] = "Páolo <főo@bar.com>"
1405 msg['To'] = 'Dinsdale'
1406 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1407 # XXX I don't know why I need two \n's here, but this is an existing
1408 # bug (if it is one) and not a problem with the new functionality.
1409 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1410 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1411 # we are successfully sending /r/n :(.
1412 expected = textwrap.dedent("""\
1413 From: Páolo <főo@bar.com>
1414 To: Dinsdale
1415 Subject: Nudge nudge, wink, wink \u1F609
1416 Content-Type: text/plain; charset="utf-8"
1417 Content-Transfer-Encoding: 8bit
1418 MIME-Version: 1.0
1419
1420 oh là là, know what I mean, know what I mean?
1421 """)
1422 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001423 HOST, self.port, local_hostname='localhost',
1424 timeout=support.LOOPBACK_TIMEOUT)
R David Murray83084442015-05-17 19:27:22 -04001425 self.addCleanup(smtp.close)
1426 self.assertEqual(smtp.send_message(msg), {})
1427 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1428 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1429 self.assertEqual(self.serv.last_message.decode(), expected)
1430 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1431 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1432 self.assertEqual(self.serv.last_rcpt_options, [])
1433
Guido van Rossum04110fb2007-08-24 16:32:05 +00001434
Barry Warsawc5ea7542015-07-09 10:39:55 -04001435EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1436
1437class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1438 def smtp_AUTH(self, arg):
1439 # RFC 4954's AUTH command allows for an optional initial-response.
1440 # Not all AUTH methods support this; some require a challenge. AUTH
1441 # PLAIN does those, so test that here. See issue #15014.
1442 args = arg.split()
1443 if args[0].lower() == 'plain':
1444 if len(args) == 2:
1445 # AUTH PLAIN <initial-response> with the response base 64
1446 # encoded. Hard code the expected response for the test.
1447 if args[1] == EXPECTED_RESPONSE:
1448 self.push('235 Ok')
1449 return
1450 self.push('571 Bad authentication')
1451
1452class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1453 channel_class = SimSMTPAUTHInitialResponseChannel
1454
1455
Barry Warsawc5ea7542015-07-09 10:39:55 -04001456class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1457 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +08001458 self.thread_key = threading_helper.threading_setup()
Barry Warsawc5ea7542015-07-09 10:39:55 -04001459 self.real_getfqdn = socket.getfqdn
1460 socket.getfqdn = mock_socket.getfqdn
1461 self.serv_evt = threading.Event()
1462 self.client_evt = threading.Event()
1463 # Pick a random unused port by passing 0 for the port number
1464 self.serv = SimSMTPAUTHInitialResponseServer(
1465 (HOST, 0), ('nowhere', -1), decode_data=True)
1466 # Keep a note of what port was assigned
1467 self.port = self.serv.socket.getsockname()[1]
1468 serv_args = (self.serv, self.serv_evt, self.client_evt)
1469 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1470 self.thread.start()
1471
1472 # wait until server thread has assigned a port number
1473 self.serv_evt.wait()
1474 self.serv_evt.clear()
1475
1476 def tearDown(self):
1477 socket.getfqdn = self.real_getfqdn
1478 # indicate that the client is finished
1479 self.client_evt.set()
1480 # wait for the server thread to terminate
1481 self.serv_evt.wait()
Hai Shie80697d2020-05-28 06:10:27 +08001482 threading_helper.join_thread(self.thread)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001483 del self.thread
1484 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +08001485 threading_helper.threading_cleanup(*self.thread_key)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001486
1487 def testAUTH_PLAIN_initial_response_login(self):
1488 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001489 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1490 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001491 smtp.login('psu', 'doesnotexist')
1492 smtp.close()
1493
1494 def testAUTH_PLAIN_initial_response_auth(self):
1495 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001496 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1497 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001498 smtp.user = 'psu'
1499 smtp.password = 'doesnotexist'
1500 code, response = smtp.auth('plain', smtp.auth_plain)
1501 smtp.close()
1502 self.assertEqual(code, 235)
1503
1504
Guido van Rossumd8faa362007-04-27 19:54:29 +00001505if __name__ == '__main__':
chason48ed88a2018-07-26 04:01:28 +09001506 unittest.main()