Skip to content

Commit

Permalink
Fix #96 -- Override contect manager to lazy open SMTP connections (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
codingjoe authored Aug 29, 2024
1 parent ea7eb63 commit 011345e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
13 changes: 13 additions & 0 deletions emark/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@


class RenderEmailBackendMixin:

def __enter__(self):
# Do not open a connection before rendering the messages
# to avoid connection timeouts.
# EmailBackend.send_messages() will open the connection.
return self

def send_messages(self, email_messages):
for message in email_messages:
if isinstance(message, MarkdownEmail):
Expand All @@ -26,6 +33,12 @@ def send_messages(self, email_messages):
class TrackingEmailBackendMixin:
"""Add a tracking framework to an email backend."""

def __enter__(self):
# Do not open a connection before rendering the messages
# to avoid connection timeouts.
# EmailBackend.send_messages() will open the connection.
return self

def send_messages(self, email_messages):
self._messages_sent = []
for message in email_messages:
Expand Down
10 changes: 10 additions & 0 deletions tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ def test_write_message__multipart(self):


class TestSMTPEmailBackend:

def test_enter(self):
with backends.SMTPEmailBackend() as backend:
assert not backend.connection, "Connection should not be opened"

def test_send(self, email_message):
class TestBackend(backends.SMTPEmailBackend):
def _send(self, message):
Expand Down Expand Up @@ -103,6 +108,11 @@ def test_write_message__native_email__multiple_recipients(self):


class TestTrackingSMTPEmailBackend:

def test_enter(self):
with backends.TrackingSMTPEmailBackend() as backend:
assert not backend.connection, "Connection should not be opened"

@pytest.mark.django_db
def test_send(self, email_message):
email_message.to = [
Expand Down

0 comments on commit 011345e

Please sign in to comment.