mirror of
https://github.com/inventree/InvenTree.git
synced 2026-12-03 12:51:34 +00:00
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 <code@mjmair.com> --------- Co-authored-by: Matthias Mair <code@mjmair.com>
This commit is contained in:
1 parent
cad306bd78
commit
f82dc70274
5 files changed
+64
-5
No files matched your search
@@ -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.
|
- [#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
|
### 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.
|
- [#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.
|
||||||
|
|||||||
@@ -379,6 +379,7 @@ The following email settings are available:
|
|||||||
|
|
||||||
{{ configtable() }}
|
{{ configtable() }}
|
||||||
{{ configsetting("INVENTREE_EMAIL_BACKEND") }} Email backend module |
|
{{ 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_HOST") }} Email server host |
|
||||||
{{ configsetting("INVENTREE_EMAIL_PORT") }} Email server port |
|
{{ configsetting("INVENTREE_EMAIL_PORT") }} Email server port |
|
||||||
{{ configsetting("INVENTREE_EMAIL_USERNAME") }} Email account username |
|
{{ configsetting("INVENTREE_EMAIL_USERNAME") }} Email account username |
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from django.core.mail.message import EmailMessage, EmailMultiAlternatives
|
|||||||
from django.utils.module_loading import import_string
|
from django.utils.module_loading import import_string
|
||||||
|
|
||||||
import structlog
|
import structlog
|
||||||
|
from anymail.backends.base import AnymailBaseBackend
|
||||||
from maintenance_mode.backends import AbstractStateBackend
|
from maintenance_mode.backends import AbstractStateBackend
|
||||||
|
|
||||||
import common.models
|
import common.models
|
||||||
@@ -99,6 +100,7 @@ class InvenTreeMailLoggingBackend(BaseEmailBackend):
|
|||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
klass = import_string(settings.INTERNAL_EMAIL_BACKEND)
|
klass = import_string(settings.INTERNAL_EMAIL_BACKEND)
|
||||||
self.backend: BaseEmailBackend = klass(*args, **kwargs)
|
self.backend: BaseEmailBackend = klass(*args, **kwargs)
|
||||||
|
self.is_anymail = isinstance(self.backend, AnymailBaseBackend)
|
||||||
|
|
||||||
def open(self):
|
def open(self):
|
||||||
"""Open the email backend connection."""
|
"""Open the email backend connection."""
|
||||||
@@ -129,7 +131,7 @@ class InvenTreeMailLoggingBackend(BaseEmailBackend):
|
|||||||
logger.exception('INVE-W10: Problem logging recipients, ignoring')
|
logger.exception('INVE-W10: Problem logging recipients, ignoring')
|
||||||
|
|
||||||
# Anymail: pre-processing
|
# Anymail: pre-processing
|
||||||
if settings.INTERNAL_EMAIL_BACKEND.startswith('anymail.backends.'):
|
if self.is_anymail:
|
||||||
for a in email_messages:
|
for a in email_messages:
|
||||||
if a.extra_headers and common.models.HEADER_MSG_ID in a.extra_headers:
|
if a.extra_headers and common.models.HEADER_MSG_ID in a.extra_headers:
|
||||||
# Remove the Message-ID header from the email
|
# Remove the Message-ID header from the email
|
||||||
@@ -156,7 +158,7 @@ class InvenTreeMailLoggingBackend(BaseEmailBackend):
|
|||||||
logger.info('INVE-W10: No emails sent')
|
logger.info('INVE-W10: No emails sent')
|
||||||
else:
|
else:
|
||||||
logger.info('INVE-W10: %s emails sent', ret_val)
|
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
|
# Anymail: ESP does return the message ID for us so we need to set it in the database
|
||||||
for k, v in {
|
for k, v in {
|
||||||
a.extra_headers['X-InvenTree-MsgId-1']: a.anymail_status.message_id
|
a.extra_headers['X-InvenTree-MsgId-1']: a.anymail_status.message_id
|
||||||
|
|||||||
@@ -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_TLS = get_boolean_setting('INVENTREE_EMAIL_TLS', 'email.tls', False)
|
||||||
EMAIL_USE_SSL = get_boolean_setting('INVENTREE_EMAIL_SSL', 'email.ssl', False)
|
EMAIL_USE_SSL = get_boolean_setting('INVENTREE_EMAIL_SSL', 'email.ssl', False)
|
||||||
# Anymail
|
# 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(
|
EMAIL_SUBJECT_PREFIX = get_setting(
|
||||||
'INVENTREE_EMAIL_PREFIX', 'email.prefix', '[InvenTree] '
|
'INVENTREE_EMAIL_PREFIX', 'email.prefix', '[InvenTree] '
|
||||||
|
|||||||
@@ -1,20 +1,28 @@
|
|||||||
"""Tests for the custom email backend and models."""
|
"""Tests for the custom email backend and models."""
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
from django.core import mail
|
from django.core import mail
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
from django.test.utils import override_settings
|
from django.test.utils import override_settings
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from anymail.backends.test import EmailBackend as AnymailTestBackend
|
||||||
from anymail.inbound import AnymailInboundMessage
|
from anymail.inbound import AnymailInboundMessage
|
||||||
from anymail.signals import AnymailInboundEvent, AnymailTrackingEvent, inbound, tracking
|
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 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.helpers_email import send_email
|
||||||
from InvenTree.unit_test import InvenTreeAPITestCase
|
from InvenTree.unit_test import InvenTreeAPITestCase
|
||||||
|
|
||||||
|
|
||||||
|
class ExternalAnymailBackend(AnymailTestBackend):
|
||||||
|
"""Anymail backend that lives outside the anymail package."""
|
||||||
|
|
||||||
|
|
||||||
class EmailTests(InvenTreeAPITestCase):
|
class EmailTests(InvenTreeAPITestCase):
|
||||||
"""Unit tests for the custom email backend and models."""
|
"""Unit tests for the custom email backend and models."""
|
||||||
|
|
||||||
@@ -97,6 +105,53 @@ class EmailTests(InvenTreeAPITestCase):
|
|||||||
self.assertEqual(headers['X-My-Header'], 'my value')
|
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(
|
@override_settings(
|
||||||
EMAIL_BACKEND='InvenTree.backends.InvenTreeMailLoggingBackend',
|
EMAIL_BACKEND='InvenTree.backends.InvenTreeMailLoggingBackend',
|
||||||
INTERNAL_EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',
|
INTERNAL_EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',
|
||||||
|
|||||||
Reference in new issue
Block a user