Skip to content

Commit

Permalink
fix: improve way of populating smtp key/cert to avoid TypeError in py…
Browse files Browse the repository at this point in the history
…>=12
  • Loading branch information
tkzt committed Nov 30, 2023
1 parent 3624515 commit 306d5a6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
17 changes: 11 additions & 6 deletions flask_mailman/backends/smtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import smtplib
import ssl
import threading
from werkzeug.utils import cached_property

from flask_mailman.backends.base import BaseEmailBackend
from flask_mailman.message import sanitize_address
Expand Down Expand Up @@ -48,6 +49,15 @@ def __init__(
def connection_class(self):
return smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP

@cached_property
def ssl_context(self):
if self.ssl_certfile or self.ssl_keyfile:
ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile)
return ssl_context

Check warning on line 57 in flask_mailman/backends/smtp.py

View check run for this annotation

Codecov / codecov/patch

flask_mailman/backends/smtp.py#L55-L57

Added lines #L55 - L57 were not covered by tests
else:
return ssl.create_default_context()

def open(self):
"""
Ensure an open connection to the email server. Return whether or not a
Expand All @@ -64,12 +74,7 @@ def open(self):
if self.timeout is not None:
connection_params['timeout'] = self.timeout
if self.use_ssl:
connection_params.update(
{
'keyfile': self.ssl_keyfile,
'certfile': self.ssl_certfile,
}
)
connection_params["context"] = self.ssl_context
try:
self.connection = self.connection_class(self.host, self.port, **connection_params)

Expand Down
10 changes: 10 additions & 0 deletions tests/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from email.utils import parseaddr
import os
import socket
from ssl import SSLError
import tempfile
import pytest

Expand Down Expand Up @@ -341,6 +342,15 @@ def test_email_tls_attempts_starttls(self):
with backend:
pass

def test_email_ssl_attempts_ssl_connection(self):
with SmtpdContext(self.app.extensions['mailman']):
self.app.extensions['mailman'].use_ssl = True
backend = smtp.EmailBackend()
self.assertTrue(backend.use_ssl)
with self.assertRaises(SSLError):
with backend:
pass

def test_connection_timeout_default(self):
"""The connection's timeout value is None by default."""
self.app.extensions['mailman'].backend = "smtp"
Expand Down

0 comments on commit 306d5a6

Please sign in to comment.