From afbcfe66bb7c615d74da418e6914ec3195414d4d Mon Sep 17 00:00:00 2001 From: Oliver Date: Thu, 17 Apr 2025 17:29:26 +1000 Subject: [PATCH] Fix for email sending (#9526) * Fix for email sending - Extract valid email for user - Do not send if email not configured for user * Improve email address filtering logic * Fix return type hint --- .devcontainer/docker-compose.yml | 2 -- .../InvenTree/InvenTree/helpers_email.py | 18 +++++++++++++++++- src/backend/InvenTree/InvenTree/tasks.py | 5 ++++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/.devcontainer/docker-compose.yml b/.devcontainer/docker-compose.yml index dbd55b6cbe..0d2594d682 100644 --- a/.devcontainer/docker-compose.yml +++ b/.devcontainer/docker-compose.yml @@ -24,8 +24,6 @@ services: volumes: - ../:/home/inventree:z - /tmp/.X11-unix:/tmp/.X11-unix - ports: - - 8000 environment: INVENTREE_DB_ENGINE: postgresql diff --git a/src/backend/InvenTree/InvenTree/helpers_email.py b/src/backend/InvenTree/InvenTree/helpers_email.py index dcb059d54e..e8fb6b6476 100644 --- a/src/backend/InvenTree/InvenTree/helpers_email.py +++ b/src/backend/InvenTree/InvenTree/helpers_email.py @@ -4,6 +4,7 @@ from django.conf import settings from django.core import mail as django_mail import structlog +from allauth.account.models import EmailAddress import InvenTree.ready import InvenTree.tasks @@ -56,7 +57,6 @@ def send_email(subject, body, recipients, from_email=None, html_message=None): recipients = [recipients] import InvenTree.ready - import InvenTree.status if InvenTree.ready.isImportingData(): # If we are importing data, don't send emails @@ -89,3 +89,19 @@ def send_email(subject, body, recipients, from_email=None, html_message=None): html_message=html_message, group='notification', ) + + +def get_email_for_user(user) -> str: + """Find an email address for the specified user.""" + # First check if the user has an associated email address + if user.email: + return user.email + + # Otherwise, find first matching email + # Priority is given to primary or verified email addresses + if ( + email := EmailAddress.objects.filter(user=user) + .order_by('-primary', '-verified') + .first() + ): + return email.email diff --git a/src/backend/InvenTree/InvenTree/tasks.py b/src/backend/InvenTree/InvenTree/tasks.py index dbe91d1974..ed3ef84c97 100644 --- a/src/backend/InvenTree/InvenTree/tasks.py +++ b/src/backend/InvenTree/InvenTree/tasks.py @@ -705,4 +705,7 @@ def email_user(user_id: int, subject: str, message: str) -> None: logger.warning('User <%s> not found - cannot send welcome message', user_id) return - user.email_user(subject=subject, message=message) + from InvenTree.helpers_email import get_email_for_user, send_email + + if email := get_email_for_user(user): + send_email(subject, message, [email])