blob: bacfbdfe51419eb3d84afc29b5071afaa025b0cf [file] [log] [blame]
Guido van Rossum806c2462007-08-06 23:33:07 +00001import asyncore
R. David Murray7dff9e02010-11-08 17:15:13 +00002import email.mime.text
Guido van Rossum04110fb2007-08-24 16:32:05 +00003import email.utils
Guido van Rossumd8faa362007-04-27 19:54:29 +00004import socket
Guido van Rossum806c2462007-08-06 23:33:07 +00005import smtpd
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import smtplib
Guido van Rossum806c2462007-08-06 23:33:07 +00007import io
R. David Murray7dff9e02010-11-08 17:15:13 +00008import re
Guido van Rossum806c2462007-08-06 23:33:07 +00009import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import time
Guido van Rossum806c2462007-08-06 23:33:07 +000011import select
Guido van Rossumd8faa362007-04-27 19:54:29 +000012
Victor Stinner45df8202010-04-28 22:31:17 +000013import unittest
Richard Jones64b02de2010-08-03 06:39:33 +000014from test import support, mock_socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000015
Victor Stinner45df8202010-04-28 22:31:17 +000016try:
17 import threading
18except ImportError:
19 threading = None
20
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021HOST = support.HOST
Guido van Rossumd8faa362007-04-27 19:54:29 +000022
Josiah Carlsond74900e2008-07-07 04:15:08 +000023if sys.platform == 'darwin':
24 # select.poll returns a select.POLLHUP at the end of the tests
25 # on darwin, so just ignore it
26 def handle_expt(self):
27 pass
28 smtpd.SMTPChannel.handle_expt = handle_expt
29
30
Christian Heimes5e696852008-04-09 08:37:03 +000031def server(evt, buf, serv):
Christian Heimes380f7f22008-02-28 11:19:05 +000032 serv.listen(5)
33 evt.set()
Guido van Rossumd8faa362007-04-27 19:54:29 +000034 try:
35 conn, addr = serv.accept()
36 except socket.timeout:
37 pass
38 else:
Guido van Rossum806c2462007-08-06 23:33:07 +000039 n = 500
40 while buf and n > 0:
41 r, w, e = select.select([], [conn], [])
42 if w:
43 sent = conn.send(buf)
44 buf = buf[sent:]
45
46 n -= 1
Guido van Rossum806c2462007-08-06 23:33:07 +000047
Guido van Rossumd8faa362007-04-27 19:54:29 +000048 conn.close()
49 finally:
50 serv.close()
51 evt.set()
52
Victor Stinner45df8202010-04-28 22:31:17 +000053class GeneralTests(unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000054
55 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +000056 smtplib.socket = mock_socket
57 self.port = 25
Guido van Rossumd8faa362007-04-27 19:54:29 +000058
59 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +000060 smtplib.socket = socket
Guido van Rossumd8faa362007-04-27 19:54:29 +000061
R. David Murray7dff9e02010-11-08 17:15:13 +000062 # This method is no longer used but is retained for backward compatibility,
63 # so test to make sure it still works.
64 def testQuoteData(self):
65 teststr = "abc\n.jkl\rfoo\r\n..blue"
66 expected = "abc\r\n..jkl\r\nfoo\r\n...blue"
67 self.assertEqual(expected, smtplib.quotedata(teststr))
68
Guido van Rossum806c2462007-08-06 23:33:07 +000069 def testBasic1(self):
Richard Jones64b02de2010-08-03 06:39:33 +000070 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossumd8faa362007-04-27 19:54:29 +000071 # connects
Christian Heimes5e696852008-04-09 08:37:03 +000072 smtp = smtplib.SMTP(HOST, self.port)
Georg Brandlf78e02b2008-06-10 17:40:04 +000073 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000074
Guido van Rossum806c2462007-08-06 23:33:07 +000075 def testBasic2(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000076 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000077 # connects, include port in host name
Christian Heimes5e696852008-04-09 08:37:03 +000078 smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
Georg Brandlf78e02b2008-06-10 17:40:04 +000079 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000080
81 def testLocalHostName(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000082 mock_socket.reply_with(b"220 Hola mundo")
Guido van Rossum806c2462007-08-06 23:33:07 +000083 # check that supplied local_hostname is used
Christian Heimes5e696852008-04-09 08:37:03 +000084 smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
Guido van Rossum806c2462007-08-06 23:33:07 +000085 self.assertEqual(smtp.local_hostname, "testhost")
Georg Brandlf78e02b2008-06-10 17:40:04 +000086 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +000087
Guido van Rossumd8faa362007-04-27 19:54:29 +000088 def testTimeoutDefault(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +000089 mock_socket.reply_with(b"220 Hola mundo")
Richard Jones64b02de2010-08-03 06:39:33 +000090 self.assertTrue(mock_socket.getdefaulttimeout() is None)
91 mock_socket.setdefaulttimeout(30)
92 self.assertEqual(mock_socket.getdefaulttimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +000093 try:
94 smtp = smtplib.SMTP(HOST, self.port)
95 finally:
Richard Jones64b02de2010-08-03 06:39:33 +000096 mock_socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +000098 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000099
100 def testTimeoutNone(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000101 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000102 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000103 socket.setdefaulttimeout(30)
104 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000105 smtp = smtplib.SMTP(HOST, self.port, timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000107 socket.setdefaulttimeout(None)
108 self.assertTrue(smtp.sock.gettimeout() is None)
109 smtp.close()
110
111 def testTimeoutValue(self):
Richard Jones6a9e6bb2010-08-04 12:27:36 +0000112 mock_socket.reply_with(b"220 Hola mundo")
Georg Brandlf78e02b2008-06-10 17:40:04 +0000113 smtp = smtplib.SMTP(HOST, self.port, timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114 self.assertEqual(smtp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000115 smtp.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000116
117
Guido van Rossum04110fb2007-08-24 16:32:05 +0000118# Test server thread using the specified SMTP server class
Christian Heimes5e696852008-04-09 08:37:03 +0000119def debugging_server(serv, serv_evt, client_evt):
Christian Heimes380f7f22008-02-28 11:19:05 +0000120 serv_evt.set()
Guido van Rossum806c2462007-08-06 23:33:07 +0000121
122 try:
123 if hasattr(select, 'poll'):
124 poll_fun = asyncore.poll2
125 else:
126 poll_fun = asyncore.poll
127
128 n = 1000
129 while asyncore.socket_map and n > 0:
130 poll_fun(0.01, asyncore.socket_map)
131
132 # when the client conversation is finished, it will
133 # set client_evt, and it's then ok to kill the server
Benjamin Peterson672b8032008-06-11 19:14:14 +0000134 if client_evt.is_set():
Guido van Rossum806c2462007-08-06 23:33:07 +0000135 serv.close()
136 break
137
138 n -= 1
139
140 except socket.timeout:
141 pass
142 finally:
Benjamin Peterson672b8032008-06-11 19:14:14 +0000143 if not client_evt.is_set():
Christian Heimes380f7f22008-02-28 11:19:05 +0000144 # allow some time for the client to read the result
145 time.sleep(0.5)
146 serv.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000147 asyncore.close_all()
Guido van Rossum806c2462007-08-06 23:33:07 +0000148 serv_evt.set()
149
150MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
151MSG_END = '------------ END MESSAGE ------------\n'
152
Guido van Rossum04110fb2007-08-24 16:32:05 +0000153# NOTE: Some SMTP objects in the tests below are created with a non-default
154# local_hostname argument to the constructor, since (on some systems) the FQDN
155# lookup caused by the default local_hostname sometimes takes so long that the
Guido van Rossum806c2462007-08-06 23:33:07 +0000156# test server times out, causing the test to fail.
Guido van Rossum04110fb2007-08-24 16:32:05 +0000157
158# Test behavior of smtpd.DebuggingServer
Victor Stinner45df8202010-04-28 22:31:17 +0000159@unittest.skipUnless(threading, 'Threading required for this test.')
160class DebuggingServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000161
R. David Murray7dff9e02010-11-08 17:15:13 +0000162 maxDiff = None
163
Guido van Rossum806c2462007-08-06 23:33:07 +0000164 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000165 self.real_getfqdn = socket.getfqdn
166 socket.getfqdn = mock_socket.getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000167 # temporarily replace sys.stdout to capture DebuggingServer output
168 self.old_stdout = sys.stdout
169 self.output = io.StringIO()
170 sys.stdout = self.output
171
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000172 self._threads = support.threading_setup()
Guido van Rossum806c2462007-08-06 23:33:07 +0000173 self.serv_evt = threading.Event()
174 self.client_evt = threading.Event()
R. David Murray7dff9e02010-11-08 17:15:13 +0000175 # Capture SMTPChannel debug output
176 self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
177 smtpd.DEBUGSTREAM = io.StringIO()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000178 # Pick a random unused port by passing 0 for the port number
179 self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
180 # Keep a note of what port was assigned
181 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000182 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000183 self.thread = threading.Thread(target=debugging_server, args=serv_args)
184 self.thread.start()
Guido van Rossum806c2462007-08-06 23:33:07 +0000185
186 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000187 self.serv_evt.wait()
188 self.serv_evt.clear()
Guido van Rossum806c2462007-08-06 23:33:07 +0000189
190 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000191 socket.getfqdn = self.real_getfqdn
Guido van Rossum806c2462007-08-06 23:33:07 +0000192 # indicate that the client is finished
193 self.client_evt.set()
194 # wait for the server thread to terminate
195 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000196 self.thread.join()
197 support.threading_cleanup(*self._threads)
Guido van Rossum806c2462007-08-06 23:33:07 +0000198 # restore sys.stdout
199 sys.stdout = self.old_stdout
R. David Murray7dff9e02010-11-08 17:15:13 +0000200 # restore DEBUGSTREAM
201 smtpd.DEBUGSTREAM.close()
202 smtpd.DEBUGSTREAM = self.old_DEBUGSTREAM
Guido van Rossum806c2462007-08-06 23:33:07 +0000203
204 def testBasic(self):
205 # connect
Christian Heimes5e696852008-04-09 08:37:03 +0000206 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000207 smtp.quit()
208
Guido van Rossum04110fb2007-08-24 16:32:05 +0000209 def testNOOP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000210 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000211 expected = (250, b'Ok')
212 self.assertEqual(smtp.noop(), expected)
213 smtp.quit()
214
215 def testRSET(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000216 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000217 expected = (250, b'Ok')
218 self.assertEqual(smtp.rset(), expected)
219 smtp.quit()
220
221 def testNotImplemented(self):
222 # EHLO isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000223 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000224 expected = (502, b'Error: command "EHLO" not implemented')
225 self.assertEqual(smtp.ehlo(), expected)
226 smtp.quit()
227
Guido van Rossum04110fb2007-08-24 16:32:05 +0000228 def testVRFY(self):
229 # VRFY isn't implemented in DebuggingServer
Christian Heimes5e696852008-04-09 08:37:03 +0000230 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000231 expected = (502, b'Error: command "VRFY" not implemented')
232 self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
233 self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
234 smtp.quit()
235
236 def testSecondHELO(self):
237 # check that a second HELO returns a message that it's a duplicate
238 # (this behavior is specific to smtpd.SMTPChannel)
Christian Heimes5e696852008-04-09 08:37:03 +0000239 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000240 smtp.helo()
241 expected = (503, b'Duplicate HELO/EHLO')
242 self.assertEqual(smtp.helo(), expected)
243 smtp.quit()
244
Guido van Rossum806c2462007-08-06 23:33:07 +0000245 def testHELP(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000246 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000247 self.assertEqual(smtp.help(), b'Error: command "HELP" not implemented')
248 smtp.quit()
249
250 def testSend(self):
251 # connect and send mail
252 m = 'A test message'
Christian Heimes5e696852008-04-09 08:37:03 +0000253 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
Guido van Rossum806c2462007-08-06 23:33:07 +0000254 smtp.sendmail('John', 'Sally', m)
Neal Norwitz25329672008-08-25 03:55:03 +0000255 # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
256 # in asyncore. This sleep might help, but should really be fixed
257 # properly by using an Event variable.
258 time.sleep(0.01)
Guido van Rossum806c2462007-08-06 23:33:07 +0000259 smtp.quit()
260
261 self.client_evt.set()
262 self.serv_evt.wait()
263 self.output.flush()
264 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
265 self.assertEqual(self.output.getvalue(), mexpect)
266
R. David Murray7dff9e02010-11-08 17:15:13 +0000267 def testSendBinary(self):
268 m = b'A test message'
269 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
270 smtp.sendmail('John', 'Sally', m)
271 # XXX (see comment in testSend)
272 time.sleep(0.01)
273 smtp.quit()
274
275 self.client_evt.set()
276 self.serv_evt.wait()
277 self.output.flush()
278 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.decode('ascii'), MSG_END)
279 self.assertEqual(self.output.getvalue(), mexpect)
280
R David Murray0f663d02011-06-09 15:05:57 -0400281 def testSendNeedingDotQuote(self):
282 # Issue 12283
283 m = '.A test\n.mes.sage.'
284 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
285 smtp.sendmail('John', 'Sally', m)
286 # XXX (see comment in testSend)
287 time.sleep(0.01)
288 smtp.quit()
289
290 self.client_evt.set()
291 self.serv_evt.wait()
292 self.output.flush()
293 mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
294 self.assertEqual(self.output.getvalue(), mexpect)
295
R. David Murray7dff9e02010-11-08 17:15:13 +0000296 def testSendMessage(self):
297 m = email.mime.text.MIMEText('A test message')
298 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
299 smtp.send_message(m, from_addr='John', to_addrs='Sally')
300 # XXX (see comment in testSend)
301 time.sleep(0.01)
302 smtp.quit()
303
304 self.client_evt.set()
305 self.serv_evt.wait()
306 self.output.flush()
307 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400308 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000309 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
310 self.assertEqual(self.output.getvalue(), mexpect)
311
312 def testSendMessageWithAddresses(self):
313 m = email.mime.text.MIMEText('A test message')
314 m['From'] = 'foo@bar.com'
315 m['To'] = 'John'
316 m['CC'] = 'Sally, Fred'
317 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
318 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
319 smtp.send_message(m)
320 # XXX (see comment in testSend)
321 time.sleep(0.01)
322 smtp.quit()
R David Murrayac4e5ab2011-07-02 21:03:19 -0400323 # make sure the Bcc header is still in the message.
324 self.assertEqual(m['Bcc'], 'John Root <root@localhost>, "Dinsdale" '
325 '<warped@silly.walks.com>')
R. David Murray7dff9e02010-11-08 17:15:13 +0000326
327 self.client_evt.set()
328 self.serv_evt.wait()
329 self.output.flush()
330 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400331 m['X-Peer'] = socket.gethostbyname('localhost')
R David Murrayac4e5ab2011-07-02 21:03:19 -0400332 # The Bcc header should not be transmitted.
R. David Murray7dff9e02010-11-08 17:15:13 +0000333 del m['Bcc']
334 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
335 self.assertEqual(self.output.getvalue(), mexpect)
336 debugout = smtpd.DEBUGSTREAM.getvalue()
337 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000338 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000339 for addr in ('John', 'Sally', 'Fred', 'root@localhost',
340 'warped@silly.walks.com'):
341 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
342 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000343 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000344
345 def testSendMessageWithSomeAddresses(self):
346 # Make sure nothing breaks if not all of the three 'to' headers exist
347 m = email.mime.text.MIMEText('A test message')
348 m['From'] = 'foo@bar.com'
349 m['To'] = 'John, Dinsdale'
350 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
351 smtp.send_message(m)
352 # XXX (see comment in testSend)
353 time.sleep(0.01)
354 smtp.quit()
355
356 self.client_evt.set()
357 self.serv_evt.wait()
358 self.output.flush()
359 # Add the X-Peer header that DebuggingServer adds
R David Murrayb912c5a2011-05-02 08:47:24 -0400360 m['X-Peer'] = socket.gethostbyname('localhost')
R. David Murray7dff9e02010-11-08 17:15:13 +0000361 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
362 self.assertEqual(self.output.getvalue(), mexpect)
363 debugout = smtpd.DEBUGSTREAM.getvalue()
364 sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000365 self.assertRegex(debugout, sender)
R. David Murray7dff9e02010-11-08 17:15:13 +0000366 for addr in ('John', 'Dinsdale'):
367 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
368 re.MULTILINE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000369 self.assertRegex(debugout, to_addr)
R. David Murray7dff9e02010-11-08 17:15:13 +0000370
R David Murrayac4e5ab2011-07-02 21:03:19 -0400371 def testSendMessageWithSpecifiedAddresses(self):
372 # Make sure addresses specified in call override those in message.
373 m = email.mime.text.MIMEText('A test message')
374 m['From'] = 'foo@bar.com'
375 m['To'] = 'John, Dinsdale'
376 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
377 smtp.send_message(m, from_addr='joe@example.com', to_addrs='foo@example.net')
378 # XXX (see comment in testSend)
379 time.sleep(0.01)
380 smtp.quit()
381
382 self.client_evt.set()
383 self.serv_evt.wait()
384 self.output.flush()
385 # Add the X-Peer header that DebuggingServer adds
386 m['X-Peer'] = socket.gethostbyname('localhost')
387 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
388 self.assertEqual(self.output.getvalue(), mexpect)
389 debugout = smtpd.DEBUGSTREAM.getvalue()
390 sender = re.compile("^sender: joe@example.com$", re.MULTILINE)
391 self.assertRegex(debugout, sender)
392 for addr in ('John', 'Dinsdale'):
393 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
394 re.MULTILINE)
395 self.assertNotRegex(debugout, to_addr)
396 recip = re.compile(r"^recips: .*'foo@example.net'.*$", re.MULTILINE)
397 self.assertRegex(debugout, recip)
398
399 def testSendMessageWithMultipleFrom(self):
400 # Sender overrides To
401 m = email.mime.text.MIMEText('A test message')
402 m['From'] = 'Bernard, Bianca'
403 m['Sender'] = 'the_rescuers@Rescue-Aid-Society.com'
404 m['To'] = 'John, Dinsdale'
405 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
406 smtp.send_message(m)
407 # XXX (see comment in testSend)
408 time.sleep(0.01)
409 smtp.quit()
410
411 self.client_evt.set()
412 self.serv_evt.wait()
413 self.output.flush()
414 # Add the X-Peer header that DebuggingServer adds
415 m['X-Peer'] = socket.gethostbyname('localhost')
416 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
417 self.assertEqual(self.output.getvalue(), mexpect)
418 debugout = smtpd.DEBUGSTREAM.getvalue()
419 sender = re.compile("^sender: the_rescuers@Rescue-Aid-Society.com$", re.MULTILINE)
420 self.assertRegex(debugout, sender)
421 for addr in ('John', 'Dinsdale'):
422 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
423 re.MULTILINE)
424 self.assertRegex(debugout, to_addr)
425
426 def testSendMessageResent(self):
427 m = email.mime.text.MIMEText('A test message')
428 m['From'] = 'foo@bar.com'
429 m['To'] = 'John'
430 m['CC'] = 'Sally, Fred'
431 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
432 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
433 m['Resent-From'] = 'holy@grail.net'
434 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
435 m['Resent-Bcc'] = 'doe@losthope.net'
436 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
437 smtp.send_message(m)
438 # XXX (see comment in testSend)
439 time.sleep(0.01)
440 smtp.quit()
441
442 self.client_evt.set()
443 self.serv_evt.wait()
444 self.output.flush()
445 # The Resent-Bcc headers are deleted before serialization.
446 del m['Bcc']
447 del m['Resent-Bcc']
448 # Add the X-Peer header that DebuggingServer adds
449 m['X-Peer'] = socket.gethostbyname('localhost')
450 mexpect = '%s%s\n%s' % (MSG_BEGIN, m.as_string(), MSG_END)
451 self.assertEqual(self.output.getvalue(), mexpect)
452 debugout = smtpd.DEBUGSTREAM.getvalue()
453 sender = re.compile("^sender: holy@grail.net$", re.MULTILINE)
454 self.assertRegex(debugout, sender)
455 for addr in ('my_mom@great.cooker.com', 'Jeff', 'doe@losthope.net'):
456 to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
457 re.MULTILINE)
458 self.assertRegex(debugout, to_addr)
459
460 def testSendMessageMultipleResentRaises(self):
461 m = email.mime.text.MIMEText('A test message')
462 m['From'] = 'foo@bar.com'
463 m['To'] = 'John'
464 m['CC'] = 'Sally, Fred'
465 m['Bcc'] = 'John Root <root@localhost>, "Dinsdale" <warped@silly.walks.com>'
466 m['Resent-Date'] = 'Thu, 1 Jan 1970 17:42:00 +0000'
467 m['Resent-From'] = 'holy@grail.net'
468 m['Resent-To'] = 'Martha <my_mom@great.cooker.com>, Jeff'
469 m['Resent-Bcc'] = 'doe@losthope.net'
470 m['Resent-Date'] = 'Thu, 2 Jan 1970 17:42:00 +0000'
471 m['Resent-To'] = 'holy@grail.net'
472 m['Resent-From'] = 'Martha <my_mom@great.cooker.com>, Jeff'
473 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
474 with self.assertRaises(ValueError):
475 smtp.send_message(m)
476 smtp.close()
Guido van Rossum806c2462007-08-06 23:33:07 +0000477
Victor Stinner45df8202010-04-28 22:31:17 +0000478class NonConnectingTests(unittest.TestCase):
Christian Heimes380f7f22008-02-28 11:19:05 +0000479
Richard Jones64b02de2010-08-03 06:39:33 +0000480 def setUp(self):
481 smtplib.socket = mock_socket
482
483 def tearDown(self):
484 smtplib.socket = socket
485
Christian Heimes380f7f22008-02-28 11:19:05 +0000486 def testNotConnected(self):
487 # Test various operations on an unconnected SMTP object that
488 # should raise exceptions (at present the attempt in SMTP.send
489 # to reference the nonexistent 'sock' attribute of the SMTP object
490 # causes an AttributeError)
491 smtp = smtplib.SMTP()
492 self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
493 self.assertRaises(smtplib.SMTPServerDisconnected,
494 smtp.send, 'test msg')
495
496 def testNonnumericPort(self):
497 # check that non-numeric port raises socket.error
Richard Jones64b02de2010-08-03 06:39:33 +0000498 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000499 "localhost", "bogus")
Richard Jones64b02de2010-08-03 06:39:33 +0000500 self.assertRaises(mock_socket.error, smtplib.SMTP,
Christian Heimes380f7f22008-02-28 11:19:05 +0000501 "localhost:bogus")
502
503
Guido van Rossum04110fb2007-08-24 16:32:05 +0000504# test response of client to a non-successful HELO message
Victor Stinner45df8202010-04-28 22:31:17 +0000505@unittest.skipUnless(threading, 'Threading required for this test.')
506class BadHELOServerTests(unittest.TestCase):
Guido van Rossum806c2462007-08-06 23:33:07 +0000507
508 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000509 smtplib.socket = mock_socket
510 mock_socket.reply_with(b"199 no hello for you!")
Guido van Rossum806c2462007-08-06 23:33:07 +0000511 self.old_stdout = sys.stdout
512 self.output = io.StringIO()
513 sys.stdout = self.output
Richard Jones64b02de2010-08-03 06:39:33 +0000514 self.port = 25
Guido van Rossum806c2462007-08-06 23:33:07 +0000515
516 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000517 smtplib.socket = socket
Guido van Rossum806c2462007-08-06 23:33:07 +0000518 sys.stdout = self.old_stdout
519
520 def testFailingHELO(self):
521 self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
Christian Heimes5e696852008-04-09 08:37:03 +0000522 HOST, self.port, 'localhost', 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523
Guido van Rossum04110fb2007-08-24 16:32:05 +0000524
525sim_users = {'Mr.A@somewhere.com':'John A',
526 'Ms.B@somewhere.com':'Sally B',
527 'Mrs.C@somewhereesle.com':'Ruth C',
528 }
529
R. David Murraycaa27b72009-05-23 18:49:56 +0000530sim_auth = ('Mr.A@somewhere.com', 'somepassword')
R. David Murrayfb123912009-05-28 18:19:00 +0000531sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
532 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
533sim_auth_credentials = {
534 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
535 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
536 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
537 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
538 }
539sim_auth_login_password = 'C29TZXBHC3N3B3JK'
R. David Murraycaa27b72009-05-23 18:49:56 +0000540
Guido van Rossum04110fb2007-08-24 16:32:05 +0000541sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
542 'list-2':['Ms.B@somewhere.com',],
543 }
544
545# Simulated SMTP channel & server
546class SimSMTPChannel(smtpd.SMTPChannel):
R. David Murrayfb123912009-05-28 18:19:00 +0000547
R. David Murray23ddc0e2009-05-29 18:03:16 +0000548 def __init__(self, extra_features, *args, **kw):
549 self._extrafeatures = ''.join(
550 [ "250-{0}\r\n".format(x) for x in extra_features ])
R. David Murrayfb123912009-05-28 18:19:00 +0000551 super(SimSMTPChannel, self).__init__(*args, **kw)
552
Guido van Rossum04110fb2007-08-24 16:32:05 +0000553 def smtp_EHLO(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000554 resp = ('250-testhost\r\n'
555 '250-EXPN\r\n'
556 '250-SIZE 20000000\r\n'
557 '250-STARTTLS\r\n'
558 '250-DELIVERBY\r\n')
559 resp = resp + self._extrafeatures + '250 HELP'
Guido van Rossum04110fb2007-08-24 16:32:05 +0000560 self.push(resp)
561
562 def smtp_VRFY(self, arg):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000563 raw_addr = email.utils.parseaddr(arg)[1]
564 quoted_addr = smtplib.quoteaddr(arg)
565 if raw_addr in sim_users:
566 self.push('250 %s %s' % (sim_users[raw_addr], quoted_addr))
567 else:
568 self.push('550 No such user: %s' % arg)
569
570 def smtp_EXPN(self, arg):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000571 list_name = email.utils.parseaddr(arg)[1].lower()
572 if list_name in sim_lists:
573 user_list = sim_lists[list_name]
574 for n, user_email in enumerate(user_list):
575 quoted_addr = smtplib.quoteaddr(user_email)
576 if n < len(user_list) - 1:
577 self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
578 else:
579 self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
580 else:
581 self.push('550 No access for you!')
582
R. David Murraycaa27b72009-05-23 18:49:56 +0000583 def smtp_AUTH(self, arg):
R. David Murrayfb123912009-05-28 18:19:00 +0000584 if arg.strip().lower()=='cram-md5':
585 self.push('334 {}'.format(sim_cram_md5_challenge))
586 return
R. David Murraycaa27b72009-05-23 18:49:56 +0000587 mech, auth = arg.split()
R. David Murrayfb123912009-05-28 18:19:00 +0000588 mech = mech.lower()
589 if mech not in sim_auth_credentials:
R. David Murraycaa27b72009-05-23 18:49:56 +0000590 self.push('504 auth type unimplemented')
R. David Murrayfb123912009-05-28 18:19:00 +0000591 return
592 if mech == 'plain' and auth==sim_auth_credentials['plain']:
593 self.push('235 plain auth ok')
594 elif mech=='login' and auth==sim_auth_credentials['login']:
595 self.push('334 Password:')
596 else:
597 self.push('550 No access for you!')
R. David Murraycaa27b72009-05-23 18:49:56 +0000598
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000599 def handle_error(self):
600 raise
601
Guido van Rossum04110fb2007-08-24 16:32:05 +0000602
603class SimSMTPServer(smtpd.SMTPServer):
R. David Murrayfb123912009-05-28 18:19:00 +0000604
R. David Murray23ddc0e2009-05-29 18:03:16 +0000605 def __init__(self, *args, **kw):
606 self._extra_features = []
607 smtpd.SMTPServer.__init__(self, *args, **kw)
608
Giampaolo Rodolà977c7072010-10-04 21:08:36 +0000609 def handle_accepted(self, conn, addr):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000610 self._SMTPchannel = SimSMTPChannel(self._extra_features,
611 self, conn, addr)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000612
613 def process_message(self, peer, mailfrom, rcpttos, data):
614 pass
615
R. David Murrayfb123912009-05-28 18:19:00 +0000616 def add_feature(self, feature):
R. David Murray23ddc0e2009-05-29 18:03:16 +0000617 self._extra_features.append(feature)
R. David Murrayfb123912009-05-28 18:19:00 +0000618
Giampaolo Rodolàd930b632010-05-06 20:21:57 +0000619 def handle_error(self):
620 raise
621
Guido van Rossum04110fb2007-08-24 16:32:05 +0000622
623# Test various SMTP & ESMTP commands/behaviors that require a simulated server
624# (i.e., something with more features than DebuggingServer)
Victor Stinner45df8202010-04-28 22:31:17 +0000625@unittest.skipUnless(threading, 'Threading required for this test.')
626class SMTPSimTests(unittest.TestCase):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000627
628 def setUp(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000629 self.real_getfqdn = socket.getfqdn
630 socket.getfqdn = mock_socket.getfqdn
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000631 self._threads = support.threading_setup()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000632 self.serv_evt = threading.Event()
633 self.client_evt = threading.Event()
Antoine Pitrou043bad02010-04-30 23:20:15 +0000634 # Pick a random unused port by passing 0 for the port number
635 self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
636 # Keep a note of what port was assigned
637 self.port = self.serv.socket.getsockname()[1]
Christian Heimes5e696852008-04-09 08:37:03 +0000638 serv_args = (self.serv, self.serv_evt, self.client_evt)
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000639 self.thread = threading.Thread(target=debugging_server, args=serv_args)
640 self.thread.start()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000641
642 # wait until server thread has assigned a port number
Christian Heimes380f7f22008-02-28 11:19:05 +0000643 self.serv_evt.wait()
644 self.serv_evt.clear()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000645
646 def tearDown(self):
Richard Jones64b02de2010-08-03 06:39:33 +0000647 socket.getfqdn = self.real_getfqdn
Guido van Rossum04110fb2007-08-24 16:32:05 +0000648 # indicate that the client is finished
649 self.client_evt.set()
650 # wait for the server thread to terminate
651 self.serv_evt.wait()
Antoine Pitrouc3d47722009-10-27 19:49:45 +0000652 self.thread.join()
653 support.threading_cleanup(*self._threads)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000654
655 def testBasic(self):
656 # smoke test
Christian Heimes5e696852008-04-09 08:37:03 +0000657 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000658 smtp.quit()
659
660 def testEHLO(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000661 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000662
663 # no features should be present before the EHLO
664 self.assertEqual(smtp.esmtp_features, {})
665
666 # features expected from the test server
667 expected_features = {'expn':'',
668 'size': '20000000',
669 'starttls': '',
670 'deliverby': '',
671 'help': '',
672 }
673
674 smtp.ehlo()
675 self.assertEqual(smtp.esmtp_features, expected_features)
676 for k in expected_features:
677 self.assertTrue(smtp.has_extn(k))
678 self.assertFalse(smtp.has_extn('unsupported-feature'))
679 smtp.quit()
680
681 def testVRFY(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000682 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000683
684 for email, name in sim_users.items():
685 expected_known = (250, bytes('%s %s' %
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000686 (name, smtplib.quoteaddr(email)),
687 "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000688 self.assertEqual(smtp.vrfy(email), expected_known)
689
690 u = 'nobody@nowhere.com'
Thomas Wouters74e68c72007-08-31 00:20:14 +0000691 expected_unknown = (550, ('No such user: %s'
692 % smtplib.quoteaddr(u)).encode('ascii'))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000693 self.assertEqual(smtp.vrfy(u), expected_unknown)
694 smtp.quit()
695
696 def testEXPN(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000697 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000698
699 for listname, members in sim_lists.items():
700 users = []
701 for m in members:
702 users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
Guido van Rossum5a23cc52007-08-30 14:02:43 +0000703 expected_known = (250, bytes('\n'.join(users), "ascii"))
Guido van Rossum04110fb2007-08-24 16:32:05 +0000704 self.assertEqual(smtp.expn(listname), expected_known)
705
706 u = 'PSU-Members-List'
707 expected_unknown = (550, b'No access for you!')
708 self.assertEqual(smtp.expn(u), expected_unknown)
709 smtp.quit()
710
R. David Murrayfb123912009-05-28 18:19:00 +0000711 def testAUTH_PLAIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000712 self.serv.add_feature("AUTH PLAIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000713 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murraycaa27b72009-05-23 18:49:56 +0000714
R. David Murrayfb123912009-05-28 18:19:00 +0000715 expected_auth_ok = (235, b'plain auth ok')
R. David Murraycaa27b72009-05-23 18:49:56 +0000716 self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
Benjamin Petersond094efd2010-10-31 17:15:42 +0000717 smtp.close()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000718
R. David Murrayfb123912009-05-28 18:19:00 +0000719 # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
720 # require a synchronous read to obtain the credentials...so instead smtpd
721 # sees the credential sent by smtplib's login method as an unknown command,
722 # which results in smtplib raising an auth error. Fortunately the error
723 # message contains the encoded credential, so we can partially check that it
724 # was generated correctly (partially, because the 'word' is uppercased in
725 # the error message).
726
727 def testAUTH_LOGIN(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000728 self.serv.add_feature("AUTH LOGIN")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000729 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000730 try: smtp.login(sim_auth[0], sim_auth[1])
731 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000732 self.assertIn(sim_auth_login_password, str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000733 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000734
735 def testAUTH_CRAM_MD5(self):
R. David Murrayfb123912009-05-28 18:19:00 +0000736 self.serv.add_feature("AUTH CRAM-MD5")
R. David Murray23ddc0e2009-05-29 18:03:16 +0000737 smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
R. David Murrayfb123912009-05-28 18:19:00 +0000738
739 try: smtp.login(sim_auth[0], sim_auth[1])
740 except smtplib.SMTPAuthenticationError as err:
Benjamin Peterson95951662010-10-31 17:59:20 +0000741 self.assertIn(sim_auth_credentials['cram-md5'], str(err))
Benjamin Petersond094efd2010-10-31 17:15:42 +0000742 smtp.close()
R. David Murrayfb123912009-05-28 18:19:00 +0000743
744 #TODO: add tests for correct AUTH method fallback now that the
745 #test infrastructure can support it.
746
Guido van Rossum04110fb2007-08-24 16:32:05 +0000747
Guido van Rossumd8faa362007-04-27 19:54:29 +0000748def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000749 support.run_unittest(GeneralTests, DebuggingServerTests,
Christian Heimes380f7f22008-02-28 11:19:05 +0000750 NonConnectingTests,
Guido van Rossum04110fb2007-08-24 16:32:05 +0000751 BadHELOServerTests, SMTPSimTests)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000752
753if __name__ == '__main__':
754 test_main()