diff --git a/django/core/mail/backends/smtp.py b/django/core/mail/backends/smtp.py index 05006a2b17..f8392918b2 100644 --- a/django/core/mail/backends/smtp.py +++ b/django/core/mail/backends/smtp.py @@ -1,5 +1,6 @@ """SMTP email backend class.""" import smtplib +import socket import ssl import threading @@ -71,7 +72,7 @@ class EmailBackend(BaseEmailBackend): if self.username and self.password: self.connection.login(force_str(self.username), force_str(self.password)) return True - except smtplib.SMTPException: + except (smtplib.SMTPException, socket.error) as e: if not self.fail_silently: raise diff --git a/tests/mail/tests.py b/tests/mail/tests.py index e518ca46d5..1bb7236032 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -7,6 +7,7 @@ import mimetypes import os import shutil import smtpd +import socket import sys import tempfile import threading @@ -1448,6 +1449,9 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): finally: SMTP.send = send + +class SMTPNoServerTests(SimpleTestCase): + def test_send_messages_after_open_failed(self): """ send_messages() shouldn't try to send messages if open() raises an @@ -1461,6 +1465,16 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com']) self.assertEqual(backend.send_messages([email]), None) + def test_fail_silently_on_connection_error(self): + """ + A socket connection error is silenced with fail_silently=True. + """ + backend = smtp.EmailBackend(username='', password='') + with self.assertRaises(socket.error): + backend.open() + backend.fail_silently = True + backend.open() + class SMTPBackendStoppedServerTest(SMTPBackendTestsBase): """