diff --git a/docs/usage.rst b/docs/usage.rst index 5111233..16cf8dd 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -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 `_ for sending email. These functions will store mail on a queue in the database, which must be sent as diff --git a/src/mailer/backend.py b/src/mailer/backend.py index 07f878c..1437303 100644 --- a/src/mailer/backend.py +++ b/src/mailer/backend.py @@ -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) diff --git a/src/mailer/engine.py b/src/mailer/engine.py index 8baf4d6..90b7c12 100644 --- a/src/mailer/engine.py +++ b/src/mailer/engine.py @@ -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( @@ -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. @@ -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() @@ -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 diff --git a/tests/test_mailer.py b/tests/test_mailer.py index 4f2813c..bc9b9b3 100644 --- a/tests/test_mailer.py +++ b/tests/test_mailer.py @@ -1,6 +1,8 @@ import datetime import pickle import time +import unittest +import warnings from unittest.mock import Mock, PropertyMock, patch import django @@ -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."""