(domains) notify support when domain status changes

During the scheduled task to check domains,
send an email notification to domain support if a
status has changed.
This commit is contained in:
Sabrina Demagny
2025-03-21 17:10:18 +01:00
parent feb5d7154b
commit 5178e460c4
8 changed files with 296 additions and 11 deletions

View File

@@ -2,12 +2,17 @@
Declare and configure the models for the People additional application : mailbox_manager
"""
import logging
import smtplib
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser
from django.core import exceptions, validators
from django.contrib.sites.models import Site
from django.core import exceptions, mail, validators
from django.db import models
from django.template.loader import render_to_string
from django.utils.text import slugify
from django.utils.translation import gettext
from django.utils.translation import get_language, gettext, override
from django.utils.translation import gettext_lazy as _
from core.models import BaseInvitation, BaseModel, Organization, User
@@ -18,6 +23,28 @@ from mailbox_manager.enums import (
MailDomainStatusChoices,
)
logger = logging.getLogger(__name__)
STATUS_NOTIFICATION_MAILS = {
# new status domain: (mail subject, mail template html, mail template text)
MailDomainStatusChoices.ENABLED: (
_("[La Suite] Your domain is ready"),
"mail/html/maildomain_enabled.html",
"mail/text/maildomain_enabled.txt",
),
MailDomainStatusChoices.ACTION_REQUIRED: (
_("[La Suite] Your domain requires action"),
"mail/html/maildomain_action_required.html",
"mail/text/maildomain_action_required.txt",
),
MailDomainStatusChoices.FAILED: (
_("[La Suite] Your domain has failed"),
"mail/html/maildomain_failed.html",
"mail/text/maildomain_failed.txt",
),
}
class MailDomain(BaseModel):
"""Domain names from which we will create email addresses (mailboxes)."""
@@ -104,6 +131,45 @@ class MailDomain(BaseModel):
bool(self.organization) and self.status == MailDomainStatusChoices.ENABLED
)
def notify_status_change(self, recipients=None, language=None):
"""
Notify the support team that the domain status has changed.
"""
subject, template_html, template_text = STATUS_NOTIFICATION_MAILS.get(
self.status, (None, None, None)
)
if not subject:
return
context = {
"title": subject,
"domain_name": self.name,
"manage_domain_url": (
f"{Site.objects.get_current().domain}/mail-domains/{self.slug}/"
),
}
try:
with override(language or get_language()):
mail.send_mail(
subject,
render_to_string(template_text, context),
settings.EMAIL_FROM,
recipients or [self.support_email],
html_message=render_to_string(template_html, context),
fail_silently=False,
)
except smtplib.SMTPException as exception:
logger.error(
"Notification email to %s was not sent: %s",
self.support_email,
exception,
)
else:
logger.info(
"Information about domain %s sent to %s.",
self.name,
self.support_email,
)
class MailDomainAccess(BaseModel):
"""Allow to manage users' accesses to mail domains."""