From f82dc702746b9729e50003f1845cdb8bc5d5d82a Mon Sep 17 00:00:00 2001 From: The Z <1020111+farirat@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:58:53 +0100 Subject: [PATCH] feat(backend): handle Anymail backends from other packages (#13420) * feat(backend): handle Anymail backends from other packages Backends that subclass AnymailBaseBackend outside the anymail package missed the Message-ID handling, the ESP message id and the ANYMAIL settings. * feat(backend): add Mailkube email backend * feat(backend): record Mailkube delivery events mailkube-django 1.2 sends them through Anymail's tracking signal. * docs: add changelog entry for Mailkube backend * chore(backend): drop the Mailkube backend from core mailkube-django, its tracking route and its docs leave the core requirements. Anymail backends from other packages keep the handling added in the first commit; such a package is installed separately. * remove self-explaining comments Co-authored-by: Matthias Mair --------- Co-authored-by: Matthias Mair --- CHANGELOG.md | 2 + docs/docs/start/config.md | 1 + src/backend/InvenTree/InvenTree/backends.py | 6 ++- src/backend/InvenTree/InvenTree/settings.py | 3 +- src/backend/InvenTree/common/test_emails.py | 57 ++++++++++++++++++++- 5 files changed, 64 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a13daa393c..2c5278b084 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#13166](https://github.com/inventree/InvenTree/pull/13166) Adds an "exclude_from_stock" attribute to the StockLocation model, allowing stock items in specified locations to be excluded from stock availability calculations. +- [#13420](https://github.com/inventree/InvenTree/pull/13420) Anymail backends from other packages (subclasses of `AnymailBaseBackend`) now get the same handling as the built-in ones, and the `ANYMAIL` settings are read for every backend. + ### Changed - [#13274](https://github.com/inventree/InvenTree/pull/13274) API requests which modify an existing object (updates, and "action" endpoints such as issuing or completing an order) now lock the database row before reading it, and run within a single database transaction. This prevents a concurrent edit from silently overwriting changes made by a background task (e.g. the "completed" quantity of a build order being reset while its outputs were being completed). If the object is locked by another long-running process, the request now returns a `409 Conflict` response and can be retried. A failed action no longer leaves partial changes behind. diff --git a/docs/docs/start/config.md b/docs/docs/start/config.md index df7d340dc1..01162382c0 100644 --- a/docs/docs/start/config.md +++ b/docs/docs/start/config.md @@ -379,6 +379,7 @@ The following email settings are available: {{ configtable() }} {{ configsetting("INVENTREE_EMAIL_BACKEND") }} Email backend module | +{{ configsetting("INVENTREE_ANYMAIL") }} Anymail settings for the selected ESP (a JSON object in the environment variable) | {{ configsetting("INVENTREE_EMAIL_HOST") }} Email server host | {{ configsetting("INVENTREE_EMAIL_PORT") }} Email server port | {{ configsetting("INVENTREE_EMAIL_USERNAME") }} Email account username | diff --git a/src/backend/InvenTree/InvenTree/backends.py b/src/backend/InvenTree/InvenTree/backends.py index a80fc3d6fb..b6837fd432 100644 --- a/src/backend/InvenTree/InvenTree/backends.py +++ b/src/backend/InvenTree/InvenTree/backends.py @@ -11,6 +11,7 @@ from django.core.mail.message import EmailMessage, EmailMultiAlternatives from django.utils.module_loading import import_string import structlog +from anymail.backends.base import AnymailBaseBackend from maintenance_mode.backends import AbstractStateBackend import common.models @@ -99,6 +100,7 @@ class InvenTreeMailLoggingBackend(BaseEmailBackend): super().__init__(*args, **kwargs) klass = import_string(settings.INTERNAL_EMAIL_BACKEND) self.backend: BaseEmailBackend = klass(*args, **kwargs) + self.is_anymail = isinstance(self.backend, AnymailBaseBackend) def open(self): """Open the email backend connection.""" @@ -129,7 +131,7 @@ class InvenTreeMailLoggingBackend(BaseEmailBackend): logger.exception('INVE-W10: Problem logging recipients, ignoring') # Anymail: pre-processing - if settings.INTERNAL_EMAIL_BACKEND.startswith('anymail.backends.'): + if self.is_anymail: for a in email_messages: if a.extra_headers and common.models.HEADER_MSG_ID in a.extra_headers: # Remove the Message-ID header from the email @@ -156,7 +158,7 @@ class InvenTreeMailLoggingBackend(BaseEmailBackend): logger.info('INVE-W10: No emails sent') else: logger.info('INVE-W10: %s emails sent', ret_val) - if settings.INTERNAL_EMAIL_BACKEND.startswith('anymail.backends.'): + if self.is_anymail: # Anymail: ESP does return the message ID for us so we need to set it in the database for k, v in { a.extra_headers['X-InvenTree-MsgId-1']: a.anymail_status.message_id diff --git a/src/backend/InvenTree/InvenTree/settings.py b/src/backend/InvenTree/InvenTree/settings.py index 5e80dc0892..1d6a871089 100644 --- a/src/backend/InvenTree/InvenTree/settings.py +++ b/src/backend/InvenTree/InvenTree/settings.py @@ -816,8 +816,7 @@ EMAIL_HOST_PASSWORD = get_setting('INVENTREE_EMAIL_PASSWORD', 'email.password') EMAIL_USE_TLS = get_boolean_setting('INVENTREE_EMAIL_TLS', 'email.tls', False) EMAIL_USE_SSL = get_boolean_setting('INVENTREE_EMAIL_SSL', 'email.ssl', False) # Anymail -if INTERNAL_EMAIL_BACKEND.startswith('anymail.backends.'): - ANYMAIL = get_setting('INVENTREE_ANYMAIL', 'email.anymail', None, dict) +ANYMAIL = get_setting('INVENTREE_ANYMAIL', 'email.anymail', None, dict) EMAIL_SUBJECT_PREFIX = get_setting( 'INVENTREE_EMAIL_PREFIX', 'email.prefix', '[InvenTree] ' diff --git a/src/backend/InvenTree/common/test_emails.py b/src/backend/InvenTree/common/test_emails.py index 7e164c6a28..6532fa6204 100644 --- a/src/backend/InvenTree/common/test_emails.py +++ b/src/backend/InvenTree/common/test_emails.py @@ -1,20 +1,28 @@ """Tests for the custom email backend and models.""" +from django.conf import settings from django.core import mail from django.core.exceptions import ValidationError from django.test import TestCase from django.test.utils import override_settings from django.urls import reverse +from anymail.backends.test import EmailBackend as AnymailTestBackend from anymail.inbound import AnymailInboundMessage from anymail.signals import AnymailInboundEvent, AnymailTrackingEvent, inbound, tracking -from common.models import EmailMessage, Priority +from common.models import HEADER_MSG_ID, EmailMessage, Priority from common.settings import set_global_setting +from InvenTree.backends import InvenTreeMailLoggingBackend +from InvenTree.config import CONFIG_LOOKUPS from InvenTree.helpers_email import send_email from InvenTree.unit_test import InvenTreeAPITestCase +class ExternalAnymailBackend(AnymailTestBackend): + """Anymail backend that lives outside the anymail package.""" + + class EmailTests(InvenTreeAPITestCase): """Unit tests for the custom email backend and models.""" @@ -97,6 +105,53 @@ class EmailTests(InvenTreeAPITestCase): self.assertEqual(headers['X-My-Header'], 'my value') """ + def test_backend_detects_anymail(self): + """Test that Anymail backends are detected by class, wherever they live.""" + for backend, expected in ( + ('anymail.backends.test.EmailBackend', True), + ('common.test_emails.ExternalAnymailBackend', True), + ('django.core.mail.backends.locmem.EmailBackend', False), + ): + with self.subTest(backend=backend): + with self.settings(INTERNAL_EMAIL_BACKEND=backend): + self.assertEqual(InvenTreeMailLoggingBackend().is_anymail, expected) + + @override_settings( + EMAIL_BACKEND='InvenTree.backends.InvenTreeMailLoggingBackend', + INTERNAL_EMAIL_BACKEND='common.test_emails.ExternalAnymailBackend', + ) + def test_email_send_anymail_external(self): + """Test that an Anymail backend from another package gets the Anymail handling.""" + send_email(subject='test sub', body='test msg', recipients=['to@example.org']) + + self.assertEqual(len(mail.outbox), 1) + message = mail.outbox[0] + self.assertNotIn(HEADER_MSG_ID, message.extra_headers) + + msg = EmailMessage.objects.get() + self.assertEqual(msg.status, EmailMessage.EmailStatus.SENT) + self.assertEqual(msg.message_id_key, str(message.anymail_status.message_id)) + + @override_settings( + EMAIL_BACKEND='InvenTree.backends.InvenTreeMailLoggingBackend', + INTERNAL_EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', + ) + def test_email_send_keeps_message_id(self): + """Test that other backends keep the Message-ID InvenTree stamped.""" + send_email(subject='test sub', body='test msg', recipients=['to@example.org']) + + self.assertEqual(len(mail.outbox), 1) + message_id = mail.outbox[0].extra_headers[HEADER_MSG_ID] + + msg = EmailMessage.objects.get() + self.assertEqual(msg.status, EmailMessage.EmailStatus.SENT) + self.assertEqual(msg.message_id_key, message_id) + + def test_anymail_settings_always_loaded(self): + """Test that the Anymail settings are read whatever the backend.""" + self.assertIn('INVENTREE_ANYMAIL', CONFIG_LOOKUPS) + self.assertIsInstance(settings.ANYMAIL, dict) + @override_settings( EMAIL_BACKEND='InvenTree.backends.InvenTreeMailLoggingBackend', INTERNAL_EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',