From 67d27e5eb5eacecc61c4fedb2ca7f10cd9adfb94 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Thu, 22 Feb 2024 18:37:31 +0100 Subject: [PATCH] add new command for send mail to admins --- idhub/management/commands/send_mail_admins.py | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 idhub/management/commands/send_mail_admins.py diff --git a/idhub/management/commands/send_mail_admins.py b/idhub/management/commands/send_mail_admins.py new file mode 100644 index 0000000..0ef24f8 --- /dev/null +++ b/idhub/management/commands/send_mail_admins.py @@ -0,0 +1,56 @@ +import logging + +from urllib.parse import urlparse + +from django.conf import settings +from django.template import loader +from django.core.mail import EmailMultiAlternatives +from django.core.management.base import BaseCommand +from django.contrib.auth import get_user_model + + +logger = logging.getLogger(__name__) +User = get_user_model() + + +class Command(BaseCommand): + help = "Send mails to the admins for add general key" + subject_template_name = 'idhub/admin/registration/start_app_admin_subject.txt' + email_template_name = 'idhub/admin/registration/start_app_admin_email.txt' + html_email_template_name = 'idhub/admin/registration/start_app_admin_email.html' + + def handle(self, *args, **kwargs): + for user in User.objects.filter(is_admin=True): + self.send_email(user) + + def send_email(self, user): + """ + Send a email when a user is activated. + """ + parsed_url = urlparse(settings.RESPONSE_URI) + domain = f"{parsed_url.scheme}://{parsed_url.netloc}/" + context = { + "domain": domain, + } + subject = loader.render_to_string(self.subject_template_name, context) + # Email subject *must not* contain newlines + subject = ''.join(subject.splitlines()) + body = loader.render_to_string(self.email_template_name, context) + from_email = settings.DEFAULT_FROM_EMAIL + to_email = user.email + + email_message = EmailMultiAlternatives( + subject, body, from_email, [to_email]) + html_email = loader.render_to_string(self.html_email_template_name, context) + email_message.attach_alternative(html_email, 'text/html') + try: + if settings.ENABLE_EMAIL: + email_message.send() + return + + logger.warning(to_email) + logger.warning(body) + + except Exception as err: + logger.error(err) + return