From b4d08a21744f66578f793c67c04eec01fd26d0c7 Mon Sep 17 00:00:00 2001
From: Karel van Klink <karel.vanklink@geant.org>
Date: Tue, 13 Feb 2024 15:42:52 +0100
Subject: [PATCH] add STARTTLS support in mailer service

---
 gso/services/mailer.py | 6 ++++++
 gso/settings.py        | 1 +
 2 files changed, 7 insertions(+)

diff --git a/gso/services/mailer.py b/gso/services/mailer.py
index be7fd2b1..ee4d7dd9 100644
--- a/gso/services/mailer.py
+++ b/gso/services/mailer.py
@@ -2,6 +2,7 @@
 
 import smtplib
 from email.message import EmailMessage
+from ssl import create_default_context
 
 from gso.settings import load_oss_params
 
@@ -9,6 +10,8 @@ from gso.settings import load_oss_params
 def send_mail(recipient, subject, body) -> None:
     """Send an email message to the given address.
 
+    Only supports STARTTLS, not SSL.
+
     :param recipient: The destination address.
     :param subject: The email subject.
     :param body: The contents of the email message.
@@ -21,6 +24,9 @@ def send_mail(recipient, subject, body) -> None:
     msg.set_content(body)
 
     with smtplib.SMTP(email_params.smtp_host, email_params.smtp_port) as s:
+        if email_params.starttls_enabled:
+            tls_context = create_default_context()
+            s.starttls(context=tls_context)
         if email_params.smtp_username or email_params.smtp_password:
             s.login(email_params.smtp_username, email_params.smtp_password)
         s.send_message(msg)
diff --git a/gso/settings.py b/gso/settings.py
index 6c7fc8ef..de222238 100644
--- a/gso/settings.py
+++ b/gso/settings.py
@@ -159,6 +159,7 @@ class EmailParams(BaseSettings):
     from_address: str
     smtp_host: str
     smtp_port: int
+    starttls_enabled: bool
     smtp_username: str | None = ""
     smtp_password: str | None = ""
 
-- 
GitLab