blob: a3e5b3f3774c6ebe7252cef18ca67ada3f4a03c9 [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
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020023from test.support import HOST
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +010024from test.support import threading_setup, threading_cleanup, join_thread
Christian Heimesc64a1a62019-09-25 16:30:20 +020025from test.support import requires_hashdigest
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +020026from unittest.mock import Mock
Guido van Rossumd8faa362007-04-27 19:54:29 +000027
Victor Stinner45df8202010-04-28 22:31:17 +000028
Josiah Carlsond74900e2008-07-07 04:15:08 +000029if sys.platform == 'darwin':
30 # select.poll returns a select.POLLHUP at the end of the tests
31 # on darwin, so just ignore it
32 def handle_expt(self):
33 pass
34 smtpd.SMTPChannel.handle_expt = handle_expt
35
36
Christian Heimes5e696852008-04-09 08:37:03 +000037def server(evt, buf, serv):
Charles-François Natali6e204602014-07-23 19:28:13 +010038 serv.listen()
Christian Heimes380f7f22008-02-28 11:19:05 +000039 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000040 try:
41 conn, addr = serv.accept()
42 except socket.timeout:
43 pass
44 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000045 n = 500
46 while buf and n > 0:
47 r, w, e = select.select([], [conn], [])
48 if w:
49 sent = conn.send(buf)
50 buf = buf[sent:]
51
52 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000053
Guido van Rossumd8faa362007-04-27 19:54:29 +000054 conn.close()
55 finally:
56 serv.close()
57 evt.set()
58
Victor Stinner45df8202010-04-28 22:31:17 +000059class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000060
61 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000062 smtplib.socket = mock_socket
63 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000064
65 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000066 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000067
R. David Murray7dff9e02010-11-08 17:15:13 +000068 # This method is no longer used but is retained for backward compatibility,
69 # so test to make sure it still works.
70 def testQuoteData(self):
71 teststr = "abc\n.jkl\rfoo\r\n..blue"
72 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
73 self.assertEqual(expected, smtplib.quotedata(teststr))
74
Guido van Rossum806c2462007-08-06 23:33:07 +000075 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000076 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000077 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000078 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000079 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000080
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080081 def testSourceAddress(self):
82 mock_socket.reply_with(b"220 Hola mundo")
83 # connects
84 smtp = smtplib.SMTP(HOST, self.port,
85 source_address=('127.0.0.1',19876))
86 self.assertEqual(smtp.source_address, ('127.0.0.1', 19876))
87 smtp.close()
88
Guido van Rossum806c2462007-08-06 23:33:07 +000089 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000090 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000091 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000092 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000093 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000094
95 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000096 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000097 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000098 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000099 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000100 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000101
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000103 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200104 self.assertIsNone(mock_socket.getdefaulttimeout())
Richard Jones64b02de2010-08-03 06:39:33 +0000105 mock_socket.setdefaulttimeout(30)
106 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000107 try:
108 smtp = smtplib.SMTP(HOST, self.port)
109 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000110 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000112 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113
114 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000115 mock_socket.reply_with(b"220 Hola mundo")
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200116 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117 socket.setdefaulttimeout(30)
118 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000119 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000120 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000121 socket.setdefaulttimeout(None)
Serhiy Storchaka578c6772014-02-08 15:06:08 +0200122 self.assertIsNone(smtp.sock.gettimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000123 smtp.close()
124
125 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000126 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000127 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000129 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130
R David Murray0c49b892015-04-16 17:14:42 -0400131 def test_debuglevel(self):
132 mock_socket.reply_with(b"220 Hello world")
133 smtp = smtplib.SMTP()
134 smtp.set_debuglevel(1)
135 with support.captured_stderr() as stderr:
136 smtp.connect(HOST, self.port)
137 smtp.close()
138 expected = re.compile(r"^connect:", re.MULTILINE)
139 self.assertRegex(stderr.getvalue(), expected)
140
141 def test_debuglevel_2(self):
142 mock_socket.reply_with(b"220 Hello world")
143 smtp = smtplib.SMTP()
144 smtp.set_debuglevel(2)
145 with support.captured_stderr() as stderr:
146 smtp.connect(HOST, self.port)
147 smtp.close()
148 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
149 re.MULTILINE)
150 self.assertRegex(stderr.getvalue(), expected)
151
Guido van Rossumd8faa362007-04-27 19:54:29 +0000152
Guido van Rossum04110fb2007-08-24 16:32:05 +0000153# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000154def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000155 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000156
157 try:
158 if hasattr(select, 'poll'):
159 poll_fun = asyncore.poll2
160 else:
161 poll_fun = asyncore.poll
162
163 n = 1000
164 while asyncore.socket_map and n > 0:
165 poll_fun(0.01, asyncore.socket_map)
166
167 # when the client conversation is finished, it will
168 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000169 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000170 serv.close()
171 break
172
173 n -= 1
174
175 except socket.timeout:
176 pass
177 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000178 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000179 # allow some time for the client to read the result
180 time.sleep(0.5)
181 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000182 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000183 serv_evt.set()
184
185MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
186MSG_END = '------------ END MESSAGE ------------\n'
187
Guido van Rossum04110fb2007-08-24 16:32:05 +0000188# NOTE: Some SMTP objects in the tests below are created with a non-default
189# local_hostname argument to the constructor, since (on some systems) the FQDN
190# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000191# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000192
193# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000194class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000195
R. David Murray7dff9e02010-11-08 17:15:13 +0000196 maxDiff = None
197
Guido van Rossum806c2462007-08-06 23:33:07 +0000198 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100199 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000200 self.real_getfqdn = socket.getfqdn
201 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000202 # temporarily replace sys.stdout to capture DebuggingServer output
203 self.old_stdout = sys.stdout
204 self.output = io.StringIO()
205 sys.stdout = self.output
206
207 self.serv_evt = threading.Event()
208 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000209 # Capture SMTPChannel debug output
210 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
211 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000212 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400213 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
214 decode_data=True)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700215 # Keep a note of what server host and port were assigned
216 self.host, self.port = self.serv.socket.getsockname()[:2]
Christian Heimes5e696852008-04-09 08:37:03 +0000217 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000218 self.thread = threading.Thread(target=debugging_server, args=serv_args)
219 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000220
221 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000222 self.serv_evt.wait()
223 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000224
225 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000226 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000227 # indicate that the client is finished
228 self.client_evt.set()
229 # wait for the server thread to terminate
230 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100231 join_thread(self.thread)
Guido van Rossum806c2462007-08-06 23:33:07 +0000232 # restore sys.stdout
233 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000234 # restore DEBUGSTREAM
235 smtpd.DEBUGSTREAM.close()
236 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100237 del self.thread
238 self.doCleanups()
239 threading_cleanup(*self.thread_key)
Guido van Rossum806c2462007-08-06 23:33:07 +0000240
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700241 def get_output_without_xpeer(self):
242 test_output = self.output.getvalue()
243 return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2',
244 test_output, flags=re.MULTILINE|re.DOTALL)
245
Guido van Rossum806c2462007-08-06 23:33:07 +0000246 def testBasic(self):
247 # connect
Victor Stinner07871b22019-12-10 20:32:59 +0100248 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
249 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum806c2462007-08-06 23:33:07 +0000250 smtp.quit()
251
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800252 def testSourceAddress(self):
253 # connect
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700254 src_port = support.find_unused_port()
Senthil Kumaranb351a482011-07-31 09:14:17 +0800255 try:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700256 smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost',
Victor Stinner07871b22019-12-10 20:32:59 +0100257 timeout=support.LOOPBACK_TIMEOUT,
258 source_address=(self.host, src_port))
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100259 self.addCleanup(smtp.close)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700260 self.assertEqual(smtp.source_address, (self.host, src_port))
Senthil Kumaranb351a482011-07-31 09:14:17 +0800261 self.assertEqual(smtp.local_hostname, 'localhost')
262 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200263 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800264 if e.errno == errno.EADDRINUSE:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700265 self.skipTest("couldn't bind to source port %d" % src_port)
Senthil Kumaranb351a482011-07-31 09:14:17 +0800266 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800267
Guido van Rossum04110fb2007-08-24 16:32:05 +0000268 def testNOOP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100269 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
270 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100271 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400272 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000273 self.assertEqual(smtp.noop(), expected)
274 smtp.quit()
275
276 def testRSET(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100277 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
278 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100279 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400280 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000281 self.assertEqual(smtp.rset(), expected)
282 smtp.quit()
283
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400284 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000285 # EHLO isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100286 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
287 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100288 self.addCleanup(smtp.close)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400289 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000290 self.assertEqual(smtp.ehlo(), expected)
291 smtp.quit()
292
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400293 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400294 # EXPN isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100295 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
296 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100297 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400298 expected = (502, b'EXPN not implemented')
299 smtp.putcmd('EXPN')
300 self.assertEqual(smtp.getreply(), expected)
301 smtp.quit()
302
303 def testVRFY(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100304 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
305 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100306 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400307 expected = (252, b'Cannot VRFY user, but will accept message ' + \
308 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000309 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
310 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
311 smtp.quit()
312
313 def testSecondHELO(self):
314 # check that a second HELO returns a message that it's a duplicate
315 # (this behavior is specific to smtpd.SMTPChannel)
Victor Stinner07871b22019-12-10 20:32:59 +0100316 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
317 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100318 self.addCleanup(smtp.close)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000319 smtp.helo()
320 expected = (503, b'Duplicate HELO/EHLO')
321 self.assertEqual(smtp.helo(), expected)
322 smtp.quit()
323
Guido van Rossum806c2462007-08-06 23:33:07 +0000324 def testHELP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100325 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
326 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100327 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400328 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
329 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000330 smtp.quit()
331
332 def testSend(self):
333 # connect and send mail
334 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100335 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
336 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100337 self.addCleanup(smtp.close)
Guido van Rossum806c2462007-08-06 23:33:07 +0000338 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000339 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
340 # in asyncore. This sleep might help, but should really be fixed
341 # properly by using an Event variable.
342 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000343 smtp.quit()
344
345 self.client_evt.set()
346 self.serv_evt.wait()
347 self.output.flush()
348 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
349 self.assertEqual(self.output.getvalue(), mexpect)
350
R. David Murray7dff9e02010-11-08 17:15:13 +0000351 def testSendBinary(self):
352 m = b'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100353 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
354 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100355 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000356 smtp.sendmail('John', 'Sally', m)
357 # XXX (see comment in testSend)
358 time.sleep(0.01)
359 smtp.quit()
360
361 self.client_evt.set()
362 self.serv_evt.wait()
363 self.output.flush()
364 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
365 self.assertEqual(self.output.getvalue(), mexpect)
366
R David Murray0f663d02011-06-09 15:05:57 -0400367 def testSendNeedingDotQuote(self):
368 # Issue 12283
369 m = '.A test\n.mes.sage.'
Victor Stinner07871b22019-12-10 20:32:59 +0100370 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
371 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100372 self.addCleanup(smtp.close)
R David Murray0f663d02011-06-09 15:05:57 -0400373 smtp.sendmail('John', 'Sally', m)
374 # XXX (see comment in testSend)
375 time.sleep(0.01)
376 smtp.quit()
377
378 self.client_evt.set()
379 self.serv_evt.wait()
380 self.output.flush()
381 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
382 self.assertEqual(self.output.getvalue(), mexpect)
383
R David Murray46346762011-07-18 21:38:54 -0400384 def testSendNullSender(self):
385 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100386 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
387 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100388 self.addCleanup(smtp.close)
R David Murray46346762011-07-18 21:38:54 -0400389 smtp.sendmail('<>', 'Sally', m)
390 # XXX (see comment in testSend)
391 time.sleep(0.01)
392 smtp.quit()
393
394 self.client_evt.set()
395 self.serv_evt.wait()
396 self.output.flush()
397 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
398 self.assertEqual(self.output.getvalue(), mexpect)
399 debugout = smtpd.DEBUGSTREAM.getvalue()
400 sender = re.compile("^sender: <>$", re.MULTILINE)
401 self.assertRegex(debugout, sender)
402
R. David Murray7dff9e02010-11-08 17:15:13 +0000403 def testSendMessage(self):
404 m = email.mime.text.MIMEText('A test message')
Victor Stinner07871b22019-12-10 20:32:59 +0100405 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
406 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100407 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000408 smtp.send_message(m, from_addr='John', to_addrs='Sally')
409 # XXX (see comment in testSend)
410 time.sleep(0.01)
411 smtp.quit()
412
413 self.client_evt.set()
414 self.serv_evt.wait()
415 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700416 # Remove the X-Peer header that DebuggingServer adds as figuring out
417 # exactly what IP address format is put there is not easy (and
418 # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is
419 # not always the same as socket.gethostbyname(HOST). :(
420 test_output = self.get_output_without_xpeer()
421 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000422 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700423 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000424
425 def testSendMessageWithAddresses(self):
426 m = email.mime.text.MIMEText('A test message')
427 m['From'] = 'foo@bar.com'
428 m['To'] = 'John'
429 m['CC'] = 'Sally, Fred'
430 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
Victor Stinner07871b22019-12-10 20:32:59 +0100431 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
432 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100433 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000434 smtp.send_message(m)
435 # XXX (see comment in testSend)
436 time.sleep(0.01)
437 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400438 # make sure the Bcc header is still in the message.
439 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
440 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000441
442 self.client_evt.set()
443 self.serv_evt.wait()
444 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700445 # Remove the X-Peer header that DebuggingServer adds.
446 test_output = self.get_output_without_xpeer()
447 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400448 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000449 del m['Bcc']
450 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700451 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000452 debugout = smtpd.DEBUGSTREAM.getvalue()
453 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000454 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000455 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
456 'warped@silly.walks.com'):
457 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
458 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000459 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000460
461 def testSendMessageWithSomeAddresses(self):
462 # Make sure nothing breaks if not all of the three 'to' headers exist
463 m = email.mime.text.MIMEText('A test message')
464 m['From'] = 'foo@bar.com'
465 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100466 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
467 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100468 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000469 smtp.send_message(m)
470 # XXX (see comment in testSend)
471 time.sleep(0.01)
472 smtp.quit()
473
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 Murray7dff9e02010-11-08 17:15:13 +0000480 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700481 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000482 debugout = smtpd.DEBUGSTREAM.getvalue()
483 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000484 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000485 for addr in ('John', 'Dinsdale'):
486 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
487 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000488 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000489
R David Murrayac4e5ab2011-07-02 21:03:19 -0400490 def testSendMessageWithSpecifiedAddresses(self):
491 # Make sure addresses specified in call override those in message.
492 m = email.mime.text.MIMEText('A test message')
493 m['From'] = 'foo@bar.com'
494 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100495 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
496 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100497 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400498 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
499 # XXX (see comment in testSend)
500 time.sleep(0.01)
501 smtp.quit()
502
503 self.client_evt.set()
504 self.serv_evt.wait()
505 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700506 # Remove the X-Peer header that DebuggingServer adds.
507 test_output = self.get_output_without_xpeer()
508 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400509 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700510 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400511 debugout = smtpd.DEBUGSTREAM.getvalue()
512 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
513 self.assertRegex(debugout, sender)
514 for addr in ('John', 'Dinsdale'):
515 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
516 re.MULTILINE)
517 self.assertNotRegex(debugout, to_addr)
518 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
519 self.assertRegex(debugout, recip)
520
521 def testSendMessageWithMultipleFrom(self):
522 # Sender overrides To
523 m = email.mime.text.MIMEText('A test message')
524 m['From'] = 'Bernard, Bianca'
525 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.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)
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: the_rescuers@Rescue-Aid-Society.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.assertRegex(debugout, to_addr)
550
551 def testSendMessageResent(self):
552 m = email.mime.text.MIMEText('A test message')
553 m['From'] = 'foo@bar.com'
554 m['To'] = 'John'
555 m['CC'] = 'Sally, Fred'
556 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
557 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
558 m['Resent-From'] = 'holy@grail.net'
559 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
560 m['Resent-Bcc'] = 'doe@losthope.net'
Victor Stinner07871b22019-12-10 20:32:59 +0100561 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
562 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100563 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400564 smtp.send_message(m)
565 # XXX (see comment in testSend)
566 time.sleep(0.01)
567 smtp.quit()
568
569 self.client_evt.set()
570 self.serv_evt.wait()
571 self.output.flush()
572 # The Resent-Bcc headers are deleted before serialization.
573 del m['Bcc']
574 del m['Resent-Bcc']
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700575 # Remove the X-Peer header that DebuggingServer adds.
576 test_output = self.get_output_without_xpeer()
577 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400578 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700579 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400580 debugout = smtpd.DEBUGSTREAM.getvalue()
581 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
582 self.assertRegex(debugout, sender)
583 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
584 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
585 re.MULTILINE)
586 self.assertRegex(debugout, to_addr)
587
588 def testSendMessageMultipleResentRaises(self):
589 m = email.mime.text.MIMEText('A test message')
590 m['From'] = 'foo@bar.com'
591 m['To'] = 'John'
592 m['CC'] = 'Sally, Fred'
593 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
594 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
595 m['Resent-From'] = 'holy@grail.net'
596 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
597 m['Resent-Bcc'] = 'doe@losthope.net'
598 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
599 m['Resent-To'] = 'holy@grail.net'
600 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
Victor Stinner07871b22019-12-10 20:32:59 +0100601 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
602 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100603 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400604 with self.assertRaises(ValueError):
605 smtp.send_message(m)
606 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000607
Victor Stinner45df8202010-04-28 22:31:17 +0000608class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000609
610 def testNotConnected(self):
611 # Test various operations on an unconnected SMTP object that
612 # should raise exceptions (at present the attempt in SMTP.send
613 # to reference the nonexistent 'sock' attribute of the SMTP object
614 # causes an AttributeError)
615 smtp = smtplib.SMTP()
616 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
617 self.assertRaises(smtplib.SMTPServerDisconnected,
618 smtp.send, 'test msg')
619
620 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200621 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200622 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000623 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200624 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000625 "localhost:bogus")
626
Romuald Brunet7b313972018-10-09 16:31:55 +0200627 def testSockAttributeExists(self):
628 # check that sock attribute is present outside of a connect() call
629 # (regression test, the previous behavior raised an
630 # AttributeError: 'SMTP' object has no attribute 'sock')
631 with smtplib.SMTP() as smtp:
632 self.assertIsNone(smtp.sock)
633
Christian Heimes380f7f22008-02-28 11:19:05 +0000634
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200635class DefaultArgumentsTests(unittest.TestCase):
636
637 def setUp(self):
638 self.msg = EmailMessage()
639 self.msg['From'] = 'Páolo <főo@bar.com>'
640 self.smtp = smtplib.SMTP()
641 self.smtp.ehlo = Mock(return_value=(200, 'OK'))
642 self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
643
644 def testSendMessage(self):
645 expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
646 self.smtp.send_message(self.msg)
647 self.smtp.send_message(self.msg)
648 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
649 expected_mail_options)
650 self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
651 expected_mail_options)
652
653 def testSendMessageWithMailOptions(self):
654 mail_options = ['STARTTLS']
655 expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
656 self.smtp.send_message(self.msg, None, None, mail_options)
657 self.assertEqual(mail_options, ['STARTTLS'])
658 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
659 expected_mail_options)
660
661
Guido van Rossum04110fb2007-08-24 16:32:05 +0000662# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000663class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000664
665 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000666 smtplib.socket = mock_socket
667 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000668 self.old_stdout = sys.stdout
669 self.output = io.StringIO()
670 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000671 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000672
673 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000674 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000675 sys.stdout = self.old_stdout
676
677 def testFailingHELO(self):
678 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000679 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000680
Guido van Rossum04110fb2007-08-24 16:32:05 +0000681
Georg Brandlb38b5c42014-02-10 22:11:21 +0100682class TooLongLineTests(unittest.TestCase):
683 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
684
685 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100686 self.thread_key = threading_setup()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100687 self.old_stdout = sys.stdout
688 self.output = io.StringIO()
689 sys.stdout = self.output
690
691 self.evt = threading.Event()
692 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
693 self.sock.settimeout(15)
694 self.port = support.bind_port(self.sock)
695 servargs = (self.evt, self.respdata, self.sock)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100696 self.thread = threading.Thread(target=server, args=servargs)
697 self.thread.start()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100698 self.evt.wait()
699 self.evt.clear()
700
701 def tearDown(self):
702 self.evt.wait()
703 sys.stdout = self.old_stdout
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100704 join_thread(self.thread)
705 del self.thread
706 self.doCleanups()
707 threading_cleanup(*self.thread_key)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100708
709 def testLineTooLong(self):
710 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
711 HOST, self.port, 'localhost', 3)
712
713
Guido van Rossum04110fb2007-08-24 16:32:05 +0000714sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400715 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000716 'Mrs.C@somewhereesle.com':'Ruth C',
717 }
718
R. David Murraycaa27b72009-05-23 18:49:56 +0000719sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000720sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
721 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000722sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400723 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000724 }
725
726# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500727class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000728class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000729
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400730 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400731 mail_response = None
732 rcpt_response = None
733 data_response = None
734 rcpt_count = 0
735 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400736 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500737 AUTH = 99 # Add protocol state to enable auth testing.
738 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400739
R. David Murray23ddc0e2009-05-29 18:03:16 +0000740 def __init__(self, extra_features, *args, **kw):
741 self._extrafeatures = ''.join(
742 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000743 super(SimSMTPChannel, self).__init__(*args, **kw)
744
R David Murrayb0deeb42015-11-08 01:03:52 -0500745 # AUTH related stuff. It would be nice if support for this were in smtpd.
746 def found_terminator(self):
747 if self.smtp_state == self.AUTH:
748 line = self._emptystring.join(self.received_lines)
749 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
750 self.received_lines = []
751 try:
752 self.auth_object(line)
753 except ResponseException as e:
754 self.smtp_state = self.COMMAND
755 self.push('%s %s' % (e.smtp_code, e.smtp_error))
756 return
757 super().found_terminator()
758
759
760 def smtp_AUTH(self, arg):
761 if not self.seen_greeting:
762 self.push('503 Error: send EHLO first')
763 return
764 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
765 self.push('500 Error: command "AUTH" not recognized')
766 return
767 if self.authenticated_user is not None:
768 self.push(
769 '503 Bad sequence of commands: already authenticated')
770 return
771 args = arg.split()
772 if len(args) not in [1, 2]:
773 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
774 return
775 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
776 try:
777 self.auth_object = getattr(self, auth_object_name)
778 except AttributeError:
779 self.push('504 Command parameter not implemented: unsupported '
780 ' authentication mechanism {!r}'.format(auth_object_name))
781 return
782 self.smtp_state = self.AUTH
783 self.auth_object(args[1] if len(args) == 2 else None)
784
785 def _authenticated(self, user, valid):
786 if valid:
787 self.authenticated_user = user
788 self.push('235 Authentication Succeeded')
789 else:
790 self.push('535 Authentication credentials invalid')
791 self.smtp_state = self.COMMAND
792
793 def _decode_base64(self, string):
794 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
795
796 def _auth_plain(self, arg=None):
797 if arg is None:
798 self.push('334 ')
799 else:
800 logpass = self._decode_base64(arg)
801 try:
802 *_, user, password = logpass.split('\0')
803 except ValueError as e:
804 self.push('535 Splitting response {!r} into user and password'
805 ' failed: {}'.format(logpass, e))
806 return
807 self._authenticated(user, password == sim_auth[1])
808
809 def _auth_login(self, arg=None):
810 if arg is None:
811 # base64 encoded 'Username:'
812 self.push('334 VXNlcm5hbWU6')
813 elif not hasattr(self, '_auth_login_user'):
814 self._auth_login_user = self._decode_base64(arg)
815 # base64 encoded 'Password:'
816 self.push('334 UGFzc3dvcmQ6')
817 else:
818 password = self._decode_base64(arg)
819 self._authenticated(self._auth_login_user, password == sim_auth[1])
820 del self._auth_login_user
821
822 def _auth_cram_md5(self, arg=None):
823 if arg is None:
824 self.push('334 {}'.format(sim_cram_md5_challenge))
825 else:
826 logpass = self._decode_base64(arg)
827 try:
828 user, hashed_pass = logpass.split()
829 except ValueError as e:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200830 self.push('535 Splitting response {!r} into user and password '
R David Murrayb0deeb42015-11-08 01:03:52 -0500831 'failed: {}'.format(logpass, e))
832 return False
833 valid_hashed_pass = hmac.HMAC(
834 sim_auth[1].encode('ascii'),
835 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
836 'md5').hexdigest()
837 self._authenticated(user, hashed_pass == valid_hashed_pass)
838 # end AUTH related stuff.
839
Guido van Rossum04110fb2007-08-24 16:32:05 +0000840 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000841 resp = ('250-testhost\r\n'
842 '250-EXPN\r\n'
843 '250-SIZE 20000000\r\n'
844 '250-STARTTLS\r\n'
845 '250-DELIVERBY\r\n')
846 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000847 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400848 self.seen_greeting = arg
849 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000850
851 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400852 # For max compatibility smtplib should be sending the raw address.
853 if arg in sim_users:
854 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000855 else:
856 self.push('550 No such user: %s' % arg)
857
858 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400859 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000860 if list_name in sim_lists:
861 user_list = sim_lists[list_name]
862 for n, user_email in enumerate(user_list):
863 quoted_addr = smtplib.quoteaddr(user_email)
864 if n < len(user_list) - 1:
865 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
866 else:
867 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
868 else:
869 self.push('550 No access for you!')
870
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400871 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400872 if self.quit_response is None:
873 super(SimSMTPChannel, self).smtp_QUIT(arg)
874 else:
875 self.push(self.quit_response)
876 self.close_when_done()
877
R David Murrayd312c742013-03-20 20:36:14 -0400878 def smtp_MAIL(self, arg):
879 if self.mail_response is None:
880 super().smtp_MAIL(arg)
881 else:
882 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400883 if self.disconnect:
884 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400885
886 def smtp_RCPT(self, arg):
887 if self.rcpt_response is None:
888 super().smtp_RCPT(arg)
889 return
R David Murrayd312c742013-03-20 20:36:14 -0400890 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400891 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400892
893 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400894 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400895 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400896
897 def smtp_DATA(self, arg):
898 if self.data_response is None:
899 super().smtp_DATA(arg)
900 else:
901 self.push(self.data_response)
902
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000903 def handle_error(self):
904 raise
905
Guido van Rossum04110fb2007-08-24 16:32:05 +0000906
907class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000908
R David Murrayd312c742013-03-20 20:36:14 -0400909 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400910
R. David Murray23ddc0e2009-05-29 18:03:16 +0000911 def __init__(self, *args, **kw):
912 self._extra_features = []
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100913 self._addresses = {}
R. David Murray23ddc0e2009-05-29 18:03:16 +0000914 smtpd.SMTPServer.__init__(self, *args, **kw)
915
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000916 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400917 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400918 self._extra_features, self, conn, addr,
919 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000920
921 def process_message(self, peer, mailfrom, rcpttos, data):
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100922 self._addresses['from'] = mailfrom
923 self._addresses['tos'] = rcpttos
Guido van Rossum04110fb2007-08-24 16:32:05 +0000924
R. David Murrayfb123912009-05-28 18:19:00 +0000925 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000926 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000927
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000928 def handle_error(self):
929 raise
930
Guido van Rossum04110fb2007-08-24 16:32:05 +0000931
932# Test various SMTP & ESMTP commands/behaviors that require a simulated server
933# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000934class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000935
936 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100937 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000938 self.real_getfqdn = socket.getfqdn
939 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000940 self.serv_evt = threading.Event()
941 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000942 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400943 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000944 # Keep a note of what port was assigned
945 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000946 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000947 self.thread = threading.Thread(target=debugging_server, args=serv_args)
948 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000949
950 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000951 self.serv_evt.wait()
952 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000953
954 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000955 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000956 # indicate that the client is finished
957 self.client_evt.set()
958 # wait for the server thread to terminate
959 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100960 join_thread(self.thread)
961 del self.thread
962 self.doCleanups()
963 threading_cleanup(*self.thread_key)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000964
965 def testBasic(self):
966 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000967 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000968 smtp.quit()
969
970 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000971 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000972
973 # no features should be present before the EHLO
974 self.assertEqual(smtp.esmtp_features, {})
975
976 # features expected from the test server
977 expected_features = {'expn':'',
978 'size': '20000000',
979 'starttls': '',
980 'deliverby': '',
981 'help': '',
982 }
983
984 smtp.ehlo()
985 self.assertEqual(smtp.esmtp_features, expected_features)
986 for k in expected_features:
987 self.assertTrue(smtp.has_extn(k))
988 self.assertFalse(smtp.has_extn('unsupported-feature'))
989 smtp.quit()
990
991 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000992 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000993
Barry Warsawc5ea7542015-07-09 10:39:55 -0400994 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +0000995 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -0400996 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000997 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -0400998 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000999
1000 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -04001001 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001002 self.assertEqual(smtp.vrfy(u), expected_unknown)
1003 smtp.quit()
1004
1005 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001006 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001007
1008 for listname, members in sim_lists.items():
1009 users = []
1010 for m in members:
1011 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001012 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001013 self.assertEqual(smtp.expn(listname), expected_known)
1014
1015 u = 'PSU-Members-List'
1016 expected_unknown = (550, b'No access for you!')
1017 self.assertEqual(smtp.expn(u), expected_unknown)
1018 smtp.quit()
1019
R David Murray76e13c12014-07-03 14:47:46 -04001020 def testAUTH_PLAIN(self):
1021 self.serv.add_feature("AUTH PLAIN")
1022 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001023 resp = smtp.login(sim_auth[0], sim_auth[1])
1024 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001025 smtp.close()
1026
R. David Murrayfb123912009-05-28 18:19:00 +00001027 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001028 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +00001029 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001030 resp = smtp.login(sim_auth[0], sim_auth[1])
1031 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001032 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001033
Christian Heimesc64a1a62019-09-25 16:30:20 +02001034 @requires_hashdigest('md5')
R. David Murrayfb123912009-05-28 18:19:00 +00001035 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001036 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +00001037 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001038 resp = smtp.login(sim_auth[0], sim_auth[1])
1039 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001040 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001041
Andrew Kuchling78591822013-11-11 14:03:23 -05001042 def testAUTH_multiple(self):
1043 # Test that multiple authentication methods are tried.
1044 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
1045 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murrayb0deeb42015-11-08 01:03:52 -05001046 resp = smtp.login(sim_auth[0], sim_auth[1])
1047 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001048 smtp.close()
1049
1050 def test_auth_function(self):
Christian Heimesc64a1a62019-09-25 16:30:20 +02001051 supported = {'PLAIN', 'LOGIN'}
1052 try:
1053 hashlib.md5()
1054 except ValueError:
1055 pass
1056 else:
1057 supported.add('CRAM-MD5')
R David Murrayb0deeb42015-11-08 01:03:52 -05001058 for mechanism in supported:
1059 self.serv.add_feature("AUTH {}".format(mechanism))
1060 for mechanism in supported:
1061 with self.subTest(mechanism=mechanism):
1062 smtp = smtplib.SMTP(HOST, self.port,
1063 local_hostname='localhost', timeout=15)
1064 smtp.ehlo('foo')
1065 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
1066 method = 'auth_' + mechanism.lower().replace('-', '_')
1067 resp = smtp.auth(mechanism, getattr(smtp, method))
1068 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1069 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -05001070
R David Murray0cff49f2014-08-30 16:51:59 -04001071 def test_quit_resets_greeting(self):
1072 smtp = smtplib.SMTP(HOST, self.port,
1073 local_hostname='localhost',
1074 timeout=15)
1075 code, message = smtp.ehlo()
1076 self.assertEqual(code, 250)
1077 self.assertIn('size', smtp.esmtp_features)
1078 smtp.quit()
1079 self.assertNotIn('size', smtp.esmtp_features)
1080 smtp.connect(HOST, self.port)
1081 self.assertNotIn('size', smtp.esmtp_features)
1082 smtp.ehlo_or_helo_if_needed()
1083 self.assertIn('size', smtp.esmtp_features)
1084 smtp.quit()
1085
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001086 def test_with_statement(self):
1087 with smtplib.SMTP(HOST, self.port) as smtp:
1088 code, message = smtp.noop()
1089 self.assertEqual(code, 250)
1090 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1091 with smtplib.SMTP(HOST, self.port) as smtp:
1092 smtp.close()
1093 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1094
1095 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001096 with self.assertRaises(smtplib.SMTPResponseException) as error:
1097 with smtplib.SMTP(HOST, self.port) as smtp:
1098 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001099 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001100 self.assertEqual(error.exception.smtp_code, 421)
1101 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001102
R. David Murrayfb123912009-05-28 18:19:00 +00001103 #TODO: add tests for correct AUTH method fallback now that the
1104 #test infrastructure can support it.
1105
R David Murrayafb151a2014-04-14 18:21:38 -04001106 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1107 def test__rest_from_mail_cmd(self):
1108 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
1109 smtp.noop()
1110 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1111 self.serv._SMTPchannel.disconnect = True
1112 with self.assertRaises(smtplib.SMTPSenderRefused):
1113 smtp.sendmail('John', 'Sally', 'test message')
1114 self.assertIsNone(smtp.sock)
1115
R David Murrayd312c742013-03-20 20:36:14 -04001116 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1117 def test_421_from_mail_cmd(self):
1118 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001119 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001120 self.serv._SMTPchannel.mail_response = '421 closing connection'
1121 with self.assertRaises(smtplib.SMTPSenderRefused):
1122 smtp.sendmail('John', 'Sally', 'test message')
1123 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001124 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001125
1126 def test_421_from_rcpt_cmd(self):
1127 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001128 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001129 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1130 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1131 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1132 self.assertIsNone(smtp.sock)
1133 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1134 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1135
1136 def test_421_from_data_cmd(self):
1137 class MySimSMTPChannel(SimSMTPChannel):
1138 def found_terminator(self):
1139 if self.smtp_state == self.DATA:
1140 self.push('421 closing')
1141 else:
1142 super().found_terminator()
1143 self.serv.channel_class = MySimSMTPChannel
1144 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R David Murray853c0f92013-03-20 21:54:05 -04001145 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001146 with self.assertRaises(smtplib.SMTPDataError):
1147 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1148 self.assertIsNone(smtp.sock)
1149 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1150
R David Murraycee7cf62015-05-16 13:58:14 -04001151 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1152 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001153 HOST, self.port, local_hostname='localhost',
1154 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001155 self.addCleanup(smtp.close)
1156 smtp.ehlo()
1157 self.assertTrue(smtp.does_esmtp)
1158 self.assertFalse(smtp.has_extn('smtputf8'))
1159 self.assertRaises(
1160 smtplib.SMTPNotSupportedError,
1161 smtp.sendmail,
1162 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1163 self.assertRaises(
1164 smtplib.SMTPNotSupportedError,
1165 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1166
1167 def test_send_unicode_without_SMTPUTF8(self):
1168 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001169 HOST, self.port, local_hostname='localhost',
1170 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001171 self.addCleanup(smtp.close)
1172 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1173 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1174
chason48ed88a2018-07-26 04:01:28 +09001175 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1176 # This test is located here and not in the SMTPUTF8SimTests
1177 # class because it needs a "regular" SMTP server to work
1178 msg = EmailMessage()
1179 msg['From'] = "Páolo <főo@bar.com>"
1180 msg['To'] = 'Dinsdale'
1181 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1182 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001183 HOST, self.port, local_hostname='localhost',
1184 timeout=support.LOOPBACK_TIMEOUT)
chason48ed88a2018-07-26 04:01:28 +09001185 self.addCleanup(smtp.close)
1186 with self.assertRaises(smtplib.SMTPNotSupportedError):
1187 smtp.send_message(msg)
1188
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001189 def test_name_field_not_included_in_envelop_addresses(self):
1190 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001191 HOST, self.port, local_hostname='localhost',
1192 timeout=support.LOOPBACK_TIMEOUT)
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001193 self.addCleanup(smtp.close)
1194
1195 message = EmailMessage()
1196 message['From'] = email.utils.formataddr(('Michaël', 'michael@example.com'))
1197 message['To'] = email.utils.formataddr(('René', 'rene@example.com'))
1198
1199 self.assertDictEqual(smtp.send_message(message), {})
1200
1201 self.assertEqual(self.serv._addresses['from'], 'michael@example.com')
1202 self.assertEqual(self.serv._addresses['tos'], ['rene@example.com'])
1203
R David Murraycee7cf62015-05-16 13:58:14 -04001204
1205class SimSMTPUTF8Server(SimSMTPServer):
1206
1207 def __init__(self, *args, **kw):
1208 # The base SMTP server turns these on automatically, but our test
1209 # server is set up to munge the EHLO response, so we need to provide
1210 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1211 self._extra_features = ['SMTPUTF8', '8BITMIME']
1212 smtpd.SMTPServer.__init__(self, *args, **kw)
1213
1214 def handle_accepted(self, conn, addr):
1215 self._SMTPchannel = self.channel_class(
1216 self._extra_features, self, conn, addr,
1217 decode_data=self._decode_data,
1218 enable_SMTPUTF8=self.enable_SMTPUTF8,
1219 )
1220
1221 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1222 rcpt_options=None):
1223 self.last_peer = peer
1224 self.last_mailfrom = mailfrom
1225 self.last_rcpttos = rcpttos
1226 self.last_message = data
1227 self.last_mail_options = mail_options
1228 self.last_rcpt_options = rcpt_options
1229
1230
R David Murraycee7cf62015-05-16 13:58:14 -04001231class SMTPUTF8SimTests(unittest.TestCase):
1232
R David Murray83084442015-05-17 19:27:22 -04001233 maxDiff = None
1234
R David Murraycee7cf62015-05-16 13:58:14 -04001235 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001236 self.thread_key = threading_setup()
R David Murraycee7cf62015-05-16 13:58:14 -04001237 self.real_getfqdn = socket.getfqdn
1238 socket.getfqdn = mock_socket.getfqdn
1239 self.serv_evt = threading.Event()
1240 self.client_evt = threading.Event()
1241 # Pick a random unused port by passing 0 for the port number
1242 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1243 decode_data=False,
1244 enable_SMTPUTF8=True)
1245 # Keep a note of what port was assigned
1246 self.port = self.serv.socket.getsockname()[1]
1247 serv_args = (self.serv, self.serv_evt, self.client_evt)
1248 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1249 self.thread.start()
1250
1251 # wait until server thread has assigned a port number
1252 self.serv_evt.wait()
1253 self.serv_evt.clear()
1254
1255 def tearDown(self):
1256 socket.getfqdn = self.real_getfqdn
1257 # indicate that the client is finished
1258 self.client_evt.set()
1259 # wait for the server thread to terminate
1260 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001261 join_thread(self.thread)
1262 del self.thread
1263 self.doCleanups()
1264 threading_cleanup(*self.thread_key)
R David Murraycee7cf62015-05-16 13:58:14 -04001265
1266 def test_test_server_supports_extensions(self):
1267 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001268 HOST, self.port, local_hostname='localhost',
1269 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001270 self.addCleanup(smtp.close)
1271 smtp.ehlo()
1272 self.assertTrue(smtp.does_esmtp)
1273 self.assertTrue(smtp.has_extn('smtputf8'))
1274
1275 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1276 m = '¡a test message containing unicode!'.encode('utf-8')
1277 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001278 HOST, self.port, local_hostname='localhost',
1279 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001280 self.addCleanup(smtp.close)
1281 smtp.sendmail('Jőhn', 'Sálly', m,
1282 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1283 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1284 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1285 self.assertEqual(self.serv.last_message, m)
1286 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1287 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1288 self.assertEqual(self.serv.last_rcpt_options, [])
1289
1290 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1291 m = '¡a test message containing unicode!'.encode('utf-8')
1292 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001293 HOST, self.port, local_hostname='localhost',
1294 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001295 self.addCleanup(smtp.close)
1296 smtp.ehlo()
1297 self.assertEqual(
1298 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1299 (250, b'OK'))
1300 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1301 self.assertEqual(smtp.data(m), (250, b'OK'))
1302 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1303 self.assertEqual(self.serv.last_rcpttos, ['János'])
1304 self.assertEqual(self.serv.last_message, m)
1305 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1306 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1307 self.assertEqual(self.serv.last_rcpt_options, [])
1308
R David Murray83084442015-05-17 19:27:22 -04001309 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1310 msg = EmailMessage()
1311 msg['From'] = "Páolo <főo@bar.com>"
1312 msg['To'] = 'Dinsdale'
1313 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1314 # XXX I don't know why I need two \n's here, but this is an existing
1315 # bug (if it is one) and not a problem with the new functionality.
1316 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1317 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1318 # we are successfully sending /r/n :(.
1319 expected = textwrap.dedent("""\
1320 From: Páolo <főo@bar.com>
1321 To: Dinsdale
1322 Subject: Nudge nudge, wink, wink \u1F609
1323 Content-Type: text/plain; charset="utf-8"
1324 Content-Transfer-Encoding: 8bit
1325 MIME-Version: 1.0
1326
1327 oh là là, know what I mean, know what I mean?
1328 """)
1329 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001330 HOST, self.port, local_hostname='localhost',
1331 timeout=support.LOOPBACK_TIMEOUT)
R David Murray83084442015-05-17 19:27:22 -04001332 self.addCleanup(smtp.close)
1333 self.assertEqual(smtp.send_message(msg), {})
1334 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1335 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1336 self.assertEqual(self.serv.last_message.decode(), expected)
1337 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1338 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1339 self.assertEqual(self.serv.last_rcpt_options, [])
1340
Guido van Rossum04110fb2007-08-24 16:32:05 +00001341
Barry Warsawc5ea7542015-07-09 10:39:55 -04001342EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1343
1344class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1345 def smtp_AUTH(self, arg):
1346 # RFC 4954's AUTH command allows for an optional initial-response.
1347 # Not all AUTH methods support this; some require a challenge. AUTH
1348 # PLAIN does those, so test that here. See issue #15014.
1349 args = arg.split()
1350 if args[0].lower() == 'plain':
1351 if len(args) == 2:
1352 # AUTH PLAIN <initial-response> with the response base 64
1353 # encoded. Hard code the expected response for the test.
1354 if args[1] == EXPECTED_RESPONSE:
1355 self.push('235 Ok')
1356 return
1357 self.push('571 Bad authentication')
1358
1359class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1360 channel_class = SimSMTPAUTHInitialResponseChannel
1361
1362
Barry Warsawc5ea7542015-07-09 10:39:55 -04001363class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1364 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001365 self.thread_key = threading_setup()
Barry Warsawc5ea7542015-07-09 10:39:55 -04001366 self.real_getfqdn = socket.getfqdn
1367 socket.getfqdn = mock_socket.getfqdn
1368 self.serv_evt = threading.Event()
1369 self.client_evt = threading.Event()
1370 # Pick a random unused port by passing 0 for the port number
1371 self.serv = SimSMTPAUTHInitialResponseServer(
1372 (HOST, 0), ('nowhere', -1), decode_data=True)
1373 # Keep a note of what port was assigned
1374 self.port = self.serv.socket.getsockname()[1]
1375 serv_args = (self.serv, self.serv_evt, self.client_evt)
1376 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1377 self.thread.start()
1378
1379 # wait until server thread has assigned a port number
1380 self.serv_evt.wait()
1381 self.serv_evt.clear()
1382
1383 def tearDown(self):
1384 socket.getfqdn = self.real_getfqdn
1385 # indicate that the client is finished
1386 self.client_evt.set()
1387 # wait for the server thread to terminate
1388 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001389 join_thread(self.thread)
1390 del self.thread
1391 self.doCleanups()
1392 threading_cleanup(*self.thread_key)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001393
1394 def testAUTH_PLAIN_initial_response_login(self):
1395 self.serv.add_feature('AUTH PLAIN')
1396 smtp = smtplib.SMTP(HOST, self.port,
1397 local_hostname='localhost', timeout=15)
1398 smtp.login('psu', 'doesnotexist')
1399 smtp.close()
1400
1401 def testAUTH_PLAIN_initial_response_auth(self):
1402 self.serv.add_feature('AUTH PLAIN')
1403 smtp = smtplib.SMTP(HOST, self.port,
1404 local_hostname='localhost', timeout=15)
1405 smtp.user = 'psu'
1406 smtp.password = 'doesnotexist'
1407 code, response = smtp.auth('plain', smtp.auth_plain)
1408 smtp.close()
1409 self.assertEqual(code, 235)
1410
1411
Guido van Rossumd8faa362007-04-27 19:54:29 +00001412if __name__ == '__main__':
chason48ed88a2018-07-26 04:01:28 +09001413 unittest.main()