django-orchestra/orchestra/contrib/mailer/backends.py

48 lines
1.7 KiB
Python
Raw Normal View History

2015-05-15 14:19:24 +00:00
from django.conf import settings as djsettings
2015-05-04 19:52:53 +00:00
from django.core.mail.backends.base import BaseEmailBackend
from orchestra.core.caches import get_request_cache
from . import settings
2015-05-04 19:52:53 +00:00
from .models import Message
from .tasks import send_message
class EmailBackend(BaseEmailBackend):
2015-05-05 19:42:55 +00:00
"""
2015-05-04 19:52:53 +00:00
A wrapper that manages a queued SMTP system.
2015-05-05 19:42:55 +00:00
"""
2015-05-04 19:52:53 +00:00
def send_messages(self, email_messages):
if not email_messages:
return
2015-05-30 14:44:05 +00:00
# Count messages per request
cache = get_request_cache()
key = 'mailer.sent_messages'
sent_messages = cache.get(key) or 0
sent_messages += 1
cache.set(key, sent_messages)
2015-05-05 19:42:55 +00:00
is_bulk = len(email_messages) > 1
2015-05-30 14:44:05 +00:00
if sent_messages > settings.MAILER_NON_QUEUED_PER_REQUEST_THRESHOLD:
is_bulk = True
2015-05-19 13:27:04 +00:00
default_priority = Message.NORMAL if is_bulk else Message.CRITICAL
num_sent = 0
2015-05-04 19:52:53 +00:00
for message in email_messages:
2015-05-19 13:27:04 +00:00
priority = message.extra_headers.get('X-Mail-Priority', default_priority)
2015-05-05 19:42:55 +00:00
content = message.message().as_string()
for to_email in message.recipients():
message = Message(
2015-05-05 19:42:55 +00:00
priority=priority,
to_address=to_email,
2015-05-15 14:19:24 +00:00
from_address=getattr(message, 'from_email', djsettings.DEFAULT_FROM_EMAIL),
2015-05-05 19:42:55 +00:00
subject=message.subject,
content=content,
)
2015-05-19 13:27:04 +00:00
if priority == Message.CRITICAL:
2015-05-05 19:42:55 +00:00
# send immidiately
send_message.apply_async(message)
else:
message.save()
2015-05-04 19:52:53 +00:00
num_sent += 1
return num_sent