76 lines
2.0 KiB
Python
76 lines
2.0 KiB
Python
import smtplib
|
|
from email.message import EmailMessage
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import settings
|
|
from app.models import NotificationLog, NotificationStatus, NotificationType, TrackedEvent
|
|
|
|
|
|
def _create_log(
|
|
db: Session,
|
|
tracked_event: TrackedEvent,
|
|
notification_type: NotificationType,
|
|
status: NotificationStatus,
|
|
message: str,
|
|
) -> NotificationLog:
|
|
log_entry = NotificationLog(
|
|
tracked_event=tracked_event,
|
|
notification_type=notification_type,
|
|
status=status,
|
|
message=message,
|
|
)
|
|
db.add(log_entry)
|
|
return log_entry
|
|
|
|
|
|
def send_email_notification(
|
|
db: Session,
|
|
tracked_event: TrackedEvent,
|
|
notification_type: NotificationType,
|
|
subject: str,
|
|
body: str,
|
|
) -> NotificationStatus:
|
|
if not settings.smtp_host or not settings.notification_email_to:
|
|
_create_log(
|
|
db,
|
|
tracked_event,
|
|
notification_type,
|
|
NotificationStatus.skipped,
|
|
"SMTP oder Empfaengeradresse nicht konfiguriert.",
|
|
)
|
|
return NotificationStatus.skipped
|
|
|
|
message = EmailMessage()
|
|
message["Subject"] = subject
|
|
message["From"] = settings.smtp_sender
|
|
message["To"] = settings.notification_email_to
|
|
message.set_content(body)
|
|
|
|
try:
|
|
with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=20) as smtp:
|
|
if settings.smtp_starttls:
|
|
smtp.starttls()
|
|
if settings.smtp_user:
|
|
smtp.login(settings.smtp_user, settings.smtp_pass)
|
|
smtp.send_message(message)
|
|
except Exception as exc:
|
|
_create_log(
|
|
db,
|
|
tracked_event,
|
|
notification_type,
|
|
NotificationStatus.failed,
|
|
f"E-Mail-Versand fehlgeschlagen: {exc}",
|
|
)
|
|
return NotificationStatus.failed
|
|
|
|
_create_log(
|
|
db,
|
|
tracked_event,
|
|
notification_type,
|
|
NotificationStatus.sent,
|
|
f"E-Mail an {settings.notification_email_to} versendet.",
|
|
)
|
|
return NotificationStatus.sent
|
|
|