Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,31 @@ For testing purposes, you could set this to
``"django.core.mail.backends.console.EmailBackend"`` to just print emails to the
console.

On Django 6.1 and later you can use the ``MAILERS`` setting instead of
``EMAIL_BACKEND``. Give the mailer that uses ``mailer.backend.DbBackend`` a
``using`` option that names the mailer which does the real sending:

.. code-block:: python

MAILERS = {
"default": {
"BACKEND": "mailer.backend.DbBackend",
"OPTIONS": {
"using": "smtp",
},
},
"smtp": {
"BACKEND": "django.core.mail.backends.smtp.EmailBackend",
"OPTIONS": {
"host": "smtp.example.com",
},
},
}

``using`` replaces ``MAILER_EMAIL_BACKEND``, which is not used when ``MAILERS``
is defined. The queue does not record which mailer a message came through, so
if several mailers use ``DbBackend`` they must all have the same ``using``.

Now, just use the normal `Django mail functions
<https://docs.djangoproject.com/en/stable/topics/email/>`_ for sending email. These
functions will store mail on a queue in the database, which must be sent as
Expand Down
11 changes: 11 additions & 0 deletions src/mailer/backend.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail.backends.base import BaseEmailBackend

from mailer.models import Message


class DbBackend(BaseEmailBackend):
def __init__(self, *args, using=None, **kwargs):
super().__init__(*args, **kwargs)
# "using" is the MAILERS alias that delivers the queued mail. It is read
# from the settings by mailer.engine, so it is only checked here.
self.using = using
if getattr(self, "alias", None) is not None and using is None:
raise ImproperlyConfigured(
f'The "{self.alias}" mailer needs a "using" option that names the mailer which delivers queued mail'
)

def send_messages(self, email_messages):
# allow for a custom batch size
MESSAGES_BATCH_SIZE = getattr(settings, "MAILER_MESSAGES_BATCH_SIZE", None)
Expand Down
73 changes: 67 additions & 6 deletions src/mailer/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,9 @@ def release_lock(lock):
logger.debug("released.")


DB_BACKEND = "mailer.backend.DbBackend"


def _require_no_backend_loop(mailer_email_backend):
if mailer_email_backend == settings.EMAIL_BACKEND == "mailer.backend.DbBackend":
raise ImproperlyConfigured(
Expand All @@ -183,6 +186,59 @@ def _require_no_backend_loop(mailer_email_backend):
)


def _get_delivery_mailer_alias():
"""
Return the MAILERS alias that delivers queued mail, or None if the project
still uses the EMAIL_* settings (always the case before Django 6.1).

The alias comes from the "using" option of the mailer that has DbBackend as
its backend. Without such a mailer, mail is put on the queue with the
functions in the mailer module, and the default mailer delivers it.
"""
mailers_setting = getattr(settings, "MAILERS", None)
if mailers_setting is None:
return None

queueing = {
alias: config.get("OPTIONS", {}).get("using")
for alias, config in mailers_setting.items()
if config.get("BACKEND") == DB_BACKEND
}
if not queueing:
return "default"

targets = set(queueing.values())
if None in targets:
raise ImproperlyConfigured(
f'A mailer with "{DB_BACKEND}" as its BACKEND needs a "using" option'
" that names the mailer which delivers queued mail"
)
if len(targets) > 1:
# The queue does not record which mailer a message was queued through.
raise ImproperlyConfigured(
f'All mailers with "{DB_BACKEND}" as their BACKEND must have the same "using" option,'
f" found {', '.join(sorted(targets))}"
)
(target,) = targets
if target not in mailers_setting:
raise ImproperlyConfigured(f'"using" is "{target}", which is not an alias in MAILERS')
if target in queueing:
raise ImproperlyConfigured(
f'"using" is "{target}", a mailer with "{DB_BACKEND}" as its BACKEND.'
" It would put mail back on the queue instead of sending it"
)
return target


def _get_delivery_connection(mailer_alias, mailer_email_backend):
if mailer_alias is None:
return get_connection(backend=mailer_email_backend)

from django.core.mail import mailers

return mailers[mailer_alias]


def send_all(queryset=None):
"""
Send all eligible messages in the queue.
Expand All @@ -196,7 +252,9 @@ def send_all(queryset=None):

error_handler = import_string(getattr(settings, "MAILER_ERROR_HANDLER", "mailer.engine.handle_delivery_exception"))

_require_no_backend_loop(mailer_email_backend)
mailer_alias = _get_delivery_mailer_alias()
if mailer_alias is None:
_require_no_backend_loop(mailer_email_backend)

if use_file_lock:
acquired, lock = acquire_lock()
Expand All @@ -216,16 +274,19 @@ def send_all(queryset=None):
continue
try:
if connection is None:
connection = get_connection(backend=mailer_email_backend)
connection = _get_delivery_connection(mailer_alias, mailer_email_backend)
logger.info(f"sending message '{message.subject}' to {', '.join(map(str, message.to_addresses))}")
email = message.email
if email is not None:
email.connection = connection
ensure_message_id(email)
email.send()
# Hand the message to the connection directly, because
# setting email.connection is deprecated since Django
# 6.1. Like EmailMessage.send(), skip a message that has
# no recipients left (all of them are on the don't-send
# list).
if email.recipients():
connection.send_messages([email])

# connection can't be stored in the MessageLog
email.connection = None
message.email = email # For the sake of MessageLog
MessageLog.objects.log(message, RESULT_SUCCESS)
counts["sent"] += 1
Expand Down
64 changes: 64 additions & 0 deletions tests/test_mailer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import datetime
import pickle
import time
import unittest
import warnings
from unittest.mock import Mock, PropertyMock, patch

import django
Expand Down Expand Up @@ -776,6 +778,68 @@ def test_loop_detection(self):
self.assertIn("MAILER_EMAIL_BACKEND", str(catcher.exception))


@unittest.skipIf(django.VERSION < (6, 1), "MAILERS was added in Django 6.1")
class MailersSettingTest(TestCase):
"""Sending the queue when the project uses MAILERS (Django 6.1+)."""

LOCMEM = {"BACKEND": "django.core.mail.backends.locmem.EmailBackend"}
MAILERS = {
"default": {"BACKEND": "mailer.backend.DbBackend", "OPTIONS": {"using": "delivery"}},
"delivery": LOCMEM,
}

def assert_send_all_improperly_configured(self, mailers, text):
with self.settings(MAILERS=mailers), self.assertRaises(ImproperlyConfigured) as catcher:
engine.send_all()
self.assertIn(text, str(catcher.exception))

def test_queue_and_send(self):
with self.settings(MAILERS=self.MAILERS):
mail.send_mail("Subject", "Body", "sender@example.com", ["recipient@example.com"])
self.assertEqual(Message.objects.count(), 1)
self.assertEqual(len(mail.outbox), 0)

with warnings.catch_warnings():
warnings.simplefilter("error")
engine.send_all()

self.assertEqual(Message.objects.count(), 0)
self.assertEqual(MessageLog.objects.count(), 1)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, "Subject")

def test_default_mailer_delivers_without_db_backend(self):
with self.settings(MAILERS={"default": self.LOCMEM}):
mailer.send_mail("Subject", "Body", "sender@example.com", ["recipient@example.com"])
self.assertEqual(len(mail.outbox), 0)

engine.send_all()

self.assertEqual(Message.objects.count(), 0)
self.assertEqual(len(mail.outbox), 1)

def test_using_required(self):
mailers = {"default": {"BACKEND": "mailer.backend.DbBackend"}, "delivery": self.LOCMEM}
self.assert_send_all_improperly_configured(mailers, '"using"')
with self.settings(MAILERS=mailers), self.assertRaises(ImproperlyConfigured):
mail.send_mail("Subject", "Body", "sender@example.com", ["recipient@example.com"])

def test_unknown_using(self):
mailers = {"default": {"BACKEND": "mailer.backend.DbBackend", "OPTIONS": {"using": "missing"}}}
self.assert_send_all_improperly_configured(mailers, "missing")

def test_conflicting_using(self):
mailers = self.MAILERS | {
"other": {"BACKEND": "mailer.backend.DbBackend", "OPTIONS": {"using": "delivery2"}},
"delivery2": self.LOCMEM,
}
self.assert_send_all_improperly_configured(mailers, "delivery, delivery2")

def test_loop_detection(self):
mailers = {"default": {"BACKEND": "mailer.backend.DbBackend", "OPTIONS": {"using": "default"}}}
self.assert_send_all_improperly_configured(mailers, "back on the queue")


class UseFileLockTest(TestCase):
"""Test the MAILER_USE_FILE_LOCK setting."""

Expand Down
Loading