blob: f3d33ab0772dd3a215d8b8e2fad75c8d47c91405 [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
Christian Heimesc64a1a62019-09-25 16:30:20 +02007import hashlib
R David Murrayb0deeb42015-11-08 01:03:52 -05008import hmac
Guido van Rossumd8faa362007-04-27 19:54:29 +00009import socket
Guido van Rossum806c2462007-08-06 23:33:07 +000010import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +000011import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +000012import io
R. David Murray7dff9e02010-11-08 17:15:13 +000013import re
Guido van Rossum806c2462007-08-06 23:33:07 +000014import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000015import time
Guido van Rossum806c2462007-08-06 23:33:07 +000016import select
Ross Lagerwall86407432012-03-29 18:08:48 +020017import errno
R David Murray83084442015-05-17 19:27:22 -040018import textwrap
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020019import threading
Guido van Rossumd8faa362007-04-27 19:54:29 +000020
Victor Stinner45df8202010-04-28 22:31:17 +000021import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000022from test import support, mock_socket
Hai Shi66abe982020-04-29 09:11:29 +080023from test.support import hashlib_helper
Serhiy Storchaka16994912020-04-25 10:06:29 +030024from test.support import socket_helper
Hai Shie80697d2020-05-28 06:10:27 +080025from test.support import threading_helper
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +020026from unittest.mock import Mock
Guido van Rossumd8faa362007-04-27 19:54:29 +000027
Serhiy Storchaka16994912020-04-25 10:06:29 +030028HOST = socket_helper.HOST
Victor Stinner45df8202010-04-28 22:31:17 +000029
Josiah Carlsond74900e2008-07-07 04:15:08 +000030if sys.platform == 'darwin':
31 # select.poll returns a select.POLLHUP at the end of the tests
32 # on darwin, so just ignore it
33 def handle_expt(self):
34 pass
35 smtpd.SMTPChannel.handle_expt = handle_expt
36
37
Christian Heimes5e696852008-04-09 08:37:03 +000038def server(evt, buf, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +010039 serv.listen()
Christian Heimes380f7f22008-02-28 11:19:05 +000040 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000041 try:
42 conn, addr = serv.accept()
Christian Heimes03c8ddd2020-11-20 09:26:07 +010043 except TimeoutError:
Guido van Rossumd8faa362007-04-27 19:54:29 +000044 pass
45 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000046 n = 500
47 while buf and n > 0:
48 r, w, e = select.select([], [conn], [])
49 if w:
50 sent = conn.send(buf)
51 buf = buf[sent:]
52
53 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000054
Guido van Rossumd8faa362007-04-27 19:54:29 +000055 conn.close()
56 finally:
57 serv.close()
58 evt.set()
59
Dong-hee Na65a5ce22020-01-15 06:42:09 +090060class GeneralTests:
Guido van Rossumd8faa362007-04-27 19:54:29 +000061
62 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000063 smtplib.socket = mock_socket
64 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000065
66 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000067 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000068
R. David Murray7dff9e02010-11-08 17:15:13 +000069 # This method is no longer used but is retained for backward compatibility,
70 # so test to make sure it still works.
71 def testQuoteData(self):
72 teststr = "abc\n.jkl\rfoo\r\n..blue"
73 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
74 self.assertEqual(expected, smtplib.quotedata(teststr))
75
Guido van Rossum806c2462007-08-06 23:33:07 +000076 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000077 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000078 # connects
Dong-hee Na65a5ce22020-01-15 06:42:09 +090079 client = self.client(HOST, self.port)
80 client.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000081
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080082 def testSourceAddress(self):
83 mock_socket.reply_with(b"220 Hola mundo")
84 # connects
Dong-hee Na65a5ce22020-01-15 06:42:09 +090085 client = self.client(HOST, self.port,
86 source_address=('127.0.0.1',19876))
87 self.assertEqual(client.source_address, ('127.0.0.1', 19876))
88 client.close()
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080089
Guido van Rossum806c2462007-08-06 23:33:07 +000090 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000091 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000092 # connects, include port in host name
Dong-hee Na65a5ce22020-01-15 06:42:09 +090093 client = self.client("%s:%s" % (HOST, self.port))
94 client.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000095
96 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000097 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000098 # check that supplied local_hostname is used
Dong-hee Na65a5ce22020-01-15 06:42:09 +090099 client = self.client(HOST, self.port, local_hostname="testhost")
100 self.assertEqual(client.local_hostname, "testhost")
101 client.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000102
Guido van Rossumd8faa362007-04-27 19:54:29 +0000103 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000104 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200105 self.assertIsNone(mock_socket.getdefaulttimeout())
Richard Jones64b02de2010-08-03 06:39:33 +0000106 mock_socket.setdefaulttimeout(30)
107 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000108 try:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900109 client = self.client(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000110 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000111 mock_socket.setdefaulttimeout(None)
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900112 self.assertEqual(client.sock.gettimeout(), 30)
113 client.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114
115 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000116 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200117 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118 socket.setdefaulttimeout(30)
119 try:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900120 client = self.client(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000121 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000122 socket.setdefaulttimeout(None)
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900123 self.assertIsNone(client.sock.gettimeout())
124 client.close()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000125
Dong-hee Na62e39732020-01-14 16:49:59 +0900126 def testTimeoutZero(self):
127 mock_socket.reply_with(b"220 Hola mundo")
128 with self.assertRaises(ValueError):
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900129 self.client(HOST, self.port, timeout=0)
Dong-hee Na62e39732020-01-14 16:49:59 +0900130
Georg Brandlf78e02b2008-06-10 17:40:04 +0000131 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000132 mock_socket.reply_with(b"220 Hola mundo")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900133 client = self.client(HOST, self.port, timeout=30)
134 self.assertEqual(client.sock.gettimeout(), 30)
135 client.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136
R David Murray0c49b892015-04-16 17:14:42 -0400137 def test_debuglevel(self):
138 mock_socket.reply_with(b"220 Hello world")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900139 client = self.client()
140 client.set_debuglevel(1)
R David Murray0c49b892015-04-16 17:14:42 -0400141 with support.captured_stderr() as stderr:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900142 client.connect(HOST, self.port)
143 client.close()
R David Murray0c49b892015-04-16 17:14:42 -0400144 expected = re.compile(r"^connect:", re.MULTILINE)
145 self.assertRegex(stderr.getvalue(), expected)
146
147 def test_debuglevel_2(self):
148 mock_socket.reply_with(b"220 Hello world")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900149 client = self.client()
150 client.set_debuglevel(2)
R David Murray0c49b892015-04-16 17:14:42 -0400151 with support.captured_stderr() as stderr:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900152 client.connect(HOST, self.port)
153 client.close()
R David Murray0c49b892015-04-16 17:14:42 -0400154 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
155 re.MULTILINE)
156 self.assertRegex(stderr.getvalue(), expected)
157
Guido van Rossumd8faa362007-04-27 19:54:29 +0000158
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900159class SMTPGeneralTests(GeneralTests, unittest.TestCase):
160
161 client = smtplib.SMTP
162
163
164class LMTPGeneralTests(GeneralTests, unittest.TestCase):
165
166 client = smtplib.LMTP
167
Ross3bf05322021-01-01 17:20:25 +0000168 @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), "test requires Unix domain socket")
169 def testUnixDomainSocketTimeoutDefault(self):
170 local_host = '/some/local/lmtp/delivery/program'
171 mock_socket.reply_with(b"220 Hello world")
172 try:
173 client = self.client(local_host, self.port)
174 finally:
175 mock_socket.setdefaulttimeout(None)
176 self.assertIsNone(client.sock.gettimeout())
177 client.close()
178
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900179 def testTimeoutZero(self):
180 super().testTimeoutZero()
181 local_host = '/some/local/lmtp/delivery/program'
182 with self.assertRaises(ValueError):
183 self.client(local_host, timeout=0)
184
Guido van Rossum04110fb2007-08-24 16:32:05 +0000185# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000186def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000187 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000188
189 try:
190 if hasattr(select, 'poll'):
191 poll_fun = asyncore.poll2
192 else:
193 poll_fun = asyncore.poll
194
195 n = 1000
196 while asyncore.socket_map and n > 0:
197 poll_fun(0.01, asyncore.socket_map)
198
199 # when the client conversation is finished, it will
200 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000201 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000202 serv.close()
203 break
204
205 n -= 1
206
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100207 except TimeoutError:
Guido van Rossum806c2462007-08-06 23:33:07 +0000208 pass
209 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000210 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000211 # allow some time for the client to read the result
212 time.sleep(0.5)
213 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000214 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000215 serv_evt.set()
216
217MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
218MSG_END = '------------ END MESSAGE ------------\n'
219
Guido van Rossum04110fb2007-08-24 16:32:05 +0000220# NOTE: Some SMTP objects in the tests below are created with a non-default
221# local_hostname argument to the constructor, since (on some systems) the FQDN
222# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000223# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000224
225# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000226class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000227
R. David Murray7dff9e02010-11-08 17:15:13 +0000228 maxDiff = None
229
Guido van Rossum806c2462007-08-06 23:33:07 +0000230 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +0800231 self.thread_key = threading_helper.threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000232 self.real_getfqdn = socket.getfqdn
233 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000234 # temporarily replace sys.stdout to capture DebuggingServer output
235 self.old_stdout = sys.stdout
236 self.output = io.StringIO()
237 sys.stdout = self.output
238
239 self.serv_evt = threading.Event()
240 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000241 # Capture SMTPChannel debug output
242 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
243 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000244 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400245 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
246 decode_data=True)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700247 # Keep a note of what server host and port were assigned
248 self.host, self.port = self.serv.socket.getsockname()[:2]
Christian Heimes5e696852008-04-09 08:37:03 +0000249 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000250 self.thread = threading.Thread(target=debugging_server, args=serv_args)
251 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000252
253 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000254 self.serv_evt.wait()
255 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000256
257 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000258 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000259 # indicate that the client is finished
260 self.client_evt.set()
261 # wait for the server thread to terminate
262 self.serv_evt.wait()
Hai Shie80697d2020-05-28 06:10:27 +0800263 threading_helper.join_thread(self.thread)
Guido van Rossum806c2462007-08-06 23:33:07 +0000264 # restore sys.stdout
265 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000266 # restore DEBUGSTREAM
267 smtpd.DEBUGSTREAM.close()
268 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100269 del self.thread
270 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +0800271 threading_helper.threading_cleanup(*self.thread_key)
Guido van Rossum806c2462007-08-06 23:33:07 +0000272
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700273 def get_output_without_xpeer(self):
274 test_output = self.output.getvalue()
275 return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2',
276 test_output, flags=re.MULTILINE|re.DOTALL)
277
Guido van Rossum806c2462007-08-06 23:33:07 +0000278 def testBasic(self):
279 # connect
Victor Stinner07871b22019-12-10 20:32:59 +0100280 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
281 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum806c2462007-08-06 23:33:07 +0000282 smtp.quit()
283
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800284 def testSourceAddress(self):
285 # connect
Serhiy Storchaka16994912020-04-25 10:06:29 +0300286 src_port = socket_helper.find_unused_port()
Senthil Kumaranb351a482011-07-31 09:14:17 +0800287 try:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700288 smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost',
Victor Stinner07871b22019-12-10 20:32:59 +0100289 timeout=support.LOOPBACK_TIMEOUT,
290 source_address=(self.host, src_port))
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100291 self.addCleanup(smtp.close)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700292 self.assertEqual(smtp.source_address, (self.host, src_port))
Senthil Kumaranb351a482011-07-31 09:14:17 +0800293 self.assertEqual(smtp.local_hostname, 'localhost')
294 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200295 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800296 if e.errno == errno.EADDRINUSE:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700297 self.skipTest("couldn't bind to source port %d" % src_port)
Senthil Kumaranb351a482011-07-31 09:14:17 +0800298 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800299
Guido van Rossum04110fb2007-08-24 16:32:05 +0000300 def testNOOP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100301 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
302 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100303 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400304 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000305 self.assertEqual(smtp.noop(), expected)
306 smtp.quit()
307
308 def testRSET(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100309 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
310 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100311 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400312 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000313 self.assertEqual(smtp.rset(), expected)
314 smtp.quit()
315
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400316 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000317 # EHLO isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100318 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
319 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100320 self.addCleanup(smtp.close)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400321 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000322 self.assertEqual(smtp.ehlo(), expected)
323 smtp.quit()
324
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400325 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400326 # EXPN isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100327 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
328 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100329 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400330 expected = (502, b'EXPN not implemented')
331 smtp.putcmd('EXPN')
332 self.assertEqual(smtp.getreply(), expected)
333 smtp.quit()
334
335 def testVRFY(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100336 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
337 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100338 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400339 expected = (252, b'Cannot VRFY user, but will accept message ' + \
340 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000341 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
342 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
343 smtp.quit()
344
345 def testSecondHELO(self):
346 # check that a second HELO returns a message that it's a duplicate
347 # (this behavior is specific to smtpd.SMTPChannel)
Victor Stinner07871b22019-12-10 20:32:59 +0100348 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
349 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100350 self.addCleanup(smtp.close)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000351 smtp.helo()
352 expected = (503, b'Duplicate HELO/EHLO')
353 self.assertEqual(smtp.helo(), expected)
354 smtp.quit()
355
Guido van Rossum806c2462007-08-06 23:33:07 +0000356 def testHELP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100357 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
358 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100359 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400360 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
361 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000362 smtp.quit()
363
364 def testSend(self):
365 # connect and send mail
366 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100367 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
368 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100369 self.addCleanup(smtp.close)
Guido van Rossum806c2462007-08-06 23:33:07 +0000370 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000371 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
372 # in asyncore. This sleep might help, but should really be fixed
373 # properly by using an Event variable.
374 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000375 smtp.quit()
376
377 self.client_evt.set()
378 self.serv_evt.wait()
379 self.output.flush()
380 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
381 self.assertEqual(self.output.getvalue(), mexpect)
382
R. David Murray7dff9e02010-11-08 17:15:13 +0000383 def testSendBinary(self):
384 m = b'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100385 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
386 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100387 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000388 smtp.sendmail('John', 'Sally', m)
389 # XXX (see comment in testSend)
390 time.sleep(0.01)
391 smtp.quit()
392
393 self.client_evt.set()
394 self.serv_evt.wait()
395 self.output.flush()
396 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
397 self.assertEqual(self.output.getvalue(), mexpect)
398
R David Murray0f663d02011-06-09 15:05:57 -0400399 def testSendNeedingDotQuote(self):
400 # Issue 12283
401 m = '.A test\n.mes.sage.'
Victor Stinner07871b22019-12-10 20:32:59 +0100402 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
403 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100404 self.addCleanup(smtp.close)
R David Murray0f663d02011-06-09 15:05:57 -0400405 smtp.sendmail('John', 'Sally', m)
406 # XXX (see comment in testSend)
407 time.sleep(0.01)
408 smtp.quit()
409
410 self.client_evt.set()
411 self.serv_evt.wait()
412 self.output.flush()
413 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
414 self.assertEqual(self.output.getvalue(), mexpect)
415
R David Murray46346762011-07-18 21:38:54 -0400416 def testSendNullSender(self):
417 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100418 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
419 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100420 self.addCleanup(smtp.close)
R David Murray46346762011-07-18 21:38:54 -0400421 smtp.sendmail('<>', 'Sally', m)
422 # XXX (see comment in testSend)
423 time.sleep(0.01)
424 smtp.quit()
425
426 self.client_evt.set()
427 self.serv_evt.wait()
428 self.output.flush()
429 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
430 self.assertEqual(self.output.getvalue(), mexpect)
431 debugout = smtpd.DEBUGSTREAM.getvalue()
432 sender = re.compile("^sender: <>$", re.MULTILINE)
433 self.assertRegex(debugout, sender)
434
R. David Murray7dff9e02010-11-08 17:15:13 +0000435 def testSendMessage(self):
436 m = email.mime.text.MIMEText('A test message')
Victor Stinner07871b22019-12-10 20:32:59 +0100437 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
438 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100439 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000440 smtp.send_message(m, from_addr='John', to_addrs='Sally')
441 # XXX (see comment in testSend)
442 time.sleep(0.01)
443 smtp.quit()
444
445 self.client_evt.set()
446 self.serv_evt.wait()
447 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700448 # Remove the X-Peer header that DebuggingServer adds as figuring out
449 # exactly what IP address format is put there is not easy (and
450 # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is
451 # not always the same as socket.gethostbyname(HOST). :(
452 test_output = self.get_output_without_xpeer()
453 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000454 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700455 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000456
457 def testSendMessageWithAddresses(self):
458 m = email.mime.text.MIMEText('A test message')
459 m['From'] = 'foo@bar.com'
460 m['To'] = 'John'
461 m['CC'] = 'Sally, Fred'
462 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
Victor Stinner07871b22019-12-10 20:32:59 +0100463 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
464 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100465 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000466 smtp.send_message(m)
467 # XXX (see comment in testSend)
468 time.sleep(0.01)
469 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400470 # make sure the Bcc header is still in the message.
471 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
472 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000473
474 self.client_evt.set()
475 self.serv_evt.wait()
476 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700477 # Remove the X-Peer header that DebuggingServer adds.
478 test_output = self.get_output_without_xpeer()
479 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400480 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000481 del m['Bcc']
482 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700483 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000484 debugout = smtpd.DEBUGSTREAM.getvalue()
485 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000486 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000487 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
488 'warped@silly.walks.com'):
489 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
490 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000491 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000492
493 def testSendMessageWithSomeAddresses(self):
494 # Make sure nothing breaks if not all of the three 'to' headers exist
495 m = email.mime.text.MIMEText('A test message')
496 m['From'] = 'foo@bar.com'
497 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100498 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
499 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100500 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000501 smtp.send_message(m)
502 # XXX (see comment in testSend)
503 time.sleep(0.01)
504 smtp.quit()
505
506 self.client_evt.set()
507 self.serv_evt.wait()
508 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700509 # Remove the X-Peer header that DebuggingServer adds.
510 test_output = self.get_output_without_xpeer()
511 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000512 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700513 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000514 debugout = smtpd.DEBUGSTREAM.getvalue()
515 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000516 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000517 for addr in ('John', 'Dinsdale'):
518 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
519 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000520 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000521
R David Murrayac4e5ab2011-07-02 21:03:19 -0400522 def testSendMessageWithSpecifiedAddresses(self):
523 # Make sure addresses specified in call override those in message.
524 m = email.mime.text.MIMEText('A test message')
525 m['From'] = 'foo@bar.com'
526 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100527 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
528 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100529 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400530 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
531 # XXX (see comment in testSend)
532 time.sleep(0.01)
533 smtp.quit()
534
535 self.client_evt.set()
536 self.serv_evt.wait()
537 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700538 # Remove the X-Peer header that DebuggingServer adds.
539 test_output = self.get_output_without_xpeer()
540 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400541 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700542 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400543 debugout = smtpd.DEBUGSTREAM.getvalue()
544 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
545 self.assertRegex(debugout, sender)
546 for addr in ('John', 'Dinsdale'):
547 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
548 re.MULTILINE)
549 self.assertNotRegex(debugout, to_addr)
550 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
551 self.assertRegex(debugout, recip)
552
553 def testSendMessageWithMultipleFrom(self):
554 # Sender overrides To
555 m = email.mime.text.MIMEText('A test message')
556 m['From'] = 'Bernard, Bianca'
557 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
558 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100559 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
560 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100561 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400562 smtp.send_message(m)
563 # XXX (see comment in testSend)
564 time.sleep(0.01)
565 smtp.quit()
566
567 self.client_evt.set()
568 self.serv_evt.wait()
569 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700570 # Remove the X-Peer header that DebuggingServer adds.
571 test_output = self.get_output_without_xpeer()
572 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400573 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700574 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400575 debugout = smtpd.DEBUGSTREAM.getvalue()
576 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
577 self.assertRegex(debugout, sender)
578 for addr in ('John', 'Dinsdale'):
579 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
580 re.MULTILINE)
581 self.assertRegex(debugout, to_addr)
582
583 def testSendMessageResent(self):
584 m = email.mime.text.MIMEText('A test message')
585 m['From'] = 'foo@bar.com'
586 m['To'] = 'John'
587 m['CC'] = 'Sally, Fred'
588 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
589 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
590 m['Resent-From'] = 'holy@grail.net'
591 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
592 m['Resent-Bcc'] = 'doe@losthope.net'
Victor Stinner07871b22019-12-10 20:32:59 +0100593 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
594 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100595 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400596 smtp.send_message(m)
597 # XXX (see comment in testSend)
598 time.sleep(0.01)
599 smtp.quit()
600
601 self.client_evt.set()
602 self.serv_evt.wait()
603 self.output.flush()
604 # The Resent-Bcc headers are deleted before serialization.
605 del m['Bcc']
606 del m['Resent-Bcc']
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700607 # Remove the X-Peer header that DebuggingServer adds.
608 test_output = self.get_output_without_xpeer()
609 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400610 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700611 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400612 debugout = smtpd.DEBUGSTREAM.getvalue()
613 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
614 self.assertRegex(debugout, sender)
615 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
616 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
617 re.MULTILINE)
618 self.assertRegex(debugout, to_addr)
619
620 def testSendMessageMultipleResentRaises(self):
621 m = email.mime.text.MIMEText('A test message')
622 m['From'] = 'foo@bar.com'
623 m['To'] = 'John'
624 m['CC'] = 'Sally, Fred'
625 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
626 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
627 m['Resent-From'] = 'holy@grail.net'
628 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
629 m['Resent-Bcc'] = 'doe@losthope.net'
630 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
631 m['Resent-To'] = 'holy@grail.net'
632 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
Victor Stinner07871b22019-12-10 20:32:59 +0100633 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
634 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100635 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400636 with self.assertRaises(ValueError):
637 smtp.send_message(m)
638 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000639
Victor Stinner45df8202010-04-28 22:31:17 +0000640class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000641
642 def testNotConnected(self):
643 # Test various operations on an unconnected SMTP object that
644 # should raise exceptions (at present the attempt in SMTP.send
645 # to reference the nonexistent 'sock' attribute of the SMTP object
646 # causes an AttributeError)
647 smtp = smtplib.SMTP()
648 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
649 self.assertRaises(smtplib.SMTPServerDisconnected,
650 smtp.send, 'test msg')
651
652 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200653 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200654 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000655 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200656 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000657 "localhost:bogus")
658
Romuald Brunet7b313972018-10-09 16:31:55 +0200659 def testSockAttributeExists(self):
660 # check that sock attribute is present outside of a connect() call
661 # (regression test, the previous behavior raised an
662 # AttributeError: 'SMTP' object has no attribute 'sock')
663 with smtplib.SMTP() as smtp:
664 self.assertIsNone(smtp.sock)
665
Christian Heimes380f7f22008-02-28 11:19:05 +0000666
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200667class DefaultArgumentsTests(unittest.TestCase):
668
669 def setUp(self):
670 self.msg = EmailMessage()
671 self.msg['From'] = 'Páolo <főo@bar.com>'
672 self.smtp = smtplib.SMTP()
673 self.smtp.ehlo = Mock(return_value=(200, 'OK'))
674 self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
675
676 def testSendMessage(self):
677 expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
678 self.smtp.send_message(self.msg)
679 self.smtp.send_message(self.msg)
680 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
681 expected_mail_options)
682 self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
683 expected_mail_options)
684
685 def testSendMessageWithMailOptions(self):
686 mail_options = ['STARTTLS']
687 expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
688 self.smtp.send_message(self.msg, None, None, mail_options)
689 self.assertEqual(mail_options, ['STARTTLS'])
690 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
691 expected_mail_options)
692
693
Guido van Rossum04110fb2007-08-24 16:32:05 +0000694# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000695class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000696
697 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000698 smtplib.socket = mock_socket
699 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000700 self.old_stdout = sys.stdout
701 self.output = io.StringIO()
702 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000703 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000704
705 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000706 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000707 sys.stdout = self.old_stdout
708
709 def testFailingHELO(self):
710 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000711 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000712
Guido van Rossum04110fb2007-08-24 16:32:05 +0000713
Georg Brandlb38b5c42014-02-10 22:11:21 +0100714class TooLongLineTests(unittest.TestCase):
715 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
716
717 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +0800718 self.thread_key = threading_helper.threading_setup()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100719 self.old_stdout = sys.stdout
720 self.output = io.StringIO()
721 sys.stdout = self.output
722
723 self.evt = threading.Event()
724 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
725 self.sock.settimeout(15)
Serhiy Storchaka16994912020-04-25 10:06:29 +0300726 self.port = socket_helper.bind_port(self.sock)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100727 servargs = (self.evt, self.respdata, self.sock)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100728 self.thread = threading.Thread(target=server, args=servargs)
729 self.thread.start()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100730 self.evt.wait()
731 self.evt.clear()
732
733 def tearDown(self):
734 self.evt.wait()
735 sys.stdout = self.old_stdout
Hai Shie80697d2020-05-28 06:10:27 +0800736 threading_helper.join_thread(self.thread)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100737 del self.thread
738 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +0800739 threading_helper.threading_cleanup(*self.thread_key)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100740
741 def testLineTooLong(self):
742 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
743 HOST, self.port, 'localhost', 3)
744
745
Guido van Rossum04110fb2007-08-24 16:32:05 +0000746sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400747 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000748 'Mrs.C@somewhereesle.com':'Ruth C',
749 }
750
R. David Murraycaa27b72009-05-23 18:49:56 +0000751sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000752sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
753 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000754sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400755 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000756 }
757
758# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500759class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000760class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000761
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400762 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400763 mail_response = None
764 rcpt_response = None
765 data_response = None
766 rcpt_count = 0
767 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400768 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500769 AUTH = 99 # Add protocol state to enable auth testing.
770 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400771
R. David Murray23ddc0e2009-05-29 18:03:16 +0000772 def __init__(self, extra_features, *args, **kw):
773 self._extrafeatures = ''.join(
774 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000775 super(SimSMTPChannel, self).__init__(*args, **kw)
776
R David Murrayb0deeb42015-11-08 01:03:52 -0500777 # AUTH related stuff. It would be nice if support for this were in smtpd.
778 def found_terminator(self):
779 if self.smtp_state == self.AUTH:
780 line = self._emptystring.join(self.received_lines)
781 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
782 self.received_lines = []
783 try:
784 self.auth_object(line)
785 except ResponseException as e:
786 self.smtp_state = self.COMMAND
787 self.push('%s %s' % (e.smtp_code, e.smtp_error))
Pandu E POLUAN7591d942021-03-13 06:25:49 +0700788 return
R David Murrayb0deeb42015-11-08 01:03:52 -0500789 super().found_terminator()
790
791
792 def smtp_AUTH(self, arg):
793 if not self.seen_greeting:
794 self.push('503 Error: send EHLO first')
795 return
796 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
797 self.push('500 Error: command "AUTH" not recognized')
798 return
799 if self.authenticated_user is not None:
800 self.push(
801 '503 Bad sequence of commands: already authenticated')
802 return
803 args = arg.split()
804 if len(args) not in [1, 2]:
805 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
806 return
807 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
808 try:
809 self.auth_object = getattr(self, auth_object_name)
810 except AttributeError:
811 self.push('504 Command parameter not implemented: unsupported '
812 ' authentication mechanism {!r}'.format(auth_object_name))
813 return
814 self.smtp_state = self.AUTH
815 self.auth_object(args[1] if len(args) == 2 else None)
816
817 def _authenticated(self, user, valid):
818 if valid:
819 self.authenticated_user = user
820 self.push('235 Authentication Succeeded')
821 else:
822 self.push('535 Authentication credentials invalid')
823 self.smtp_state = self.COMMAND
824
825 def _decode_base64(self, string):
826 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
827
828 def _auth_plain(self, arg=None):
829 if arg is None:
830 self.push('334 ')
831 else:
832 logpass = self._decode_base64(arg)
833 try:
834 *_, user, password = logpass.split('\0')
835 except ValueError as e:
836 self.push('535 Splitting response {!r} into user and password'
837 ' failed: {}'.format(logpass, e))
838 return
839 self._authenticated(user, password == sim_auth[1])
840
841 def _auth_login(self, arg=None):
842 if arg is None:
843 # base64 encoded 'Username:'
844 self.push('334 VXNlcm5hbWU6')
845 elif not hasattr(self, '_auth_login_user'):
846 self._auth_login_user = self._decode_base64(arg)
847 # base64 encoded 'Password:'
848 self.push('334 UGFzc3dvcmQ6')
849 else:
850 password = self._decode_base64(arg)
851 self._authenticated(self._auth_login_user, password == sim_auth[1])
852 del self._auth_login_user
853
Pandu E POLUAN7591d942021-03-13 06:25:49 +0700854 def _auth_buggy(self, arg=None):
855 # This AUTH mechanism will 'trap' client in a neverending 334
856 # base64 encoded 'BuGgYbUgGy'
857 self.push('334 QnVHZ1liVWdHeQ==')
858
R David Murrayb0deeb42015-11-08 01:03:52 -0500859 def _auth_cram_md5(self, arg=None):
860 if arg is None:
861 self.push('334 {}'.format(sim_cram_md5_challenge))
862 else:
863 logpass = self._decode_base64(arg)
864 try:
865 user, hashed_pass = logpass.split()
866 except ValueError as e:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200867 self.push('535 Splitting response {!r} into user and password '
R David Murrayb0deeb42015-11-08 01:03:52 -0500868 'failed: {}'.format(logpass, e))
869 return False
870 valid_hashed_pass = hmac.HMAC(
871 sim_auth[1].encode('ascii'),
872 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
873 'md5').hexdigest()
874 self._authenticated(user, hashed_pass == valid_hashed_pass)
875 # end AUTH related stuff.
876
Guido van Rossum04110fb2007-08-24 16:32:05 +0000877 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000878 resp = ('250-testhost\r\n'
879 '250-EXPN\r\n'
880 '250-SIZE 20000000\r\n'
881 '250-STARTTLS\r\n'
882 '250-DELIVERBY\r\n')
883 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000884 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400885 self.seen_greeting = arg
886 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000887
888 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400889 # For max compatibility smtplib should be sending the raw address.
890 if arg in sim_users:
891 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000892 else:
893 self.push('550 No such user: %s' % arg)
894
895 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400896 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000897 if list_name in sim_lists:
898 user_list = sim_lists[list_name]
899 for n, user_email in enumerate(user_list):
900 quoted_addr = smtplib.quoteaddr(user_email)
901 if n < len(user_list) - 1:
902 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
903 else:
904 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
905 else:
906 self.push('550 No access for you!')
907
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400908 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400909 if self.quit_response is None:
910 super(SimSMTPChannel, self).smtp_QUIT(arg)
911 else:
912 self.push(self.quit_response)
913 self.close_when_done()
914
R David Murrayd312c742013-03-20 20:36:14 -0400915 def smtp_MAIL(self, arg):
916 if self.mail_response is None:
917 super().smtp_MAIL(arg)
918 else:
919 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400920 if self.disconnect:
921 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400922
923 def smtp_RCPT(self, arg):
924 if self.rcpt_response is None:
925 super().smtp_RCPT(arg)
926 return
R David Murrayd312c742013-03-20 20:36:14 -0400927 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400928 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400929
930 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400931 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400932 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400933
934 def smtp_DATA(self, arg):
935 if self.data_response is None:
936 super().smtp_DATA(arg)
937 else:
938 self.push(self.data_response)
939
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000940 def handle_error(self):
941 raise
942
Guido van Rossum04110fb2007-08-24 16:32:05 +0000943
944class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000945
R David Murrayd312c742013-03-20 20:36:14 -0400946 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400947
R. David Murray23ddc0e2009-05-29 18:03:16 +0000948 def __init__(self, *args, **kw):
949 self._extra_features = []
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100950 self._addresses = {}
R. David Murray23ddc0e2009-05-29 18:03:16 +0000951 smtpd.SMTPServer.__init__(self, *args, **kw)
952
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000953 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400954 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400955 self._extra_features, self, conn, addr,
956 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000957
958 def process_message(self, peer, mailfrom, rcpttos, data):
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100959 self._addresses['from'] = mailfrom
960 self._addresses['tos'] = rcpttos
Guido van Rossum04110fb2007-08-24 16:32:05 +0000961
R. David Murrayfb123912009-05-28 18:19:00 +0000962 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000963 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000964
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000965 def handle_error(self):
966 raise
967
Guido van Rossum04110fb2007-08-24 16:32:05 +0000968
969# Test various SMTP & ESMTP commands/behaviors that require a simulated server
970# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000971class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000972
973 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +0800974 self.thread_key = threading_helper.threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000975 self.real_getfqdn = socket.getfqdn
976 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000977 self.serv_evt = threading.Event()
978 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000979 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400980 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000981 # Keep a note of what port was assigned
982 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000983 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000984 self.thread = threading.Thread(target=debugging_server, args=serv_args)
985 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000986
987 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000988 self.serv_evt.wait()
989 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000990
991 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000992 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000993 # indicate that the client is finished
994 self.client_evt.set()
995 # wait for the server thread to terminate
996 self.serv_evt.wait()
Hai Shie80697d2020-05-28 06:10:27 +0800997 threading_helper.join_thread(self.thread)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100998 del self.thread
999 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +08001000 threading_helper.threading_cleanup(*self.thread_key)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001001
1002 def testBasic(self):
1003 # smoke test
Victor Stinner7772b1a2019-12-11 22:17:04 +01001004 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1005 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001006 smtp.quit()
1007
1008 def testEHLO(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001009 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1010 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001011
1012 # no features should be present before the EHLO
1013 self.assertEqual(smtp.esmtp_features, {})
1014
1015 # features expected from the test server
1016 expected_features = {'expn':'',
1017 'size': '20000000',
1018 'starttls': '',
1019 'deliverby': '',
1020 'help': '',
1021 }
1022
1023 smtp.ehlo()
1024 self.assertEqual(smtp.esmtp_features, expected_features)
1025 for k in expected_features:
1026 self.assertTrue(smtp.has_extn(k))
1027 self.assertFalse(smtp.has_extn('unsupported-feature'))
1028 smtp.quit()
1029
1030 def testVRFY(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001031 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1032 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001033
Barry Warsawc5ea7542015-07-09 10:39:55 -04001034 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +00001035 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -04001036 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001037 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -04001038 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001039
1040 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -04001041 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001042 self.assertEqual(smtp.vrfy(u), expected_unknown)
1043 smtp.quit()
1044
1045 def testEXPN(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001046 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1047 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001048
1049 for listname, members in sim_lists.items():
1050 users = []
1051 for m in members:
1052 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001053 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001054 self.assertEqual(smtp.expn(listname), expected_known)
1055
1056 u = 'PSU-Members-List'
1057 expected_unknown = (550, b'No access for you!')
1058 self.assertEqual(smtp.expn(u), expected_unknown)
1059 smtp.quit()
1060
R David Murray76e13c12014-07-03 14:47:46 -04001061 def testAUTH_PLAIN(self):
1062 self.serv.add_feature("AUTH PLAIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001063 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1064 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001065 resp = smtp.login(sim_auth[0], sim_auth[1])
1066 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001067 smtp.close()
1068
R. David Murrayfb123912009-05-28 18:19:00 +00001069 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001070 self.serv.add_feature("AUTH LOGIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001071 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1072 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001073 resp = smtp.login(sim_auth[0], sim_auth[1])
1074 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001075 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001076
Pandu E POLUAN7591d942021-03-13 06:25:49 +07001077 def testAUTH_LOGIN_initial_response_ok(self):
1078 self.serv.add_feature("AUTH LOGIN")
1079 with smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1080 timeout=support.LOOPBACK_TIMEOUT) as smtp:
1081 smtp.user, smtp.password = sim_auth
1082 smtp.ehlo("test_auth_login")
1083 resp = smtp.auth("LOGIN", smtp.auth_login, initial_response_ok=True)
1084 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1085
1086 def testAUTH_LOGIN_initial_response_notok(self):
1087 self.serv.add_feature("AUTH LOGIN")
1088 with smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1089 timeout=support.LOOPBACK_TIMEOUT) as smtp:
1090 smtp.user, smtp.password = sim_auth
1091 smtp.ehlo("test_auth_login")
1092 resp = smtp.auth("LOGIN", smtp.auth_login, initial_response_ok=False)
1093 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1094
1095 def testAUTH_BUGGY(self):
1096 self.serv.add_feature("AUTH BUGGY")
1097
1098 def auth_buggy(challenge=None):
1099 self.assertEqual(b"BuGgYbUgGy", challenge)
1100 return "\0"
1101
1102 smtp = smtplib.SMTP(
1103 HOST, self.port, local_hostname='localhost',
1104 timeout=support.LOOPBACK_TIMEOUT
1105 )
1106 try:
1107 smtp.user, smtp.password = sim_auth
1108 smtp.ehlo("test_auth_buggy")
1109 expect = r"^Server AUTH mechanism infinite loop.*"
1110 with self.assertRaisesRegex(smtplib.SMTPException, expect) as cm:
1111 smtp.auth("BUGGY", auth_buggy, initial_response_ok=False)
1112 finally:
1113 smtp.close()
1114
Hai Shi66abe982020-04-29 09:11:29 +08001115 @hashlib_helper.requires_hashdigest('md5')
R. David Murrayfb123912009-05-28 18:19:00 +00001116 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001117 self.serv.add_feature("AUTH CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001118 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1119 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001120 resp = smtp.login(sim_auth[0], sim_auth[1])
1121 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001122 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001123
Christian Heimes909b5712020-05-22 20:04:33 +02001124 @hashlib_helper.requires_hashdigest('md5')
Andrew Kuchling78591822013-11-11 14:03:23 -05001125 def testAUTH_multiple(self):
1126 # Test that multiple authentication methods are tried.
1127 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001128 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1129 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001130 resp = smtp.login(sim_auth[0], sim_auth[1])
1131 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001132 smtp.close()
1133
1134 def test_auth_function(self):
Christian Heimesc64a1a62019-09-25 16:30:20 +02001135 supported = {'PLAIN', 'LOGIN'}
1136 try:
1137 hashlib.md5()
1138 except ValueError:
1139 pass
1140 else:
1141 supported.add('CRAM-MD5')
R David Murrayb0deeb42015-11-08 01:03:52 -05001142 for mechanism in supported:
1143 self.serv.add_feature("AUTH {}".format(mechanism))
1144 for mechanism in supported:
1145 with self.subTest(mechanism=mechanism):
1146 smtp = smtplib.SMTP(HOST, self.port,
Victor Stinner7772b1a2019-12-11 22:17:04 +01001147 local_hostname='localhost',
1148 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001149 smtp.ehlo('foo')
1150 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
1151 method = 'auth_' + mechanism.lower().replace('-', '_')
1152 resp = smtp.auth(mechanism, getattr(smtp, method))
1153 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1154 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -05001155
R David Murray0cff49f2014-08-30 16:51:59 -04001156 def test_quit_resets_greeting(self):
1157 smtp = smtplib.SMTP(HOST, self.port,
1158 local_hostname='localhost',
Victor Stinner7772b1a2019-12-11 22:17:04 +01001159 timeout=support.LOOPBACK_TIMEOUT)
R David Murray0cff49f2014-08-30 16:51:59 -04001160 code, message = smtp.ehlo()
1161 self.assertEqual(code, 250)
1162 self.assertIn('size', smtp.esmtp_features)
1163 smtp.quit()
1164 self.assertNotIn('size', smtp.esmtp_features)
1165 smtp.connect(HOST, self.port)
1166 self.assertNotIn('size', smtp.esmtp_features)
1167 smtp.ehlo_or_helo_if_needed()
1168 self.assertIn('size', smtp.esmtp_features)
1169 smtp.quit()
1170
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001171 def test_with_statement(self):
1172 with smtplib.SMTP(HOST, self.port) as smtp:
1173 code, message = smtp.noop()
1174 self.assertEqual(code, 250)
1175 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1176 with smtplib.SMTP(HOST, self.port) as smtp:
1177 smtp.close()
1178 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1179
1180 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001181 with self.assertRaises(smtplib.SMTPResponseException) as error:
1182 with smtplib.SMTP(HOST, self.port) as smtp:
1183 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001184 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001185 self.assertEqual(error.exception.smtp_code, 421)
1186 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001187
R. David Murrayfb123912009-05-28 18:19:00 +00001188 #TODO: add tests for correct AUTH method fallback now that the
1189 #test infrastructure can support it.
1190
R David Murrayafb151a2014-04-14 18:21:38 -04001191 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1192 def test__rest_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001193 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1194 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayafb151a2014-04-14 18:21:38 -04001195 smtp.noop()
1196 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1197 self.serv._SMTPchannel.disconnect = True
1198 with self.assertRaises(smtplib.SMTPSenderRefused):
1199 smtp.sendmail('John', 'Sally', 'test message')
1200 self.assertIsNone(smtp.sock)
1201
R David Murrayd312c742013-03-20 20:36:14 -04001202 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1203 def test_421_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001204 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1205 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001206 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001207 self.serv._SMTPchannel.mail_response = '421 closing connection'
1208 with self.assertRaises(smtplib.SMTPSenderRefused):
1209 smtp.sendmail('John', 'Sally', 'test message')
1210 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001211 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001212
1213 def test_421_from_rcpt_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001214 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1215 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001216 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001217 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1218 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1219 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1220 self.assertIsNone(smtp.sock)
1221 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1222 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1223
1224 def test_421_from_data_cmd(self):
1225 class MySimSMTPChannel(SimSMTPChannel):
1226 def found_terminator(self):
1227 if self.smtp_state == self.DATA:
1228 self.push('421 closing')
1229 else:
1230 super().found_terminator()
1231 self.serv.channel_class = MySimSMTPChannel
Victor Stinner7772b1a2019-12-11 22:17:04 +01001232 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1233 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001234 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001235 with self.assertRaises(smtplib.SMTPDataError):
1236 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1237 self.assertIsNone(smtp.sock)
1238 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1239
R David Murraycee7cf62015-05-16 13:58:14 -04001240 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1241 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001242 HOST, self.port, local_hostname='localhost',
1243 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001244 self.addCleanup(smtp.close)
1245 smtp.ehlo()
1246 self.assertTrue(smtp.does_esmtp)
1247 self.assertFalse(smtp.has_extn('smtputf8'))
1248 self.assertRaises(
1249 smtplib.SMTPNotSupportedError,
1250 smtp.sendmail,
1251 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1252 self.assertRaises(
1253 smtplib.SMTPNotSupportedError,
1254 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1255
1256 def test_send_unicode_without_SMTPUTF8(self):
1257 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001258 HOST, self.port, local_hostname='localhost',
1259 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001260 self.addCleanup(smtp.close)
1261 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1262 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1263
chason48ed88a2018-07-26 04:01:28 +09001264 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1265 # This test is located here and not in the SMTPUTF8SimTests
1266 # class because it needs a "regular" SMTP server to work
1267 msg = EmailMessage()
1268 msg['From'] = "Páolo <főo@bar.com>"
1269 msg['To'] = 'Dinsdale'
1270 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1271 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001272 HOST, self.port, local_hostname='localhost',
1273 timeout=support.LOOPBACK_TIMEOUT)
chason48ed88a2018-07-26 04:01:28 +09001274 self.addCleanup(smtp.close)
1275 with self.assertRaises(smtplib.SMTPNotSupportedError):
1276 smtp.send_message(msg)
1277
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001278 def test_name_field_not_included_in_envelop_addresses(self):
1279 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001280 HOST, self.port, local_hostname='localhost',
1281 timeout=support.LOOPBACK_TIMEOUT)
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001282 self.addCleanup(smtp.close)
1283
1284 message = EmailMessage()
1285 message['From'] = email.utils.formataddr(('Michaël', 'michael@example.com'))
1286 message['To'] = email.utils.formataddr(('René', 'rene@example.com'))
1287
1288 self.assertDictEqual(smtp.send_message(message), {})
1289
1290 self.assertEqual(self.serv._addresses['from'], 'michael@example.com')
1291 self.assertEqual(self.serv._addresses['tos'], ['rene@example.com'])
1292
R David Murraycee7cf62015-05-16 13:58:14 -04001293
1294class SimSMTPUTF8Server(SimSMTPServer):
1295
1296 def __init__(self, *args, **kw):
1297 # The base SMTP server turns these on automatically, but our test
1298 # server is set up to munge the EHLO response, so we need to provide
1299 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1300 self._extra_features = ['SMTPUTF8', '8BITMIME']
1301 smtpd.SMTPServer.__init__(self, *args, **kw)
1302
1303 def handle_accepted(self, conn, addr):
1304 self._SMTPchannel = self.channel_class(
1305 self._extra_features, self, conn, addr,
1306 decode_data=self._decode_data,
1307 enable_SMTPUTF8=self.enable_SMTPUTF8,
1308 )
1309
1310 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1311 rcpt_options=None):
1312 self.last_peer = peer
1313 self.last_mailfrom = mailfrom
1314 self.last_rcpttos = rcpttos
1315 self.last_message = data
1316 self.last_mail_options = mail_options
1317 self.last_rcpt_options = rcpt_options
1318
1319
R David Murraycee7cf62015-05-16 13:58:14 -04001320class SMTPUTF8SimTests(unittest.TestCase):
1321
R David Murray83084442015-05-17 19:27:22 -04001322 maxDiff = None
1323
R David Murraycee7cf62015-05-16 13:58:14 -04001324 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +08001325 self.thread_key = threading_helper.threading_setup()
R David Murraycee7cf62015-05-16 13:58:14 -04001326 self.real_getfqdn = socket.getfqdn
1327 socket.getfqdn = mock_socket.getfqdn
1328 self.serv_evt = threading.Event()
1329 self.client_evt = threading.Event()
1330 # Pick a random unused port by passing 0 for the port number
1331 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1332 decode_data=False,
1333 enable_SMTPUTF8=True)
1334 # Keep a note of what port was assigned
1335 self.port = self.serv.socket.getsockname()[1]
1336 serv_args = (self.serv, self.serv_evt, self.client_evt)
1337 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1338 self.thread.start()
1339
1340 # wait until server thread has assigned a port number
1341 self.serv_evt.wait()
1342 self.serv_evt.clear()
1343
1344 def tearDown(self):
1345 socket.getfqdn = self.real_getfqdn
1346 # indicate that the client is finished
1347 self.client_evt.set()
1348 # wait for the server thread to terminate
1349 self.serv_evt.wait()
Hai Shie80697d2020-05-28 06:10:27 +08001350 threading_helper.join_thread(self.thread)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001351 del self.thread
1352 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +08001353 threading_helper.threading_cleanup(*self.thread_key)
R David Murraycee7cf62015-05-16 13:58:14 -04001354
1355 def test_test_server_supports_extensions(self):
1356 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001357 HOST, self.port, local_hostname='localhost',
1358 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001359 self.addCleanup(smtp.close)
1360 smtp.ehlo()
1361 self.assertTrue(smtp.does_esmtp)
1362 self.assertTrue(smtp.has_extn('smtputf8'))
1363
1364 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1365 m = '¡a test message containing unicode!'.encode('utf-8')
1366 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001367 HOST, self.port, local_hostname='localhost',
1368 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001369 self.addCleanup(smtp.close)
1370 smtp.sendmail('Jőhn', 'Sálly', m,
1371 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1372 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1373 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1374 self.assertEqual(self.serv.last_message, m)
1375 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1376 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1377 self.assertEqual(self.serv.last_rcpt_options, [])
1378
1379 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1380 m = '¡a test message containing unicode!'.encode('utf-8')
1381 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001382 HOST, self.port, local_hostname='localhost',
1383 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001384 self.addCleanup(smtp.close)
1385 smtp.ehlo()
1386 self.assertEqual(
1387 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1388 (250, b'OK'))
1389 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1390 self.assertEqual(smtp.data(m), (250, b'OK'))
1391 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1392 self.assertEqual(self.serv.last_rcpttos, ['János'])
1393 self.assertEqual(self.serv.last_message, m)
1394 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1395 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1396 self.assertEqual(self.serv.last_rcpt_options, [])
1397
R David Murray83084442015-05-17 19:27:22 -04001398 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1399 msg = EmailMessage()
1400 msg['From'] = "Páolo <főo@bar.com>"
1401 msg['To'] = 'Dinsdale'
1402 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1403 # XXX I don't know why I need two \n's here, but this is an existing
1404 # bug (if it is one) and not a problem with the new functionality.
1405 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1406 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1407 # we are successfully sending /r/n :(.
1408 expected = textwrap.dedent("""\
1409 From: Páolo <főo@bar.com>
1410 To: Dinsdale
1411 Subject: Nudge nudge, wink, wink \u1F609
1412 Content-Type: text/plain; charset="utf-8"
1413 Content-Transfer-Encoding: 8bit
1414 MIME-Version: 1.0
1415
1416 oh là là, know what I mean, know what I mean?
1417 """)
1418 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001419 HOST, self.port, local_hostname='localhost',
1420 timeout=support.LOOPBACK_TIMEOUT)
R David Murray83084442015-05-17 19:27:22 -04001421 self.addCleanup(smtp.close)
1422 self.assertEqual(smtp.send_message(msg), {})
1423 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1424 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1425 self.assertEqual(self.serv.last_message.decode(), expected)
1426 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1427 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1428 self.assertEqual(self.serv.last_rcpt_options, [])
1429
Guido van Rossum04110fb2007-08-24 16:32:05 +00001430
Barry Warsawc5ea7542015-07-09 10:39:55 -04001431EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1432
1433class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1434 def smtp_AUTH(self, arg):
1435 # RFC 4954's AUTH command allows for an optional initial-response.
1436 # Not all AUTH methods support this; some require a challenge. AUTH
1437 # PLAIN does those, so test that here. See issue #15014.
1438 args = arg.split()
1439 if args[0].lower() == 'plain':
1440 if len(args) == 2:
1441 # AUTH PLAIN <initial-response> with the response base 64
1442 # encoded. Hard code the expected response for the test.
1443 if args[1] == EXPECTED_RESPONSE:
1444 self.push('235 Ok')
1445 return
1446 self.push('571 Bad authentication')
1447
1448class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1449 channel_class = SimSMTPAUTHInitialResponseChannel
1450
1451
Barry Warsawc5ea7542015-07-09 10:39:55 -04001452class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1453 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +08001454 self.thread_key = threading_helper.threading_setup()
Barry Warsawc5ea7542015-07-09 10:39:55 -04001455 self.real_getfqdn = socket.getfqdn
1456 socket.getfqdn = mock_socket.getfqdn
1457 self.serv_evt = threading.Event()
1458 self.client_evt = threading.Event()
1459 # Pick a random unused port by passing 0 for the port number
1460 self.serv = SimSMTPAUTHInitialResponseServer(
1461 (HOST, 0), ('nowhere', -1), decode_data=True)
1462 # Keep a note of what port was assigned
1463 self.port = self.serv.socket.getsockname()[1]
1464 serv_args = (self.serv, self.serv_evt, self.client_evt)
1465 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1466 self.thread.start()
1467
1468 # wait until server thread has assigned a port number
1469 self.serv_evt.wait()
1470 self.serv_evt.clear()
1471
1472 def tearDown(self):
1473 socket.getfqdn = self.real_getfqdn
1474 # indicate that the client is finished
1475 self.client_evt.set()
1476 # wait for the server thread to terminate
1477 self.serv_evt.wait()
Hai Shie80697d2020-05-28 06:10:27 +08001478 threading_helper.join_thread(self.thread)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001479 del self.thread
1480 self.doCleanups()
Hai Shie80697d2020-05-28 06:10:27 +08001481 threading_helper.threading_cleanup(*self.thread_key)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001482
1483 def testAUTH_PLAIN_initial_response_login(self):
1484 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001485 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1486 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001487 smtp.login('psu', 'doesnotexist')
1488 smtp.close()
1489
1490 def testAUTH_PLAIN_initial_response_auth(self):
1491 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001492 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1493 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001494 smtp.user = 'psu'
1495 smtp.password = 'doesnotexist'
1496 code, response = smtp.auth('plain', smtp.auth_plain)
1497 smtp.close()
1498 self.assertEqual(code, 235)
1499
1500
Guido van Rossumd8faa362007-04-27 19:54:29 +00001501if __name__ == '__main__':
chason48ed88a2018-07-26 04:01:28 +09001502 unittest.main()