blob: 067c01c10c1b36c60661499363154bb39a9d06d5 [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
Dong-hee Na65a5ce22020-01-15 06:42:09 +090059class GeneralTests:
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
Dong-hee Na65a5ce22020-01-15 06:42:09 +090078 client = self.client(HOST, self.port)
79 client.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
Dong-hee Na65a5ce22020-01-15 06:42:09 +090084 client = self.client(HOST, self.port,
85 source_address=('127.0.0.1',19876))
86 self.assertEqual(client.source_address, ('127.0.0.1', 19876))
87 client.close()
Senthil Kumaran3d23fd62011-07-30 10:56:50 +080088
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
Dong-hee Na65a5ce22020-01-15 06:42:09 +090092 client = self.client("%s:%s" % (HOST, self.port))
93 client.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
Dong-hee Na65a5ce22020-01-15 06:42:09 +090098 client = self.client(HOST, self.port, local_hostname="testhost")
99 self.assertEqual(client.local_hostname, "testhost")
100 client.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:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900108 client = self.client(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000109 finally:
Richard Jones64b02de2010-08-03 06:39:33 +0000110 mock_socket.setdefaulttimeout(None)
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900111 self.assertEqual(client.sock.gettimeout(), 30)
112 client.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:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900119 client = self.client(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)
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900122 self.assertIsNone(client.sock.gettimeout())
123 client.close()
Georg Brandlf78e02b2008-06-10 17:40:04 +0000124
Dong-hee Na62e39732020-01-14 16:49:59 +0900125 def testTimeoutZero(self):
126 mock_socket.reply_with(b"220 Hola mundo")
127 with self.assertRaises(ValueError):
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900128 self.client(HOST, self.port, timeout=0)
Dong-hee Na62e39732020-01-14 16:49:59 +0900129
Georg Brandlf78e02b2008-06-10 17:40:04 +0000130 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000131 mock_socket.reply_with(b"220 Hola mundo")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900132 client = self.client(HOST, self.port, timeout=30)
133 self.assertEqual(client.sock.gettimeout(), 30)
134 client.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000135
R David Murray0c49b892015-04-16 17:14:42 -0400136 def test_debuglevel(self):
137 mock_socket.reply_with(b"220 Hello world")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900138 client = self.client()
139 client.set_debuglevel(1)
R David Murray0c49b892015-04-16 17:14:42 -0400140 with support.captured_stderr() as stderr:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900141 client.connect(HOST, self.port)
142 client.close()
R David Murray0c49b892015-04-16 17:14:42 -0400143 expected = re.compile(r"^connect:", re.MULTILINE)
144 self.assertRegex(stderr.getvalue(), expected)
145
146 def test_debuglevel_2(self):
147 mock_socket.reply_with(b"220 Hello world")
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900148 client = self.client()
149 client.set_debuglevel(2)
R David Murray0c49b892015-04-16 17:14:42 -0400150 with support.captured_stderr() as stderr:
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900151 client.connect(HOST, self.port)
152 client.close()
R David Murray0c49b892015-04-16 17:14:42 -0400153 expected = re.compile(r"^\d{2}:\d{2}:\d{2}\.\d{6} connect: ",
154 re.MULTILINE)
155 self.assertRegex(stderr.getvalue(), expected)
156
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157
Dong-hee Na65a5ce22020-01-15 06:42:09 +0900158class SMTPGeneralTests(GeneralTests, unittest.TestCase):
159
160 client = smtplib.SMTP
161
162
163class LMTPGeneralTests(GeneralTests, unittest.TestCase):
164
165 client = smtplib.LMTP
166
167 def testTimeoutZero(self):
168 super().testTimeoutZero()
169 local_host = '/some/local/lmtp/delivery/program'
170 with self.assertRaises(ValueError):
171 self.client(local_host, timeout=0)
172
Guido van Rossum04110fb2007-08-24 16:32:05 +0000173# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000174def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000175 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000176
177 try:
178 if hasattr(select, 'poll'):
179 poll_fun = asyncore.poll2
180 else:
181 poll_fun = asyncore.poll
182
183 n = 1000
184 while asyncore.socket_map and n > 0:
185 poll_fun(0.01, asyncore.socket_map)
186
187 # when the client conversation is finished, it will
188 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000189 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000190 serv.close()
191 break
192
193 n -= 1
194
195 except socket.timeout:
196 pass
197 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000198 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000199 # allow some time for the client to read the result
200 time.sleep(0.5)
201 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000202 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000203 serv_evt.set()
204
205MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
206MSG_END = '------------ END MESSAGE ------------\n'
207
Guido van Rossum04110fb2007-08-24 16:32:05 +0000208# NOTE: Some SMTP objects in the tests below are created with a non-default
209# local_hostname argument to the constructor, since (on some systems) the FQDN
210# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000211# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000212
213# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000214class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000215
R. David Murray7dff9e02010-11-08 17:15:13 +0000216 maxDiff = None
217
Guido van Rossum806c2462007-08-06 23:33:07 +0000218 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100219 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000220 self.real_getfqdn = socket.getfqdn
221 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000222 # temporarily replace sys.stdout to capture DebuggingServer output
223 self.old_stdout = sys.stdout
224 self.output = io.StringIO()
225 sys.stdout = self.output
226
227 self.serv_evt = threading.Event()
228 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000229 # Capture SMTPChannel debug output
230 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
231 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000232 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400233 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1),
234 decode_data=True)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700235 # Keep a note of what server host and port were assigned
236 self.host, self.port = self.serv.socket.getsockname()[:2]
Christian Heimes5e696852008-04-09 08:37:03 +0000237 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000238 self.thread = threading.Thread(target=debugging_server, args=serv_args)
239 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000240
241 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000242 self.serv_evt.wait()
243 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000244
245 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000246 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000247 # indicate that the client is finished
248 self.client_evt.set()
249 # wait for the server thread to terminate
250 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100251 join_thread(self.thread)
Guido van Rossum806c2462007-08-06 23:33:07 +0000252 # restore sys.stdout
253 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000254 # restore DEBUGSTREAM
255 smtpd.DEBUGSTREAM.close()
256 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100257 del self.thread
258 self.doCleanups()
259 threading_cleanup(*self.thread_key)
Guido van Rossum806c2462007-08-06 23:33:07 +0000260
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700261 def get_output_without_xpeer(self):
262 test_output = self.output.getvalue()
263 return re.sub(r'(.*?)^X-Peer:\s*\S+\n(.*)', r'\1\2',
264 test_output, flags=re.MULTILINE|re.DOTALL)
265
Guido van Rossum806c2462007-08-06 23:33:07 +0000266 def testBasic(self):
267 # connect
Victor Stinner07871b22019-12-10 20:32:59 +0100268 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
269 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum806c2462007-08-06 23:33:07 +0000270 smtp.quit()
271
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800272 def testSourceAddress(self):
273 # connect
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700274 src_port = support.find_unused_port()
Senthil Kumaranb351a482011-07-31 09:14:17 +0800275 try:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700276 smtp = smtplib.SMTP(self.host, self.port, local_hostname='localhost',
Victor Stinner07871b22019-12-10 20:32:59 +0100277 timeout=support.LOOPBACK_TIMEOUT,
278 source_address=(self.host, src_port))
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100279 self.addCleanup(smtp.close)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700280 self.assertEqual(smtp.source_address, (self.host, src_port))
Senthil Kumaranb351a482011-07-31 09:14:17 +0800281 self.assertEqual(smtp.local_hostname, 'localhost')
282 smtp.quit()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200283 except OSError as e:
Senthil Kumaranb351a482011-07-31 09:14:17 +0800284 if e.errno == errno.EADDRINUSE:
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700285 self.skipTest("couldn't bind to source port %d" % src_port)
Senthil Kumaranb351a482011-07-31 09:14:17 +0800286 raise
Senthil Kumaran3d23fd62011-07-30 10:56:50 +0800287
Guido van Rossum04110fb2007-08-24 16:32:05 +0000288 def testNOOP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100289 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
290 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100291 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400292 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000293 self.assertEqual(smtp.noop(), expected)
294 smtp.quit()
295
296 def testRSET(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100297 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
298 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100299 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400300 expected = (250, b'OK')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000301 self.assertEqual(smtp.rset(), expected)
302 smtp.quit()
303
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400304 def testELHO(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000305 # EHLO isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100306 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
307 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100308 self.addCleanup(smtp.close)
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400309 expected = (250, b'\nSIZE 33554432\nHELP')
Guido van Rossum806c2462007-08-06 23:33:07 +0000310 self.assertEqual(smtp.ehlo(), expected)
311 smtp.quit()
312
Benjamin Peterson1eca0622013-09-29 10:46:31 -0400313 def testEXPNNotImplemented(self):
R David Murrayd1a30c92012-05-26 14:33:59 -0400314 # EXPN isn't implemented in DebuggingServer
Victor Stinner07871b22019-12-10 20:32:59 +0100315 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
316 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100317 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400318 expected = (502, b'EXPN not implemented')
319 smtp.putcmd('EXPN')
320 self.assertEqual(smtp.getreply(), expected)
321 smtp.quit()
322
323 def testVRFY(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100324 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
325 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100326 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400327 expected = (252, b'Cannot VRFY user, but will accept message ' + \
328 b'and attempt delivery')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000329 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
330 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
331 smtp.quit()
332
333 def testSecondHELO(self):
334 # check that a second HELO returns a message that it's a duplicate
335 # (this behavior is specific to smtpd.SMTPChannel)
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)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000339 smtp.helo()
340 expected = (503, b'Duplicate HELO/EHLO')
341 self.assertEqual(smtp.helo(), expected)
342 smtp.quit()
343
Guido van Rossum806c2462007-08-06 23:33:07 +0000344 def testHELP(self):
Victor Stinner07871b22019-12-10 20:32:59 +0100345 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
346 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100347 self.addCleanup(smtp.close)
R David Murrayd1a30c92012-05-26 14:33:59 -0400348 self.assertEqual(smtp.help(), b'Supported commands: EHLO HELO MAIL ' + \
349 b'RCPT DATA RSET NOOP QUIT VRFY')
Guido van Rossum806c2462007-08-06 23:33:07 +0000350 smtp.quit()
351
352 def testSend(self):
353 # connect and send mail
354 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100355 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
356 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100357 self.addCleanup(smtp.close)
Guido van Rossum806c2462007-08-06 23:33:07 +0000358 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000359 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
360 # in asyncore. This sleep might help, but should really be fixed
361 # properly by using an Event variable.
362 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000363 smtp.quit()
364
365 self.client_evt.set()
366 self.serv_evt.wait()
367 self.output.flush()
368 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
369 self.assertEqual(self.output.getvalue(), mexpect)
370
R. David Murray7dff9e02010-11-08 17:15:13 +0000371 def testSendBinary(self):
372 m = b'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100373 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
374 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100375 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000376 smtp.sendmail('John', 'Sally', m)
377 # XXX (see comment in testSend)
378 time.sleep(0.01)
379 smtp.quit()
380
381 self.client_evt.set()
382 self.serv_evt.wait()
383 self.output.flush()
384 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
385 self.assertEqual(self.output.getvalue(), mexpect)
386
R David Murray0f663d02011-06-09 15:05:57 -0400387 def testSendNeedingDotQuote(self):
388 # Issue 12283
389 m = '.A test\n.mes.sage.'
Victor Stinner07871b22019-12-10 20:32:59 +0100390 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
391 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100392 self.addCleanup(smtp.close)
R David Murray0f663d02011-06-09 15:05:57 -0400393 smtp.sendmail('John', 'Sally', m)
394 # XXX (see comment in testSend)
395 time.sleep(0.01)
396 smtp.quit()
397
398 self.client_evt.set()
399 self.serv_evt.wait()
400 self.output.flush()
401 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
402 self.assertEqual(self.output.getvalue(), mexpect)
403
R David Murray46346762011-07-18 21:38:54 -0400404 def testSendNullSender(self):
405 m = 'A test message'
Victor Stinner07871b22019-12-10 20:32:59 +0100406 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
407 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100408 self.addCleanup(smtp.close)
R David Murray46346762011-07-18 21:38:54 -0400409 smtp.sendmail('<>', 'Sally', m)
410 # XXX (see comment in testSend)
411 time.sleep(0.01)
412 smtp.quit()
413
414 self.client_evt.set()
415 self.serv_evt.wait()
416 self.output.flush()
417 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
418 self.assertEqual(self.output.getvalue(), mexpect)
419 debugout = smtpd.DEBUGSTREAM.getvalue()
420 sender = re.compile("^sender: <>$", re.MULTILINE)
421 self.assertRegex(debugout, sender)
422
R. David Murray7dff9e02010-11-08 17:15:13 +0000423 def testSendMessage(self):
424 m = email.mime.text.MIMEText('A test message')
Victor Stinner07871b22019-12-10 20:32:59 +0100425 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
426 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100427 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000428 smtp.send_message(m, from_addr='John', to_addrs='Sally')
429 # XXX (see comment in testSend)
430 time.sleep(0.01)
431 smtp.quit()
432
433 self.client_evt.set()
434 self.serv_evt.wait()
435 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700436 # Remove the X-Peer header that DebuggingServer adds as figuring out
437 # exactly what IP address format is put there is not easy (and
438 # irrelevant to our test). Typically 127.0.0.1 or ::1, but it is
439 # not always the same as socket.gethostbyname(HOST). :(
440 test_output = self.get_output_without_xpeer()
441 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000442 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700443 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000444
445 def testSendMessageWithAddresses(self):
446 m = email.mime.text.MIMEText('A test message')
447 m['From'] = 'foo@bar.com'
448 m['To'] = 'John'
449 m['CC'] = 'Sally, Fred'
450 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
Victor Stinner07871b22019-12-10 20:32:59 +0100451 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
452 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100453 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000454 smtp.send_message(m)
455 # XXX (see comment in testSend)
456 time.sleep(0.01)
457 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400458 # make sure the Bcc header is still in the message.
459 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
460 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000461
462 self.client_evt.set()
463 self.serv_evt.wait()
464 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700465 # Remove the X-Peer header that DebuggingServer adds.
466 test_output = self.get_output_without_xpeer()
467 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400468 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000469 del m['Bcc']
470 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700471 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000472 debugout = smtpd.DEBUGSTREAM.getvalue()
473 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000474 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000475 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
476 'warped@silly.walks.com'):
477 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
478 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000479 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000480
481 def testSendMessageWithSomeAddresses(self):
482 # Make sure nothing breaks if not all of the three 'to' headers exist
483 m = email.mime.text.MIMEText('A test message')
484 m['From'] = 'foo@bar.com'
485 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100486 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
487 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100488 self.addCleanup(smtp.close)
R. David Murray7dff9e02010-11-08 17:15:13 +0000489 smtp.send_message(m)
490 # XXX (see comment in testSend)
491 time.sleep(0.01)
492 smtp.quit()
493
494 self.client_evt.set()
495 self.serv_evt.wait()
496 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700497 # Remove the X-Peer header that DebuggingServer adds.
498 test_output = self.get_output_without_xpeer()
499 del m['X-Peer']
R. David Murray7dff9e02010-11-08 17:15:13 +0000500 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700501 self.assertEqual(test_output, mexpect)
R. David Murray7dff9e02010-11-08 17:15:13 +0000502 debugout = smtpd.DEBUGSTREAM.getvalue()
503 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000504 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000505 for addr in ('John', 'Dinsdale'):
506 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
507 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000508 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000509
R David Murrayac4e5ab2011-07-02 21:03:19 -0400510 def testSendMessageWithSpecifiedAddresses(self):
511 # Make sure addresses specified in call override those in message.
512 m = email.mime.text.MIMEText('A test message')
513 m['From'] = 'foo@bar.com'
514 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100515 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
516 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100517 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400518 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
519 # XXX (see comment in testSend)
520 time.sleep(0.01)
521 smtp.quit()
522
523 self.client_evt.set()
524 self.serv_evt.wait()
525 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700526 # Remove the X-Peer header that DebuggingServer adds.
527 test_output = self.get_output_without_xpeer()
528 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400529 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700530 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400531 debugout = smtpd.DEBUGSTREAM.getvalue()
532 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
533 self.assertRegex(debugout, sender)
534 for addr in ('John', 'Dinsdale'):
535 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
536 re.MULTILINE)
537 self.assertNotRegex(debugout, to_addr)
538 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
539 self.assertRegex(debugout, recip)
540
541 def testSendMessageWithMultipleFrom(self):
542 # Sender overrides To
543 m = email.mime.text.MIMEText('A test message')
544 m['From'] = 'Bernard, Bianca'
545 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
546 m['To'] = 'John, Dinsdale'
Victor Stinner07871b22019-12-10 20:32:59 +0100547 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
548 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100549 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400550 smtp.send_message(m)
551 # XXX (see comment in testSend)
552 time.sleep(0.01)
553 smtp.quit()
554
555 self.client_evt.set()
556 self.serv_evt.wait()
557 self.output.flush()
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700558 # Remove the X-Peer header that DebuggingServer adds.
559 test_output = self.get_output_without_xpeer()
560 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400561 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700562 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400563 debugout = smtpd.DEBUGSTREAM.getvalue()
564 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
565 self.assertRegex(debugout, sender)
566 for addr in ('John', 'Dinsdale'):
567 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
568 re.MULTILINE)
569 self.assertRegex(debugout, to_addr)
570
571 def testSendMessageResent(self):
572 m = email.mime.text.MIMEText('A test message')
573 m['From'] = 'foo@bar.com'
574 m['To'] = 'John'
575 m['CC'] = 'Sally, Fred'
576 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
577 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
578 m['Resent-From'] = 'holy@grail.net'
579 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
580 m['Resent-Bcc'] = 'doe@losthope.net'
Victor Stinner07871b22019-12-10 20:32:59 +0100581 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
582 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100583 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400584 smtp.send_message(m)
585 # XXX (see comment in testSend)
586 time.sleep(0.01)
587 smtp.quit()
588
589 self.client_evt.set()
590 self.serv_evt.wait()
591 self.output.flush()
592 # The Resent-Bcc headers are deleted before serialization.
593 del m['Bcc']
594 del m['Resent-Bcc']
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700595 # Remove the X-Peer header that DebuggingServer adds.
596 test_output = self.get_output_without_xpeer()
597 del m['X-Peer']
R David Murrayac4e5ab2011-07-02 21:03:19 -0400598 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
Gregory P. Smithefb1d0a2017-09-09 00:30:15 -0700599 self.assertEqual(test_output, mexpect)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400600 debugout = smtpd.DEBUGSTREAM.getvalue()
601 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
602 self.assertRegex(debugout, sender)
603 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
604 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
605 re.MULTILINE)
606 self.assertRegex(debugout, to_addr)
607
608 def testSendMessageMultipleResentRaises(self):
609 m = email.mime.text.MIMEText('A test message')
610 m['From'] = 'foo@bar.com'
611 m['To'] = 'John'
612 m['CC'] = 'Sally, Fred'
613 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
614 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
615 m['Resent-From'] = 'holy@grail.net'
616 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
617 m['Resent-Bcc'] = 'doe@losthope.net'
618 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
619 m['Resent-To'] = 'holy@grail.net'
620 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
Victor Stinner07871b22019-12-10 20:32:59 +0100621 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
622 timeout=support.LOOPBACK_TIMEOUT)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100623 self.addCleanup(smtp.close)
R David Murrayac4e5ab2011-07-02 21:03:19 -0400624 with self.assertRaises(ValueError):
625 smtp.send_message(m)
626 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000627
Victor Stinner45df8202010-04-28 22:31:17 +0000628class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000629
630 def testNotConnected(self):
631 # Test various operations on an unconnected SMTP object that
632 # should raise exceptions (at present the attempt in SMTP.send
633 # to reference the nonexistent 'sock' attribute of the SMTP object
634 # causes an AttributeError)
635 smtp = smtplib.SMTP()
636 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
637 self.assertRaises(smtplib.SMTPServerDisconnected,
638 smtp.send, 'test msg')
639
640 def testNonnumericPort(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +0200641 # check that non-numeric port raises OSError
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200642 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000643 "localhost", "bogus")
Andrew Svetlov2ade6f22012-12-17 18:57:16 +0200644 self.assertRaises(OSError, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000645 "localhost:bogus")
646
Romuald Brunet7b313972018-10-09 16:31:55 +0200647 def testSockAttributeExists(self):
648 # check that sock attribute is present outside of a connect() call
649 # (regression test, the previous behavior raised an
650 # AttributeError: 'SMTP' object has no attribute 'sock')
651 with smtplib.SMTP() as smtp:
652 self.assertIsNone(smtp.sock)
653
Christian Heimes380f7f22008-02-28 11:19:05 +0000654
Pablo Aguiard5fbe9b2018-09-08 00:04:48 +0200655class DefaultArgumentsTests(unittest.TestCase):
656
657 def setUp(self):
658 self.msg = EmailMessage()
659 self.msg['From'] = 'Páolo <főo@bar.com>'
660 self.smtp = smtplib.SMTP()
661 self.smtp.ehlo = Mock(return_value=(200, 'OK'))
662 self.smtp.has_extn, self.smtp.sendmail = Mock(), Mock()
663
664 def testSendMessage(self):
665 expected_mail_options = ('SMTPUTF8', 'BODY=8BITMIME')
666 self.smtp.send_message(self.msg)
667 self.smtp.send_message(self.msg)
668 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
669 expected_mail_options)
670 self.assertEqual(self.smtp.sendmail.call_args_list[1][0][3],
671 expected_mail_options)
672
673 def testSendMessageWithMailOptions(self):
674 mail_options = ['STARTTLS']
675 expected_mail_options = ('STARTTLS', 'SMTPUTF8', 'BODY=8BITMIME')
676 self.smtp.send_message(self.msg, None, None, mail_options)
677 self.assertEqual(mail_options, ['STARTTLS'])
678 self.assertEqual(self.smtp.sendmail.call_args_list[0][0][3],
679 expected_mail_options)
680
681
Guido van Rossum04110fb2007-08-24 16:32:05 +0000682# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000683class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000684
685 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000686 smtplib.socket = mock_socket
687 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000688 self.old_stdout = sys.stdout
689 self.output = io.StringIO()
690 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000691 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000692
693 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000694 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000695 sys.stdout = self.old_stdout
696
697 def testFailingHELO(self):
698 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000699 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700
Guido van Rossum04110fb2007-08-24 16:32:05 +0000701
Georg Brandlb38b5c42014-02-10 22:11:21 +0100702class TooLongLineTests(unittest.TestCase):
703 respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
704
705 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100706 self.thread_key = threading_setup()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100707 self.old_stdout = sys.stdout
708 self.output = io.StringIO()
709 sys.stdout = self.output
710
711 self.evt = threading.Event()
712 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
713 self.sock.settimeout(15)
714 self.port = support.bind_port(self.sock)
715 servargs = (self.evt, self.respdata, self.sock)
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100716 self.thread = threading.Thread(target=server, args=servargs)
717 self.thread.start()
Georg Brandlb38b5c42014-02-10 22:11:21 +0100718 self.evt.wait()
719 self.evt.clear()
720
721 def tearDown(self):
722 self.evt.wait()
723 sys.stdout = self.old_stdout
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100724 join_thread(self.thread)
725 del self.thread
726 self.doCleanups()
727 threading_cleanup(*self.thread_key)
Georg Brandlb38b5c42014-02-10 22:11:21 +0100728
729 def testLineTooLong(self):
730 self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
731 HOST, self.port, 'localhost', 3)
732
733
Guido van Rossum04110fb2007-08-24 16:32:05 +0000734sim_users = {'Mr.A@somewhere.com':'John A',
R David Murray46346762011-07-18 21:38:54 -0400735 'Ms.B@xn--fo-fka.com':'Sally B',
Guido van Rossum04110fb2007-08-24 16:32:05 +0000736 'Mrs.C@somewhereesle.com':'Ruth C',
737 }
738
R. David Murraycaa27b72009-05-23 18:49:56 +0000739sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000740sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
741 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
Guido van Rossum04110fb2007-08-24 16:32:05 +0000742sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
R David Murray46346762011-07-18 21:38:54 -0400743 'list-2':['Ms.B@xn--fo-fka.com',],
Guido van Rossum04110fb2007-08-24 16:32:05 +0000744 }
745
746# Simulated SMTP channel & server
R David Murrayb0deeb42015-11-08 01:03:52 -0500747class ResponseException(Exception): pass
Guido van Rossum04110fb2007-08-24 16:32:05 +0000748class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000749
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400750 quit_response = None
R David Murrayd312c742013-03-20 20:36:14 -0400751 mail_response = None
752 rcpt_response = None
753 data_response = None
754 rcpt_count = 0
755 rset_count = 0
R David Murrayafb151a2014-04-14 18:21:38 -0400756 disconnect = 0
R David Murrayb0deeb42015-11-08 01:03:52 -0500757 AUTH = 99 # Add protocol state to enable auth testing.
758 authenticated_user = None
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400759
R. David Murray23ddc0e2009-05-29 18:03:16 +0000760 def __init__(self, extra_features, *args, **kw):
761 self._extrafeatures = ''.join(
762 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000763 super(SimSMTPChannel, self).__init__(*args, **kw)
764
R David Murrayb0deeb42015-11-08 01:03:52 -0500765 # AUTH related stuff. It would be nice if support for this were in smtpd.
766 def found_terminator(self):
767 if self.smtp_state == self.AUTH:
768 line = self._emptystring.join(self.received_lines)
769 print('Data:', repr(line), file=smtpd.DEBUGSTREAM)
770 self.received_lines = []
771 try:
772 self.auth_object(line)
773 except ResponseException as e:
774 self.smtp_state = self.COMMAND
775 self.push('%s %s' % (e.smtp_code, e.smtp_error))
776 return
777 super().found_terminator()
778
779
780 def smtp_AUTH(self, arg):
781 if not self.seen_greeting:
782 self.push('503 Error: send EHLO first')
783 return
784 if not self.extended_smtp or 'AUTH' not in self._extrafeatures:
785 self.push('500 Error: command "AUTH" not recognized')
786 return
787 if self.authenticated_user is not None:
788 self.push(
789 '503 Bad sequence of commands: already authenticated')
790 return
791 args = arg.split()
792 if len(args) not in [1, 2]:
793 self.push('501 Syntax: AUTH <mechanism> [initial-response]')
794 return
795 auth_object_name = '_auth_%s' % args[0].lower().replace('-', '_')
796 try:
797 self.auth_object = getattr(self, auth_object_name)
798 except AttributeError:
799 self.push('504 Command parameter not implemented: unsupported '
800 ' authentication mechanism {!r}'.format(auth_object_name))
801 return
802 self.smtp_state = self.AUTH
803 self.auth_object(args[1] if len(args) == 2 else None)
804
805 def _authenticated(self, user, valid):
806 if valid:
807 self.authenticated_user = user
808 self.push('235 Authentication Succeeded')
809 else:
810 self.push('535 Authentication credentials invalid')
811 self.smtp_state = self.COMMAND
812
813 def _decode_base64(self, string):
814 return base64.decodebytes(string.encode('ascii')).decode('utf-8')
815
816 def _auth_plain(self, arg=None):
817 if arg is None:
818 self.push('334 ')
819 else:
820 logpass = self._decode_base64(arg)
821 try:
822 *_, user, password = logpass.split('\0')
823 except ValueError as e:
824 self.push('535 Splitting response {!r} into user and password'
825 ' failed: {}'.format(logpass, e))
826 return
827 self._authenticated(user, password == sim_auth[1])
828
829 def _auth_login(self, arg=None):
830 if arg is None:
831 # base64 encoded 'Username:'
832 self.push('334 VXNlcm5hbWU6')
833 elif not hasattr(self, '_auth_login_user'):
834 self._auth_login_user = self._decode_base64(arg)
835 # base64 encoded 'Password:'
836 self.push('334 UGFzc3dvcmQ6')
837 else:
838 password = self._decode_base64(arg)
839 self._authenticated(self._auth_login_user, password == sim_auth[1])
840 del self._auth_login_user
841
842 def _auth_cram_md5(self, arg=None):
843 if arg is None:
844 self.push('334 {}'.format(sim_cram_md5_challenge))
845 else:
846 logpass = self._decode_base64(arg)
847 try:
848 user, hashed_pass = logpass.split()
849 except ValueError as e:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200850 self.push('535 Splitting response {!r} into user and password '
R David Murrayb0deeb42015-11-08 01:03:52 -0500851 'failed: {}'.format(logpass, e))
852 return False
853 valid_hashed_pass = hmac.HMAC(
854 sim_auth[1].encode('ascii'),
855 self._decode_base64(sim_cram_md5_challenge).encode('ascii'),
856 'md5').hexdigest()
857 self._authenticated(user, hashed_pass == valid_hashed_pass)
858 # end AUTH related stuff.
859
Guido van Rossum04110fb2007-08-24 16:32:05 +0000860 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000861 resp = ('250-testhost\r\n'
862 '250-EXPN\r\n'
863 '250-SIZE 20000000\r\n'
864 '250-STARTTLS\r\n'
865 '250-DELIVERBY\r\n')
866 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000867 self.push(resp)
R David Murrayf1a40b42013-03-20 21:12:17 -0400868 self.seen_greeting = arg
869 self.extended_smtp = True
Guido van Rossum04110fb2007-08-24 16:32:05 +0000870
871 def smtp_VRFY(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400872 # For max compatibility smtplib should be sending the raw address.
873 if arg in sim_users:
874 self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000875 else:
876 self.push('550 No such user: %s' % arg)
877
878 def smtp_EXPN(self, arg):
R David Murray46346762011-07-18 21:38:54 -0400879 list_name = arg.lower()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000880 if list_name in sim_lists:
881 user_list = sim_lists[list_name]
882 for n, user_email in enumerate(user_list):
883 quoted_addr = smtplib.quoteaddr(user_email)
884 if n < len(user_list) - 1:
885 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
886 else:
887 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
888 else:
889 self.push('550 No access for you!')
890
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400891 def smtp_QUIT(self, arg):
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400892 if self.quit_response is None:
893 super(SimSMTPChannel, self).smtp_QUIT(arg)
894 else:
895 self.push(self.quit_response)
896 self.close_when_done()
897
R David Murrayd312c742013-03-20 20:36:14 -0400898 def smtp_MAIL(self, arg):
899 if self.mail_response is None:
900 super().smtp_MAIL(arg)
901 else:
902 self.push(self.mail_response)
R David Murrayafb151a2014-04-14 18:21:38 -0400903 if self.disconnect:
904 self.close_when_done()
R David Murrayd312c742013-03-20 20:36:14 -0400905
906 def smtp_RCPT(self, arg):
907 if self.rcpt_response is None:
908 super().smtp_RCPT(arg)
909 return
R David Murrayd312c742013-03-20 20:36:14 -0400910 self.rcpt_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400911 self.push(self.rcpt_response[self.rcpt_count-1])
R David Murrayd312c742013-03-20 20:36:14 -0400912
913 def smtp_RSET(self, arg):
R David Murrayd312c742013-03-20 20:36:14 -0400914 self.rset_count += 1
R David Murray03b01162013-03-20 22:11:40 -0400915 super().smtp_RSET(arg)
R David Murrayd312c742013-03-20 20:36:14 -0400916
917 def smtp_DATA(self, arg):
918 if self.data_response is None:
919 super().smtp_DATA(arg)
920 else:
921 self.push(self.data_response)
922
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000923 def handle_error(self):
924 raise
925
Guido van Rossum04110fb2007-08-24 16:32:05 +0000926
927class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000928
R David Murrayd312c742013-03-20 20:36:14 -0400929 channel_class = SimSMTPChannel
Barry Warsaw1f5c9582011-03-15 15:04:44 -0400930
R. David Murray23ddc0e2009-05-29 18:03:16 +0000931 def __init__(self, *args, **kw):
932 self._extra_features = []
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100933 self._addresses = {}
R. David Murray23ddc0e2009-05-29 18:03:16 +0000934 smtpd.SMTPServer.__init__(self, *args, **kw)
935
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000936 def handle_accepted(self, conn, addr):
R David Murrayf1a40b42013-03-20 21:12:17 -0400937 self._SMTPchannel = self.channel_class(
R David Murray1144da52014-06-11 12:27:40 -0400938 self._extra_features, self, conn, addr,
939 decode_data=self._decode_data)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000940
941 def process_message(self, peer, mailfrom, rcpttos, data):
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +0100942 self._addresses['from'] = mailfrom
943 self._addresses['tos'] = rcpttos
Guido van Rossum04110fb2007-08-24 16:32:05 +0000944
R. David Murrayfb123912009-05-28 18:19:00 +0000945 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000946 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000947
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000948 def handle_error(self):
949 raise
950
Guido van Rossum04110fb2007-08-24 16:32:05 +0000951
952# Test various SMTP & ESMTP commands/behaviors that require a simulated server
953# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000954class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000955
956 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100957 self.thread_key = threading_setup()
Richard Jones64b02de2010-08-03 06:39:33 +0000958 self.real_getfqdn = socket.getfqdn
959 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000960 self.serv_evt = threading.Event()
961 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000962 # Pick a random unused port by passing 0 for the port number
R David Murray1144da52014-06-11 12:27:40 -0400963 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1), decode_data=True)
Antoine Pitrou043bad02010-04-30 23:20:15 +0000964 # Keep a note of what port was assigned
965 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000966 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000967 self.thread = threading.Thread(target=debugging_server, args=serv_args)
968 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000969
970 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000971 self.serv_evt.wait()
972 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000973
974 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000975 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000976 # indicate that the client is finished
977 self.client_evt.set()
978 # wait for the server thread to terminate
979 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +0100980 join_thread(self.thread)
981 del self.thread
982 self.doCleanups()
983 threading_cleanup(*self.thread_key)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000984
985 def testBasic(self):
986 # smoke test
Victor Stinner7772b1a2019-12-11 22:17:04 +0100987 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
988 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000989 smtp.quit()
990
991 def testEHLO(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +0100992 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
993 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000994
995 # no features should be present before the EHLO
996 self.assertEqual(smtp.esmtp_features, {})
997
998 # features expected from the test server
999 expected_features = {'expn':'',
1000 'size': '20000000',
1001 'starttls': '',
1002 'deliverby': '',
1003 'help': '',
1004 }
1005
1006 smtp.ehlo()
1007 self.assertEqual(smtp.esmtp_features, expected_features)
1008 for k in expected_features:
1009 self.assertTrue(smtp.has_extn(k))
1010 self.assertFalse(smtp.has_extn('unsupported-feature'))
1011 smtp.quit()
1012
1013 def testVRFY(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001014 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1015 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001016
Barry Warsawc5ea7542015-07-09 10:39:55 -04001017 for addr_spec, name in sim_users.items():
Guido van Rossum04110fb2007-08-24 16:32:05 +00001018 expected_known = (250, bytes('%s %s' %
Barry Warsawc5ea7542015-07-09 10:39:55 -04001019 (name, smtplib.quoteaddr(addr_spec)),
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001020 "ascii"))
Barry Warsawc5ea7542015-07-09 10:39:55 -04001021 self.assertEqual(smtp.vrfy(addr_spec), expected_known)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001022
1023 u = 'nobody@nowhere.com'
R David Murray46346762011-07-18 21:38:54 -04001024 expected_unknown = (550, ('No such user: %s' % u).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001025 self.assertEqual(smtp.vrfy(u), expected_unknown)
1026 smtp.quit()
1027
1028 def testEXPN(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001029 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1030 timeout=support.LOOPBACK_TIMEOUT)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001031
1032 for listname, members in sim_lists.items():
1033 users = []
1034 for m in members:
1035 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +00001036 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +00001037 self.assertEqual(smtp.expn(listname), expected_known)
1038
1039 u = 'PSU-Members-List'
1040 expected_unknown = (550, b'No access for you!')
1041 self.assertEqual(smtp.expn(u), expected_unknown)
1042 smtp.quit()
1043
R David Murray76e13c12014-07-03 14:47:46 -04001044 def testAUTH_PLAIN(self):
1045 self.serv.add_feature("AUTH PLAIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001046 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1047 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001048 resp = smtp.login(sim_auth[0], sim_auth[1])
1049 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001050 smtp.close()
1051
R. David Murrayfb123912009-05-28 18:19:00 +00001052 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001053 self.serv.add_feature("AUTH LOGIN")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001054 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1055 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001056 resp = smtp.login(sim_auth[0], sim_auth[1])
1057 self.assertEqual(resp, (235, b'Authentication Succeeded'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001058 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001059
Christian Heimesc64a1a62019-09-25 16:30:20 +02001060 @requires_hashdigest('md5')
R. David Murrayfb123912009-05-28 18:19:00 +00001061 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +00001062 self.serv.add_feature("AUTH CRAM-MD5")
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'))
Benjamin Petersond094efd2010-10-31 17:15:42 +00001067 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +00001068
Andrew Kuchling78591822013-11-11 14:03:23 -05001069 def testAUTH_multiple(self):
1070 # Test that multiple authentication methods are tried.
1071 self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5")
Victor Stinner7772b1a2019-12-11 22:17:04 +01001072 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1073 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001074 resp = smtp.login(sim_auth[0], sim_auth[1])
1075 self.assertEqual(resp, (235, b'Authentication Succeeded'))
R David Murray76e13c12014-07-03 14:47:46 -04001076 smtp.close()
1077
1078 def test_auth_function(self):
Christian Heimesc64a1a62019-09-25 16:30:20 +02001079 supported = {'PLAIN', 'LOGIN'}
1080 try:
1081 hashlib.md5()
1082 except ValueError:
1083 pass
1084 else:
1085 supported.add('CRAM-MD5')
R David Murrayb0deeb42015-11-08 01:03:52 -05001086 for mechanism in supported:
1087 self.serv.add_feature("AUTH {}".format(mechanism))
1088 for mechanism in supported:
1089 with self.subTest(mechanism=mechanism):
1090 smtp = smtplib.SMTP(HOST, self.port,
Victor Stinner7772b1a2019-12-11 22:17:04 +01001091 local_hostname='localhost',
1092 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayb0deeb42015-11-08 01:03:52 -05001093 smtp.ehlo('foo')
1094 smtp.user, smtp.password = sim_auth[0], sim_auth[1]
1095 method = 'auth_' + mechanism.lower().replace('-', '_')
1096 resp = smtp.auth(mechanism, getattr(smtp, method))
1097 self.assertEqual(resp, (235, b'Authentication Succeeded'))
1098 smtp.close()
Andrew Kuchling78591822013-11-11 14:03:23 -05001099
R David Murray0cff49f2014-08-30 16:51:59 -04001100 def test_quit_resets_greeting(self):
1101 smtp = smtplib.SMTP(HOST, self.port,
1102 local_hostname='localhost',
Victor Stinner7772b1a2019-12-11 22:17:04 +01001103 timeout=support.LOOPBACK_TIMEOUT)
R David Murray0cff49f2014-08-30 16:51:59 -04001104 code, message = smtp.ehlo()
1105 self.assertEqual(code, 250)
1106 self.assertIn('size', smtp.esmtp_features)
1107 smtp.quit()
1108 self.assertNotIn('size', smtp.esmtp_features)
1109 smtp.connect(HOST, self.port)
1110 self.assertNotIn('size', smtp.esmtp_features)
1111 smtp.ehlo_or_helo_if_needed()
1112 self.assertIn('size', smtp.esmtp_features)
1113 smtp.quit()
1114
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001115 def test_with_statement(self):
1116 with smtplib.SMTP(HOST, self.port) as smtp:
1117 code, message = smtp.noop()
1118 self.assertEqual(code, 250)
1119 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1120 with smtplib.SMTP(HOST, self.port) as smtp:
1121 smtp.close()
1122 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
1123
1124 def test_with_statement_QUIT_failure(self):
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001125 with self.assertRaises(smtplib.SMTPResponseException) as error:
1126 with smtplib.SMTP(HOST, self.port) as smtp:
1127 smtp.noop()
R David Murray6bd52022013-03-21 00:32:31 -04001128 self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001129 self.assertEqual(error.exception.smtp_code, 421)
1130 self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')
Barry Warsaw1f5c9582011-03-15 15:04:44 -04001131
R. David Murrayfb123912009-05-28 18:19:00 +00001132 #TODO: add tests for correct AUTH method fallback now that the
1133 #test infrastructure can support it.
1134
R David Murrayafb151a2014-04-14 18:21:38 -04001135 # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception
1136 def test__rest_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001137 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1138 timeout=support.LOOPBACK_TIMEOUT)
R David Murrayafb151a2014-04-14 18:21:38 -04001139 smtp.noop()
1140 self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
1141 self.serv._SMTPchannel.disconnect = True
1142 with self.assertRaises(smtplib.SMTPSenderRefused):
1143 smtp.sendmail('John', 'Sally', 'test message')
1144 self.assertIsNone(smtp.sock)
1145
R David Murrayd312c742013-03-20 20:36:14 -04001146 # Issue 5713: make sure close, not rset, is called if we get a 421 error
1147 def test_421_from_mail_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001148 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1149 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001150 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001151 self.serv._SMTPchannel.mail_response = '421 closing connection'
1152 with self.assertRaises(smtplib.SMTPSenderRefused):
1153 smtp.sendmail('John', 'Sally', 'test message')
1154 self.assertIsNone(smtp.sock)
R David Murray03b01162013-03-20 22:11:40 -04001155 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
R David Murrayd312c742013-03-20 20:36:14 -04001156
1157 def test_421_from_rcpt_cmd(self):
Victor Stinner7772b1a2019-12-11 22:17:04 +01001158 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1159 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001160 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001161 self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
1162 with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
1163 smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
1164 self.assertIsNone(smtp.sock)
1165 self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
1166 self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
1167
1168 def test_421_from_data_cmd(self):
1169 class MySimSMTPChannel(SimSMTPChannel):
1170 def found_terminator(self):
1171 if self.smtp_state == self.DATA:
1172 self.push('421 closing')
1173 else:
1174 super().found_terminator()
1175 self.serv.channel_class = MySimSMTPChannel
Victor Stinner7772b1a2019-12-11 22:17:04 +01001176 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1177 timeout=support.LOOPBACK_TIMEOUT)
R David Murray853c0f92013-03-20 21:54:05 -04001178 smtp.noop()
R David Murrayd312c742013-03-20 20:36:14 -04001179 with self.assertRaises(smtplib.SMTPDataError):
1180 smtp.sendmail('John@foo.org', ['Sally@foo.org'], 'test message')
1181 self.assertIsNone(smtp.sock)
1182 self.assertEqual(self.serv._SMTPchannel.rcpt_count, 0)
1183
R David Murraycee7cf62015-05-16 13:58:14 -04001184 def test_smtputf8_NotSupportedError_if_no_server_support(self):
1185 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001186 HOST, self.port, local_hostname='localhost',
1187 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001188 self.addCleanup(smtp.close)
1189 smtp.ehlo()
1190 self.assertTrue(smtp.does_esmtp)
1191 self.assertFalse(smtp.has_extn('smtputf8'))
1192 self.assertRaises(
1193 smtplib.SMTPNotSupportedError,
1194 smtp.sendmail,
1195 'John', 'Sally', '', mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1196 self.assertRaises(
1197 smtplib.SMTPNotSupportedError,
1198 smtp.mail, 'John', options=['BODY=8BITMIME', 'SMTPUTF8'])
1199
1200 def test_send_unicode_without_SMTPUTF8(self):
1201 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001202 HOST, self.port, local_hostname='localhost',
1203 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001204 self.addCleanup(smtp.close)
1205 self.assertRaises(UnicodeEncodeError, smtp.sendmail, 'Alice', 'Böb', '')
1206 self.assertRaises(UnicodeEncodeError, smtp.mail, 'Älice')
1207
chason48ed88a2018-07-26 04:01:28 +09001208 def test_send_message_error_on_non_ascii_addrs_if_no_smtputf8(self):
1209 # This test is located here and not in the SMTPUTF8SimTests
1210 # class because it needs a "regular" SMTP server to work
1211 msg = EmailMessage()
1212 msg['From'] = "Páolo <főo@bar.com>"
1213 msg['To'] = 'Dinsdale'
1214 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1215 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001216 HOST, self.port, local_hostname='localhost',
1217 timeout=support.LOOPBACK_TIMEOUT)
chason48ed88a2018-07-26 04:01:28 +09001218 self.addCleanup(smtp.close)
1219 with self.assertRaises(smtplib.SMTPNotSupportedError):
1220 smtp.send_message(msg)
1221
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001222 def test_name_field_not_included_in_envelop_addresses(self):
1223 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001224 HOST, self.port, local_hostname='localhost',
1225 timeout=support.LOOPBACK_TIMEOUT)
Stéphane Wirtel8d83e4b2018-01-31 01:02:51 +01001226 self.addCleanup(smtp.close)
1227
1228 message = EmailMessage()
1229 message['From'] = email.utils.formataddr(('Michaël', 'michael@example.com'))
1230 message['To'] = email.utils.formataddr(('René', 'rene@example.com'))
1231
1232 self.assertDictEqual(smtp.send_message(message), {})
1233
1234 self.assertEqual(self.serv._addresses['from'], 'michael@example.com')
1235 self.assertEqual(self.serv._addresses['tos'], ['rene@example.com'])
1236
R David Murraycee7cf62015-05-16 13:58:14 -04001237
1238class SimSMTPUTF8Server(SimSMTPServer):
1239
1240 def __init__(self, *args, **kw):
1241 # The base SMTP server turns these on automatically, but our test
1242 # server is set up to munge the EHLO response, so we need to provide
1243 # them as well. And yes, the call is to SMTPServer not SimSMTPServer.
1244 self._extra_features = ['SMTPUTF8', '8BITMIME']
1245 smtpd.SMTPServer.__init__(self, *args, **kw)
1246
1247 def handle_accepted(self, conn, addr):
1248 self._SMTPchannel = self.channel_class(
1249 self._extra_features, self, conn, addr,
1250 decode_data=self._decode_data,
1251 enable_SMTPUTF8=self.enable_SMTPUTF8,
1252 )
1253
1254 def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None,
1255 rcpt_options=None):
1256 self.last_peer = peer
1257 self.last_mailfrom = mailfrom
1258 self.last_rcpttos = rcpttos
1259 self.last_message = data
1260 self.last_mail_options = mail_options
1261 self.last_rcpt_options = rcpt_options
1262
1263
R David Murraycee7cf62015-05-16 13:58:14 -04001264class SMTPUTF8SimTests(unittest.TestCase):
1265
R David Murray83084442015-05-17 19:27:22 -04001266 maxDiff = None
1267
R David Murraycee7cf62015-05-16 13:58:14 -04001268 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001269 self.thread_key = threading_setup()
R David Murraycee7cf62015-05-16 13:58:14 -04001270 self.real_getfqdn = socket.getfqdn
1271 socket.getfqdn = mock_socket.getfqdn
1272 self.serv_evt = threading.Event()
1273 self.client_evt = threading.Event()
1274 # Pick a random unused port by passing 0 for the port number
1275 self.serv = SimSMTPUTF8Server((HOST, 0), ('nowhere', -1),
1276 decode_data=False,
1277 enable_SMTPUTF8=True)
1278 # Keep a note of what port was assigned
1279 self.port = self.serv.socket.getsockname()[1]
1280 serv_args = (self.serv, self.serv_evt, self.client_evt)
1281 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1282 self.thread.start()
1283
1284 # wait until server thread has assigned a port number
1285 self.serv_evt.wait()
1286 self.serv_evt.clear()
1287
1288 def tearDown(self):
1289 socket.getfqdn = self.real_getfqdn
1290 # indicate that the client is finished
1291 self.client_evt.set()
1292 # wait for the server thread to terminate
1293 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001294 join_thread(self.thread)
1295 del self.thread
1296 self.doCleanups()
1297 threading_cleanup(*self.thread_key)
R David Murraycee7cf62015-05-16 13:58:14 -04001298
1299 def test_test_server_supports_extensions(self):
1300 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001301 HOST, self.port, local_hostname='localhost',
1302 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001303 self.addCleanup(smtp.close)
1304 smtp.ehlo()
1305 self.assertTrue(smtp.does_esmtp)
1306 self.assertTrue(smtp.has_extn('smtputf8'))
1307
1308 def test_send_unicode_with_SMTPUTF8_via_sendmail(self):
1309 m = '¡a test message containing unicode!'.encode('utf-8')
1310 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001311 HOST, self.port, local_hostname='localhost',
1312 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001313 self.addCleanup(smtp.close)
1314 smtp.sendmail('Jőhn', 'Sálly', m,
1315 mail_options=['BODY=8BITMIME', 'SMTPUTF8'])
1316 self.assertEqual(self.serv.last_mailfrom, 'Jőhn')
1317 self.assertEqual(self.serv.last_rcpttos, ['Sálly'])
1318 self.assertEqual(self.serv.last_message, m)
1319 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1320 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1321 self.assertEqual(self.serv.last_rcpt_options, [])
1322
1323 def test_send_unicode_with_SMTPUTF8_via_low_level_API(self):
1324 m = '¡a test message containing unicode!'.encode('utf-8')
1325 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001326 HOST, self.port, local_hostname='localhost',
1327 timeout=support.LOOPBACK_TIMEOUT)
R David Murraycee7cf62015-05-16 13:58:14 -04001328 self.addCleanup(smtp.close)
1329 smtp.ehlo()
1330 self.assertEqual(
1331 smtp.mail('Jő', options=['BODY=8BITMIME', 'SMTPUTF8']),
1332 (250, b'OK'))
1333 self.assertEqual(smtp.rcpt('János'), (250, b'OK'))
1334 self.assertEqual(smtp.data(m), (250, b'OK'))
1335 self.assertEqual(self.serv.last_mailfrom, 'Jő')
1336 self.assertEqual(self.serv.last_rcpttos, ['János'])
1337 self.assertEqual(self.serv.last_message, m)
1338 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1339 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1340 self.assertEqual(self.serv.last_rcpt_options, [])
1341
R David Murray83084442015-05-17 19:27:22 -04001342 def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
1343 msg = EmailMessage()
1344 msg['From'] = "Páolo <főo@bar.com>"
1345 msg['To'] = 'Dinsdale'
1346 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
1347 # XXX I don't know why I need two \n's here, but this is an existing
1348 # bug (if it is one) and not a problem with the new functionality.
1349 msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
1350 # XXX smtpd converts received /r/n to /n, so we can't easily test that
1351 # we are successfully sending /r/n :(.
1352 expected = textwrap.dedent("""\
1353 From: Páolo <főo@bar.com>
1354 To: Dinsdale
1355 Subject: Nudge nudge, wink, wink \u1F609
1356 Content-Type: text/plain; charset="utf-8"
1357 Content-Transfer-Encoding: 8bit
1358 MIME-Version: 1.0
1359
1360 oh là là, know what I mean, know what I mean?
1361 """)
1362 smtp = smtplib.SMTP(
Victor Stinner07871b22019-12-10 20:32:59 +01001363 HOST, self.port, local_hostname='localhost',
1364 timeout=support.LOOPBACK_TIMEOUT)
R David Murray83084442015-05-17 19:27:22 -04001365 self.addCleanup(smtp.close)
1366 self.assertEqual(smtp.send_message(msg), {})
1367 self.assertEqual(self.serv.last_mailfrom, 'főo@bar.com')
1368 self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
1369 self.assertEqual(self.serv.last_message.decode(), expected)
1370 self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
1371 self.assertIn('SMTPUTF8', self.serv.last_mail_options)
1372 self.assertEqual(self.serv.last_rcpt_options, [])
1373
Guido van Rossum04110fb2007-08-24 16:32:05 +00001374
Barry Warsawc5ea7542015-07-09 10:39:55 -04001375EXPECTED_RESPONSE = encode_base64(b'\0psu\0doesnotexist', eol='')
1376
1377class SimSMTPAUTHInitialResponseChannel(SimSMTPChannel):
1378 def smtp_AUTH(self, arg):
1379 # RFC 4954's AUTH command allows for an optional initial-response.
1380 # Not all AUTH methods support this; some require a challenge. AUTH
1381 # PLAIN does those, so test that here. See issue #15014.
1382 args = arg.split()
1383 if args[0].lower() == 'plain':
1384 if len(args) == 2:
1385 # AUTH PLAIN <initial-response> with the response base 64
1386 # encoded. Hard code the expected response for the test.
1387 if args[1] == EXPECTED_RESPONSE:
1388 self.push('235 Ok')
1389 return
1390 self.push('571 Bad authentication')
1391
1392class SimSMTPAUTHInitialResponseServer(SimSMTPServer):
1393 channel_class = SimSMTPAUTHInitialResponseChannel
1394
1395
Barry Warsawc5ea7542015-07-09 10:39:55 -04001396class SMTPAUTHInitialResponseSimTests(unittest.TestCase):
1397 def setUp(self):
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001398 self.thread_key = threading_setup()
Barry Warsawc5ea7542015-07-09 10:39:55 -04001399 self.real_getfqdn = socket.getfqdn
1400 socket.getfqdn = mock_socket.getfqdn
1401 self.serv_evt = threading.Event()
1402 self.client_evt = threading.Event()
1403 # Pick a random unused port by passing 0 for the port number
1404 self.serv = SimSMTPAUTHInitialResponseServer(
1405 (HOST, 0), ('nowhere', -1), decode_data=True)
1406 # Keep a note of what port was assigned
1407 self.port = self.serv.socket.getsockname()[1]
1408 serv_args = (self.serv, self.serv_evt, self.client_evt)
1409 self.thread = threading.Thread(target=debugging_server, args=serv_args)
1410 self.thread.start()
1411
1412 # wait until server thread has assigned a port number
1413 self.serv_evt.wait()
1414 self.serv_evt.clear()
1415
1416 def tearDown(self):
1417 socket.getfqdn = self.real_getfqdn
1418 # indicate that the client is finished
1419 self.client_evt.set()
1420 # wait for the server thread to terminate
1421 self.serv_evt.wait()
Pablo Galindo5b7a2cb2018-09-08 00:15:22 +01001422 join_thread(self.thread)
1423 del self.thread
1424 self.doCleanups()
1425 threading_cleanup(*self.thread_key)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001426
1427 def testAUTH_PLAIN_initial_response_login(self):
1428 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001429 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1430 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001431 smtp.login('psu', 'doesnotexist')
1432 smtp.close()
1433
1434 def testAUTH_PLAIN_initial_response_auth(self):
1435 self.serv.add_feature('AUTH PLAIN')
Victor Stinner7772b1a2019-12-11 22:17:04 +01001436 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost',
1437 timeout=support.LOOPBACK_TIMEOUT)
Barry Warsawc5ea7542015-07-09 10:39:55 -04001438 smtp.user = 'psu'
1439 smtp.password = 'doesnotexist'
1440 code, response = smtp.auth('plain', smtp.auth_plain)
1441 smtp.close()
1442 self.assertEqual(code, 235)
1443
1444
Guido van Rossumd8faa362007-04-27 19:54:29 +00001445if __name__ == '__main__':
chason48ed88a2018-07-26 04:01:28 +09001446 unittest.main()