foerderbarometer/input/utils/mail/__init__.py

84 lines
2.4 KiB
Python
Raw Normal View History

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
2025-10-17 10:06:23 +00:00
2025-10-17 13:14:16 +00:00
from input.models import Project
2025-10-17 10:06:23 +00:00
2025-10-17 15:31:51 +00:00
from .attachments import collect_and_attach
2025-10-17 10:06:23 +00:00
__all__ = [
2025-10-17 12:51:18 +00:00
'build_email',
'send_email',
2025-10-17 15:31:51 +00:00
'collect_and_attach',
2025-10-17 13:14:16 +00:00
'send_applicant_decision_mail',
2025-10-17 10:06:23 +00:00
'send_staff_decision_mail',
2025-10-17 13:14:16 +00:00
'send_decision_mails',
2025-10-17 10:06:23 +00:00
]
2025-10-17 12:51:18 +00:00
def build_email(template_name: str, context: dict, subject: str, *recipients: str, **kwargs):
body = get_template(f'mails/{template_name}.txt').render(context)
html = get_template(f'mails/{template_name}.html').render(context)
kwargs.setdefault('from_email', settings.IF_EMAIL)
kwargs['subject'] = subject
kwargs['body'] = body
kwargs['to'] = recipients
email = EmailMultiAlternatives(**kwargs)
email.attach_alternative(html, 'text/html')
return email
def send_email(template_name: str, context: dict, subject: str, *recipients: str, fail_silently=False, **kwargs):
return build_email(template_name, context, subject, *recipients, **kwargs).send(fail_silently)
2025-10-17 13:14:16 +00:00
def get_decision_mail_context(obj: Project):
"""
Build a minimal, consistent context for decision mails (applicant & staff).
"""
2025-10-17 13:14:16 +00:00
return {
2025-10-17 13:14:16 +00:00
'project': obj,
'data': {
2025-10-17 13:14:16 +00:00
'realname': obj.realname or obj.email,
'name': obj.name,
},
}
2025-10-17 13:14:16 +00:00
def send_base_decision_mail(obj: Project, scope: str, subject: str, recipient: str):
context = get_decision_mail_context(obj)
decision = 'granted' if obj.granted else 'denied'
decision_label = 'bewilligt' if obj.granted else 'abgelehnt'
subject = subject.format(name=obj.name, decision=decision_label)
return send_email(f'approval_{scope}_{decision}', context, subject, recipient)
def send_applicant_decision_mail(obj: Project):
"""
Send a decision email to the applicant after manual approval/denial.
"""
2025-10-17 13:14:16 +00:00
if recipient := obj.email:
return send_base_decision_mail(obj, 'applicant', 'Deine Förderanfrage „{name} {decision}', recipient)
2025-10-17 13:14:16 +00:00
return 0
2025-10-17 13:14:16 +00:00
def send_staff_decision_mail(obj: Project):
"""
Send a decision email to the internal team (staff) after approval/denial.
"""
2025-10-17 13:14:16 +00:00
return send_base_decision_mail(obj, 'staff', 'Entscheidung: {name} ({decision})', settings.IF_EMAIL)
2025-10-17 13:14:16 +00:00
def send_decision_mails(obj: Project):
return send_applicant_decision_mail(obj) + send_staff_decision_mail(obj)