From 7b728e3dfeb64f3d430d7460c04949e25a9b37a5 Mon Sep 17 00:00:00 2001 From: Gabriel Kaszewski Date: Tue, 27 May 2025 23:49:58 +0200 Subject: [PATCH] refactor MailProvider model and enhance email validation in admin form --- api/admin.py | 25 ++++++++++++++++--- .../0002_alter_mailprovider_host.py | 18 +++++++++++++ api/models.py | 2 +- 3 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 api/migrations/0002_alter_mailprovider_host.py diff --git a/api/admin.py b/api/admin.py index 1781217..24e3ecb 100644 --- a/api/admin.py +++ b/api/admin.py @@ -1,4 +1,6 @@ +import logging import smtplib +import socket from django.contrib import admin from django import forms @@ -6,6 +8,8 @@ from django.core.exceptions import ValidationError from api.models import MailProvider +_logger = logging.getLogger(__name__) + class MailProviderForm(forms.ModelForm): host_password = forms.CharField(widget=forms.PasswordInput(render_value=True)) @@ -21,11 +25,26 @@ class MailProviderForm(forms.ModelForm): password = cleaned_data.get("host_password") use_tls = cleaned_data.get("use_tls") + if host: + try: + socket.gethostbyname(host) + except socket.gaierror: + raise ValidationError( + "Invalid mail server hostname. Could not resolve host." + ) + if host and port and user and password: try: - connection = smtplib.SMTP(host, port, timeout=10) - if use_tls: - connection.starttls() + if port == 465: + connection = smtplib.SMTP_SSL(host, port, timeout=10) + else: + connection = smtplib.SMTP(host, port, timeout=10) + if use_tls and port == 465: + raise ValidationError( + "Port 465 should not be used with STARTTLS. Use SMTP_SSL instead or change to port 587." + ) + if use_tls: + connection.starttls() connection.login(user, password) connection.quit() except Exception as e: diff --git a/api/migrations/0002_alter_mailprovider_host.py b/api/migrations/0002_alter_mailprovider_host.py new file mode 100644 index 0000000..40c23a2 --- /dev/null +++ b/api/migrations/0002_alter_mailprovider_host.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.1 on 2025-05-27 21:48 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='mailprovider', + name='host', + field=models.CharField(max_length=255), + ), + ] diff --git a/api/models.py b/api/models.py index 5476c08..53a994e 100644 --- a/api/models.py +++ b/api/models.py @@ -1,7 +1,7 @@ from django.db import models class MailProvider(models.Model): - host = models.URLField() + host = models.CharField(max_length=255) port = models.IntegerField(default=587) host_user = models.CharField(max_length=255) host_password = models.CharField(max_length=255)