Skip to content

Commit

Permalink
Reusing SMTP connections for sending e-mails.
Browse files Browse the repository at this point in the history
http://github.com/jtauber/django-mailer/issues/#issue/2

Note: Connections are only reused on success.
  • Loading branch information
istruble committed May 23, 2009
1 parent 22739b4 commit 50bd5fd
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions mailer/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from mailer.models import Message, DontSendEntry, MessageLog

from django.conf import settings
from django.core.mail import send_mail as core_send_mail
from django.core.mail import EmailMessage

# when queue is empty, how long to wait (in seconds) before checking again
EMPTY_QUEUE_SLEEP = getattr(settings, "MAILER_EMPTY_QUEUE_SLEEP", 30)
Expand All @@ -16,6 +16,10 @@
# default behavior is to never wait for the lock to be available.
LOCK_WAIT_TIMEOUT = getattr(settings, "MAILER_LOCK_WAIT_TIMEOUT", -1)

# a DRY_RUN will not create SMTP connections or attempt to send msgs.
DRY_RUN = getattr(settings, "MAILER_DRY_RUN", False)
SKIP_SEND = getattr(settings, "MAILER_DRY_RUN_SKIP_SEND", DRY_RUN)


def prioritize():
"""
Expand Down Expand Up @@ -58,6 +62,7 @@ def send_all():
dont_send = 0
deferred = 0
sent = 0
connection = None

try:
for message in prioritize():
Expand All @@ -69,12 +74,25 @@ def send_all():
else:
try:
logging.info("sending message '%s' to %s" % (message.subject.encode("utf-8"), message.to_address.encode("utf-8")))
core_send_mail(message.subject, message.message_body, message.from_address, [message.to_address])
msg = EmailMessage(
subject=message.subject,
body=message.message_body,
from_email=message.from_address,
to=[message.to_address],
connection=connection)
if not DRY_RUN:
if connection is None:
# save the connection for possible reuse
connection = msg.get_connection()
logging.debug("got new connection")
if not SKIP_SEND:
msg.send()
MessageLog.objects.log(message, 1) # @@@ avoid using literal result code
message.delete()
sent += 1
except (socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError), err:
message.defer()
connection = None # don't try to cache on error
logging.info("message deferred due to failure: %s" % err)
MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code
deferred += 1
Expand Down

0 comments on commit 50bd5fd

Please sign in to comment.