Index: Doc/library/smtplib.rst =================================================================== --- Doc/library/smtplib.rst (revisione 88501) +++ Doc/library/smtplib.rst (copia locale) @@ -34,6 +34,19 @@ For normal use, you should only require the initialization/connect, :meth:`sendmail`, and :meth:`quit` methods. An example is included below. + :class:`SMTP` class supports the :keyword:`with` statement. Here is a sample + on how using it: + + >>> from smtplib import SMTP + >>> with SMTP("domain.org") as smtp: + ... smtp.noop() + ... + (250, b'Ok') + >>> + + .. versionchanged:: 3.3 + Support for the :keyword:`with` statement was added. + .. class:: SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None[, timeout]) Index: Lib/smtplib.py =================================================================== --- Lib/smtplib.py (revisione 88501) +++ Lib/smtplib.py (copia locale) @@ -269,6 +269,19 @@ pass self.local_hostname = '[%s]' % addr + def __enter__(self): + return self + + def __exit__(self, *args): + try: + rc, msg = self.docmd("QUIT") + if rc != 221: + raise SMTPResponseException(errmsg) + except SMTPServerDisconnected: + pass + finally: + self.close() + def set_debuglevel(self, debuglevel): """Set the debug output level. Index: Lib/test/test_smtplib.py =================================================================== --- Lib/test/test_smtplib.py (revisione 88501) +++ Lib/test/test_smtplib.py (copia locale) @@ -115,6 +115,7 @@ smtp.close() + # Test server thread using the specified SMTP server class def debugging_server(serv, serv_evt, client_evt): serv_evt.set() @@ -620,6 +621,17 @@ self.assertIn(sim_auth_credentials['cram-md5'], str(err)) smtp.close() + def test_with_statement(self): + with smtplib.SMTP(HOST, self.port) as smtp: + print(smtp.noop()) + code = smtp.noop()[0] + self.assertEqual(code, 250) + self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo') + + with smtplib.SMTP(HOST, self.port) as smtp: + smtp.close() + self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo') + #TODO: add tests for correct AUTH method fallback now that the #test infrastructure can support it.