simple-module-mail 0.0.48__tar.gz → 0.0.50__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/PKG-INFO +9 -7
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/README.md +5 -3
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/core/constants.py +3 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/core/data_compatibility.py +2 -2
- simple_module_mail-0.0.50/mail/core/settings.py +70 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/core/transports.py +3 -2
- simple_module_mail-0.0.50/mail/delivery/_destination.py +126 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/delivery/runtime.py +4 -4
- simple_module_mail-0.0.50/mail/delivery/sender.py +148 -0
- simple_module_mail-0.0.50/mail/locales/de.json +49 -0
- simple_module_mail-0.0.50/mail/locales/en.json +49 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/module.py +8 -8
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/pyproject.toml +4 -4
- simple_module_mail-0.0.50/tests/conftest.py +20 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/core/module/test_mail_lifecycle.py +3 -3
- simple_module_mail-0.0.50/tests/core/settings/test_mail_settings.py +79 -0
- simple_module_mail-0.0.50/tests/core/settings/test_mail_settings_save.py +80 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/delivery/runtime/test_mail_health.py +6 -5
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/delivery/runtime/test_mail_reload_failures.py +7 -7
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/delivery/runtime/test_mail_transports.py +7 -7
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/delivery/sender/test_mail_address_headers.py +51 -8
- simple_module_mail-0.0.50/tests/delivery/sender/test_mail_headers.py +155 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/delivery/sender/test_mail_outbox.py +18 -10
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/delivery/sender/test_mail_sender.py +65 -28
- simple_module_mail-0.0.50/tests/delivery/sender/test_mail_starttls_connection.py +106 -0
- simple_module_mail-0.0.50/tests/delivery/sender/test_smtp_destination.py +254 -0
- simple_module_mail-0.0.50/tests/delivery/sender/test_smtp_socket_ownership.py +128 -0
- simple_module_mail-0.0.48/mail/core/settings.py +0 -31
- simple_module_mail-0.0.48/mail/delivery/sender.py +0 -108
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/.gitignore +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/LICENSE +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/__init__.py +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/contracts/__init__.py +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/core/__init__.py +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/core/state.py +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/delivery/__init__.py +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/mail/py.typed +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/core/data_compatibility/test_mail_data_compatibility.py +0 -0
- {simple_module_mail-0.0.48 → simple_module_mail-0.0.50}/tests/core/settings/test_mail_settings_migration.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: simple_module_mail
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.50
|
|
4
4
|
Summary: Outgoing mail (SMTP or console) for simple_module apps, configured from the DB-backed settings
|
|
5
5
|
Project-URL: Homepage, https://github.com/antosubash/simple_module_python
|
|
6
6
|
Project-URL: Repository, https://github.com/antosubash/simple_module_python
|
|
@@ -11,9 +11,9 @@ License-Expression: MIT
|
|
|
11
11
|
License-File: LICENSE
|
|
12
12
|
Keywords: email,mail,simple-module,smtp
|
|
13
13
|
Requires-Python: >=3.12
|
|
14
|
-
Requires-Dist: aiosmtplib<6,>=
|
|
15
|
-
Requires-Dist: simple-module-core==0.0.
|
|
16
|
-
Requires-Dist: simple-module-settings==0.0.
|
|
14
|
+
Requires-Dist: aiosmtplib<6,>=4.0
|
|
15
|
+
Requires-Dist: simple-module-core==0.0.50
|
|
16
|
+
Requires-Dist: simple-module-settings==0.0.50
|
|
17
17
|
Description-Content-Type: text/markdown
|
|
18
18
|
|
|
19
19
|
# simple_module_mail
|
|
@@ -21,7 +21,7 @@ Description-Content-Type: text/markdown
|
|
|
21
21
|
Outgoing mail for `simple_module` apps. The module owns the transport (SMTP via
|
|
22
22
|
`aiosmtplib`, or a console backend that logs each message) and its settings, and
|
|
23
23
|
installs a process-level sender that any module can use through
|
|
24
|
-
`simple_module_core.mail` without knowing whether mail is configured.
|
|
24
|
+
`simple_module_core.mailer.mail` without knowing whether mail is configured.
|
|
25
25
|
|
|
26
26
|
The default backend is `console`: messages are logged, nothing is delivered.
|
|
27
27
|
Switch to `smtp` and fill in the server details to deliver real email.
|
|
@@ -44,7 +44,9 @@ uv sync --all-packages
|
|
|
44
44
|
|
|
45
45
|
1. Sign in as an admin and open **Settings -> Modules -> Mail**.
|
|
46
46
|
2. Set `backend` to `smtp` and fill `smtp_host`, `smtp_port`, `smtp_username`,
|
|
47
|
-
`smtp_password` (masked in the UI), `smtp_from
|
|
47
|
+
`smtp_password` (masked in the UI), `smtp_from`, `smtp_tls` and
|
|
48
|
+
`smtp_tls_mode` (`auto`, `starttls` or `implicit`). Use `implicit` for
|
|
49
|
+
implicit TLS on custom ports; `smtp_tls=false` disables TLS in every mode. Saving
|
|
48
50
|
rebuilds the sender live, no restart needed.
|
|
49
51
|
3. Use **Test connection** to run the `mail.mailer` health check. It logs in to
|
|
50
52
|
the server and hangs up without sending anything.
|
|
@@ -52,7 +54,7 @@ uv sync --all-packages
|
|
|
52
54
|
From code, send through the core interface:
|
|
53
55
|
|
|
54
56
|
```python
|
|
55
|
-
from simple_module_core.mail import MailMessage, current_mail_sender
|
|
57
|
+
from simple_module_core.mailer.mail import MailMessage, current_mail_sender
|
|
56
58
|
|
|
57
59
|
await current_mail_sender().send(
|
|
58
60
|
MailMessage(to="a@example.com", subject="Hello", text="Plain body")
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Outgoing mail for `simple_module` apps. The module owns the transport (SMTP via
|
|
4
4
|
`aiosmtplib`, or a console backend that logs each message) and its settings, and
|
|
5
5
|
installs a process-level sender that any module can use through
|
|
6
|
-
`simple_module_core.mail` without knowing whether mail is configured.
|
|
6
|
+
`simple_module_core.mailer.mail` without knowing whether mail is configured.
|
|
7
7
|
|
|
8
8
|
The default backend is `console`: messages are logged, nothing is delivered.
|
|
9
9
|
Switch to `smtp` and fill in the server details to deliver real email.
|
|
@@ -26,7 +26,9 @@ uv sync --all-packages
|
|
|
26
26
|
|
|
27
27
|
1. Sign in as an admin and open **Settings -> Modules -> Mail**.
|
|
28
28
|
2. Set `backend` to `smtp` and fill `smtp_host`, `smtp_port`, `smtp_username`,
|
|
29
|
-
`smtp_password` (masked in the UI), `smtp_from
|
|
29
|
+
`smtp_password` (masked in the UI), `smtp_from`, `smtp_tls` and
|
|
30
|
+
`smtp_tls_mode` (`auto`, `starttls` or `implicit`). Use `implicit` for
|
|
31
|
+
implicit TLS on custom ports; `smtp_tls=false` disables TLS in every mode. Saving
|
|
30
32
|
rebuilds the sender live, no restart needed.
|
|
31
33
|
3. Use **Test connection** to run the `mail.mailer` health check. It logs in to
|
|
32
34
|
the server and hangs up without sending anything.
|
|
@@ -34,7 +36,7 @@ uv sync --all-packages
|
|
|
34
36
|
From code, send through the core interface:
|
|
35
37
|
|
|
36
38
|
```python
|
|
37
|
-
from simple_module_core.mail import MailMessage, current_mail_sender
|
|
39
|
+
from simple_module_core.mailer.mail import MailMessage, current_mail_sender
|
|
38
40
|
|
|
39
41
|
await current_mail_sender().send(
|
|
40
42
|
MailMessage(to="a@example.com", subject="Hello", text="Plain body")
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Detect system settings that still use the pre-mail-module namespace."""
|
|
2
2
|
|
|
3
|
-
from simple_module_core.data_compatibility import DataCompatibilityIssue
|
|
4
|
-
from simple_module_db.stored_settings import (
|
|
3
|
+
from simple_module_core.migrations.data_compatibility import DataCompatibilityIssue
|
|
4
|
+
from simple_module_db.queries.stored_settings import (
|
|
5
5
|
SCOPE_SYSTEM,
|
|
6
6
|
SYSTEM_SCOPE_ID,
|
|
7
7
|
settings_table_clause,
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Mail module settings — DB-backed via ``register_module_settings``.
|
|
2
|
+
|
|
3
|
+
``smtp_password`` is masked by the settings UI because its name matches the
|
|
4
|
+
secret-field pattern (``simple_module_core.settings.secret_fields.is_secret_field``).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from email.errors import HeaderParseError
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
from pydantic import Field, field_validator
|
|
13
|
+
from pydantic_settings import SettingsConfigDict
|
|
14
|
+
from simple_module_core.mailer.mail import parse_mailbox, smtp_address_header
|
|
15
|
+
from simple_module_core.settings.settings_base import DbBackedSettings
|
|
16
|
+
|
|
17
|
+
from mail.core import constants as c
|
|
18
|
+
from mail.core.transports import TRANSPORT_NAMES
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MailSettings(DbBackedSettings):
|
|
22
|
+
"""Which transport sends mail, and the SMTP account it uses."""
|
|
23
|
+
|
|
24
|
+
# ``DbBackedSettings`` so the DB is the only source (GH #283).
|
|
25
|
+
model_config = SettingsConfigDict(extra="ignore")
|
|
26
|
+
|
|
27
|
+
# Keep unknown stored names intact: lenient hydration must not silently
|
|
28
|
+
# turn an uninstalled production provider into successful console delivery.
|
|
29
|
+
backend: str = Field(default=c.BACKEND_CONSOLE, json_schema_extra={"choices": TRANSPORT_NAMES})
|
|
30
|
+
smtp_host: str = ""
|
|
31
|
+
smtp_port: int = Field(default=c.DEFAULT_SMTP_PORT, ge=c.MIN_PORT, le=c.MAX_PORT)
|
|
32
|
+
smtp_username: str = ""
|
|
33
|
+
smtp_password: str = ""
|
|
34
|
+
smtp_from: str = Field(
|
|
35
|
+
default=c.DEFAULT_FROM,
|
|
36
|
+
json_schema_extra={"persist_normalized": True},
|
|
37
|
+
description="One sender mailbox: addr or Display Name <addr>; "
|
|
38
|
+
"at most 254 address characters and 320 total. Cannot be blank.",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
@field_validator("smtp_from")
|
|
42
|
+
@classmethod
|
|
43
|
+
def _check_smtp_from(cls, value: str) -> str:
|
|
44
|
+
error = (
|
|
45
|
+
"smtp_from must be one mailbox (addr or Display Name <addr>) with a local part "
|
|
46
|
+
"and domain, at most 254 address characters and 320 total, "
|
|
47
|
+
"without control characters; blank is not allowed"
|
|
48
|
+
)
|
|
49
|
+
# Reject controls before trimming can hide them.
|
|
50
|
+
if any(ord(c) < 32 or ord(c) == 127 for c in value):
|
|
51
|
+
raise ValueError(error)
|
|
52
|
+
value = value.strip()
|
|
53
|
+
if not value or len(value) > 320:
|
|
54
|
+
raise ValueError(error)
|
|
55
|
+
try:
|
|
56
|
+
address = parse_mailbox(value, allow_smtputf8=True)
|
|
57
|
+
smtp_address_header(value)
|
|
58
|
+
# The stdlib parser also raises these for incomplete quotes/domain literals.
|
|
59
|
+
except (ValueError, HeaderParseError, IndexError, AttributeError) as exc:
|
|
60
|
+
raise ValueError(error) from exc
|
|
61
|
+
if len(address.addr_spec) > 254:
|
|
62
|
+
raise ValueError(error)
|
|
63
|
+
return value
|
|
64
|
+
|
|
65
|
+
smtp_tls: bool = True
|
|
66
|
+
smtp_tls_mode: Literal["auto", "starttls", "implicit"] = Field(
|
|
67
|
+
default=c.SMTP_TLS_AUTO,
|
|
68
|
+
description="auto: implicit TLS on 465, STARTTLS elsewhere; starttls or implicit: "
|
|
69
|
+
"force that mode on any port. Ignored when smtp_tls is false.",
|
|
70
|
+
)
|
|
@@ -8,8 +8,8 @@ from collections.abc import Callable
|
|
|
8
8
|
from dataclasses import dataclass
|
|
9
9
|
from typing import Any
|
|
10
10
|
|
|
11
|
-
from simple_module_core.mail import ConsoleMailSender, MailSender
|
|
12
|
-
from simple_module_core.settings_base import DbBackedSettings
|
|
11
|
+
from simple_module_core.mailer.mail import ConsoleMailSender, MailSender
|
|
12
|
+
from simple_module_core.settings.settings_base import DbBackedSettings
|
|
13
13
|
|
|
14
14
|
from mail.core import constants as c
|
|
15
15
|
|
|
@@ -38,6 +38,7 @@ def _smtp(settings: Any, log_bodies: bool) -> MailSender:
|
|
|
38
38
|
password=settings.smtp_password,
|
|
39
39
|
from_address=settings.smtp_from,
|
|
40
40
|
use_tls=settings.smtp_tls,
|
|
41
|
+
tls_mode=settings.smtp_tls_mode,
|
|
41
42
|
)
|
|
42
43
|
|
|
43
44
|
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Resolve, vet and pin SMTP destinations before handing sockets to aiosmtplib."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import ipaddress
|
|
5
|
+
import logging
|
|
6
|
+
import socket
|
|
7
|
+
from collections.abc import AsyncGenerator
|
|
8
|
+
from contextlib import asynccontextmanager, suppress
|
|
9
|
+
from typing import cast
|
|
10
|
+
|
|
11
|
+
import aiosmtplib
|
|
12
|
+
|
|
13
|
+
from mail.core.constants import SMTP_TIMEOUT_SECONDS
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
_METADATA_ADDRESSES = frozenset(
|
|
17
|
+
ipaddress.ip_address(address) for address in ("fd00:ec2::254", "100.100.100.200", "192.0.0.192")
|
|
18
|
+
)
|
|
19
|
+
_NAT64_V6 = ipaddress.IPv6Network("64:ff9b::/96")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _refused(address: str) -> bool:
|
|
23
|
+
ip = ipaddress.ip_address(address.split("%", 1)[0])
|
|
24
|
+
if isinstance(ip, ipaddress.IPv6Address):
|
|
25
|
+
if ip.sixtofour is not None and _refused(str(ip.sixtofour)):
|
|
26
|
+
return True
|
|
27
|
+
if ip.teredo is not None and any(_refused(str(endpoint)) for endpoint in ip.teredo):
|
|
28
|
+
return True
|
|
29
|
+
# ipaddress labels even globally usable NAT64 destinations as reserved.
|
|
30
|
+
if ip in _NAT64_V6:
|
|
31
|
+
ip = ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF)
|
|
32
|
+
else:
|
|
33
|
+
ip = ip.ipv4_mapped or ip
|
|
34
|
+
# IPv6 loopback is also classified as reserved by ipaddress.
|
|
35
|
+
return not ip.is_loopback and (
|
|
36
|
+
ip.is_link_local
|
|
37
|
+
or ip.is_unspecified
|
|
38
|
+
or ip.is_multicast
|
|
39
|
+
or ip.is_reserved
|
|
40
|
+
or ip in _METADATA_ADDRESSES
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def _connect(host: str, port: int) -> socket.socket:
|
|
45
|
+
loop = asyncio.get_running_loop()
|
|
46
|
+
async with asyncio.timeout(SMTP_TIMEOUT_SECONDS):
|
|
47
|
+
answers = await loop.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
48
|
+
if not answers:
|
|
49
|
+
raise OSError("SMTP hostname resolved to no addresses")
|
|
50
|
+
# Check every answer before opening any socket, including mixed-family DNS.
|
|
51
|
+
if any(_refused(cast(str, answer[4][0])) for answer in answers):
|
|
52
|
+
reason = (
|
|
53
|
+
"SMTP destination refused: link-local, metadata, unspecified, "
|
|
54
|
+
"multicast or reserved address"
|
|
55
|
+
)
|
|
56
|
+
logger.warning(reason)
|
|
57
|
+
raise ValueError(reason)
|
|
58
|
+
for index, (family, kind, proto, _, address) in enumerate(answers):
|
|
59
|
+
sock = socket.socket(family, kind, proto)
|
|
60
|
+
try:
|
|
61
|
+
sock.setblocking(False)
|
|
62
|
+
# Numeric sockaddr: sock_connect never resolves the configured name again.
|
|
63
|
+
await loop.sock_connect(sock, address)
|
|
64
|
+
except OSError:
|
|
65
|
+
sock.close()
|
|
66
|
+
if index == len(answers) - 1:
|
|
67
|
+
raise
|
|
68
|
+
except BaseException:
|
|
69
|
+
sock.close()
|
|
70
|
+
raise
|
|
71
|
+
else:
|
|
72
|
+
return sock
|
|
73
|
+
raise OSError("SMTP hostname resolved to no usable addresses")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _SocketSMTP(aiosmtplib.SMTP):
|
|
77
|
+
"""Remember ownership even after aiosmtplib clears its transport on failure."""
|
|
78
|
+
|
|
79
|
+
socket_transferred = False
|
|
80
|
+
|
|
81
|
+
def close(self) -> None:
|
|
82
|
+
# connect() also calls close() on greeting/TLS errors, clearing transport.
|
|
83
|
+
self.socket_transferred |= self.transport is not None
|
|
84
|
+
super().close()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@asynccontextmanager
|
|
88
|
+
async def _smtp_connection(
|
|
89
|
+
host: str,
|
|
90
|
+
port: int,
|
|
91
|
+
*,
|
|
92
|
+
username: str,
|
|
93
|
+
password: str,
|
|
94
|
+
use_tls: bool,
|
|
95
|
+
start_tls: bool,
|
|
96
|
+
) -> AsyncGenerator[aiosmtplib.SMTP]:
|
|
97
|
+
try:
|
|
98
|
+
sock = await _connect(host, port)
|
|
99
|
+
except TimeoutError as exc:
|
|
100
|
+
raise TimeoutError("Timed out resolving or connecting to SMTP destination") from exc
|
|
101
|
+
try:
|
|
102
|
+
# Keep the configured hostname for TLS verification/SNI with a pinned socket.
|
|
103
|
+
client = _SocketSMTP(
|
|
104
|
+
hostname=host,
|
|
105
|
+
sock=sock,
|
|
106
|
+
use_tls=use_tls,
|
|
107
|
+
start_tls=start_tls,
|
|
108
|
+
timeout=SMTP_TIMEOUT_SECONDS,
|
|
109
|
+
)
|
|
110
|
+
except BaseException:
|
|
111
|
+
sock.close()
|
|
112
|
+
raise
|
|
113
|
+
try:
|
|
114
|
+
await client.connect()
|
|
115
|
+
try:
|
|
116
|
+
if username:
|
|
117
|
+
await client.login(username, password)
|
|
118
|
+
yield client
|
|
119
|
+
finally:
|
|
120
|
+
# A hangup failure must not mask a login or delivery error.
|
|
121
|
+
with suppress(Exception):
|
|
122
|
+
await client.quit()
|
|
123
|
+
finally:
|
|
124
|
+
client.close()
|
|
125
|
+
if not client.socket_transferred:
|
|
126
|
+
sock.close()
|
|
@@ -7,15 +7,15 @@ from typing import Any
|
|
|
7
7
|
|
|
8
8
|
from settings.core.service import SettingService
|
|
9
9
|
from settings.module_settings.store import SettingsStore
|
|
10
|
-
from simple_module_core.
|
|
11
|
-
from simple_module_core.health import HealthCheckResult, HealthStatus
|
|
12
|
-
from simple_module_core.mail import (
|
|
10
|
+
from simple_module_core.mailer.mail import (
|
|
13
11
|
MailMessage,
|
|
14
12
|
MailSender,
|
|
15
13
|
current_mail_sender,
|
|
16
14
|
install_default_mail_sender,
|
|
17
15
|
)
|
|
18
|
-
from simple_module_core.
|
|
16
|
+
from simple_module_core.settings.environments import NON_PROD_ENVIRONMENTS
|
|
17
|
+
from simple_module_core.settings.settings_hydrate import hydrate_settings
|
|
18
|
+
from simple_module_core.web.health import HealthCheckResult, HealthStatus
|
|
19
19
|
|
|
20
20
|
from mail.core import constants as c
|
|
21
21
|
from mail.core.settings import MailSettings
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Mail senders and the settings -> sender mapping."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from email import policy
|
|
6
|
+
from email.message import EmailMessage
|
|
7
|
+
from email.utils import formatdate, make_msgid
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from simple_module_core.mailer.mail import (
|
|
11
|
+
MailMessage,
|
|
12
|
+
MailSender,
|
|
13
|
+
smtp_address_header,
|
|
14
|
+
validate_mail_headers,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
from mail.core import constants as c
|
|
18
|
+
from mail.core.settings import MailSettings
|
|
19
|
+
from mail.core.transports import get_mail_transport
|
|
20
|
+
from mail.delivery._destination import _smtp_connection
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _SmtpPolicy(policy.EmailPolicy):
|
|
24
|
+
"""Keep UTF-8 header lines within SMTP's byte limit."""
|
|
25
|
+
|
|
26
|
+
def fold_binary(self, name: str, value: Any) -> bytes:
|
|
27
|
+
folded = super().fold_binary(name, value)
|
|
28
|
+
if self.utf8 and any(len(line) > 998 for line in folded.split(b"\r\n")):
|
|
29
|
+
# The stdlib counts characters; UTF-8 needs up to four bytes each.
|
|
30
|
+
return policy.EmailPolicy.fold_binary(self.clone(max_line_length=998 // 4), name, value)
|
|
31
|
+
return folded
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _tls_kwargs(port: int, use_tls: bool, mode: str) -> dict[str, bool]:
|
|
35
|
+
"""An explicit mode overrides port inference; the TLS switch still wins."""
|
|
36
|
+
implicit = mode == c.SMTP_TLS_IMPLICIT or (mode == c.SMTP_TLS_AUTO and port == c.SMTP_TLS_PORT)
|
|
37
|
+
return {"use_tls": use_tls and implicit, "start_tls": use_tls and not implicit}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class SmtpMailSender:
|
|
41
|
+
"""Delivers through an SMTP server with aiosmtplib."""
|
|
42
|
+
|
|
43
|
+
delivers_email = True
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
host: str,
|
|
48
|
+
port: int,
|
|
49
|
+
username: str,
|
|
50
|
+
password: str,
|
|
51
|
+
from_address: str,
|
|
52
|
+
use_tls: bool,
|
|
53
|
+
tls_mode: str = c.SMTP_TLS_AUTO,
|
|
54
|
+
) -> None:
|
|
55
|
+
self._host = host
|
|
56
|
+
self._port = port
|
|
57
|
+
self._username = username
|
|
58
|
+
self._password = password
|
|
59
|
+
self._from = from_address
|
|
60
|
+
self._use_tls = use_tls
|
|
61
|
+
self._tls_mode = tls_mode
|
|
62
|
+
|
|
63
|
+
async def send(self, message: MailMessage) -> None:
|
|
64
|
+
email = EmailMessage()
|
|
65
|
+
email["From"] = smtp_address_header(self._from)
|
|
66
|
+
email["To"] = smtp_address_header(message.to)
|
|
67
|
+
if message.reply_to is not None:
|
|
68
|
+
email["Reply-To"] = smtp_address_header(message.reply_to)
|
|
69
|
+
email["Subject"] = message.subject
|
|
70
|
+
email["Date"] = formatdate(localtime=False, usegmt=True)
|
|
71
|
+
from_header = email["From"]
|
|
72
|
+
domain = None
|
|
73
|
+
if not from_header.defects and len(from_header.addresses) == 1:
|
|
74
|
+
domain = from_header.addresses[0].domain or None
|
|
75
|
+
email["Message-ID"] = make_msgid(domain=domain)
|
|
76
|
+
# Revalidate because a frozen dataclass can still contain a mutable dictionary.
|
|
77
|
+
for name, value in validate_mail_headers(message.headers).items():
|
|
78
|
+
email[name] = value
|
|
79
|
+
email.set_content(message.text)
|
|
80
|
+
if message.html:
|
|
81
|
+
email.add_alternative(message.html, subtype="html")
|
|
82
|
+
for attachment in message.attachments:
|
|
83
|
+
maintype, subtype = attachment.content_type.split("/")
|
|
84
|
+
email.add_attachment(
|
|
85
|
+
attachment.content,
|
|
86
|
+
maintype=maintype,
|
|
87
|
+
subtype=subtype,
|
|
88
|
+
filename=attachment.filename,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Never infer the SMTP envelope from custom or trace headers.
|
|
92
|
+
sender = from_header.addresses[0].addr_spec
|
|
93
|
+
recipients = [address.addr_spec for address in email["To"].addresses]
|
|
94
|
+
utf8_required = not (sender.isascii() and all(address.isascii() for address in recipients))
|
|
95
|
+
# Typeshed's EmailPolicy constructor self type excludes subclasses.
|
|
96
|
+
wire_policy = _SmtpPolicy( # ty: ignore[invalid-argument-type]
|
|
97
|
+
utf8=utf8_required, linesep="\r\n"
|
|
98
|
+
)
|
|
99
|
+
# Avoid encoded words in long RFC 2369 URLs; bytes bypass aiosmtplib's refolding.
|
|
100
|
+
wire = email.as_bytes(policy=wire_policy.clone(max_line_length=998, cte_type="7bit"))
|
|
101
|
+
tls = _tls_kwargs(self._port, self._use_tls, self._tls_mode)
|
|
102
|
+
async with _smtp_connection(
|
|
103
|
+
self._host,
|
|
104
|
+
self._port,
|
|
105
|
+
username=self._username,
|
|
106
|
+
password=self._password,
|
|
107
|
+
**tls,
|
|
108
|
+
) as client:
|
|
109
|
+
await client.sendmail(
|
|
110
|
+
sender,
|
|
111
|
+
recipients,
|
|
112
|
+
wire,
|
|
113
|
+
mail_options=["SMTPUTF8"] if utf8_required else [],
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
async def verify_connection(self) -> None:
|
|
117
|
+
"""Open an SMTP session and authenticate, then hang up.
|
|
118
|
+
|
|
119
|
+
Deliberately stops short of sending anything: an admin checking their
|
|
120
|
+
config should not put a stray message in someone's inbox. Raises
|
|
121
|
+
whatever aiosmtplib raises so the caller can show the real reason.
|
|
122
|
+
"""
|
|
123
|
+
tls = _tls_kwargs(self._port, self._use_tls, self._tls_mode)
|
|
124
|
+
async with _smtp_connection(
|
|
125
|
+
self._host,
|
|
126
|
+
self._port,
|
|
127
|
+
username=self._username,
|
|
128
|
+
password=self._password,
|
|
129
|
+
**tls,
|
|
130
|
+
):
|
|
131
|
+
pass
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def build_sender(
|
|
135
|
+
settings: MailSettings,
|
|
136
|
+
*,
|
|
137
|
+
log_bodies: bool = True,
|
|
138
|
+
development: bool = True,
|
|
139
|
+
options: Any = None,
|
|
140
|
+
) -> MailSender:
|
|
141
|
+
"""Build the selected registered transport with its module-owned options.
|
|
142
|
+
|
|
143
|
+
*log_bodies* is false outside development and testing: a console backend
|
|
144
|
+
left in place in production must not write reset and invite tokens to the
|
|
145
|
+
log, so there it logs only recipient, subject and attachment metadata.
|
|
146
|
+
"""
|
|
147
|
+
transport = get_mail_transport(settings.backend, development=development)
|
|
148
|
+
return transport.factory(settings if options is None else options, log_bodies)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"settings_form": {
|
|
3
|
+
"title": "E-Mail",
|
|
4
|
+
"description": "Wie ausgehende E-Mails versendet werden und welches SMTP-Konto dafür genutzt wird.",
|
|
5
|
+
"fields": {
|
|
6
|
+
"backend": {
|
|
7
|
+
"label": "Versandart",
|
|
8
|
+
"help": "Wie E-Mails zugestellt werden. Konsole versendet nichts und protokolliert die Nachrichten nur (den Inhalt nur in Entwicklung und Tests).",
|
|
9
|
+
"choices": {
|
|
10
|
+
"console": "Konsole (nur Protokoll)",
|
|
11
|
+
"smtp": "SMTP"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"smtp_host": {
|
|
15
|
+
"label": "SMTP-Host",
|
|
16
|
+
"help": "Hostname des SMTP-Servers."
|
|
17
|
+
},
|
|
18
|
+
"smtp_port": {
|
|
19
|
+
"label": "SMTP-Port",
|
|
20
|
+
"help": "Port des SMTP-Servers, meist 587 oder 465."
|
|
21
|
+
},
|
|
22
|
+
"smtp_username": {
|
|
23
|
+
"label": "SMTP-Benutzername",
|
|
24
|
+
"help": "Kontoname für den SMTP-Server. Leer lassen, wenn keine Anmeldung nötig ist."
|
|
25
|
+
},
|
|
26
|
+
"smtp_password": {
|
|
27
|
+
"label": "SMTP-Passwort",
|
|
28
|
+
"help": "Passwort für dieses Konto. Nach dem Speichern wird es ausgeblendet."
|
|
29
|
+
},
|
|
30
|
+
"smtp_from": {
|
|
31
|
+
"label": "Absenderadresse",
|
|
32
|
+
"help": "Adresse, die als Absender ausgehender E-Mails erscheint."
|
|
33
|
+
},
|
|
34
|
+
"smtp_tls": {
|
|
35
|
+
"label": "TLS verwenden",
|
|
36
|
+
"help": "Die Verbindung zum SMTP-Server verschlüsseln."
|
|
37
|
+
},
|
|
38
|
+
"smtp_tls_mode": {
|
|
39
|
+
"label": "TLS-Modus",
|
|
40
|
+
"help": "Automatisch nutzt implizites TLS auf Port 465, sonst STARTTLS. Alternativ lässt sich ein Modus für jeden Port erzwingen. Wird ignoriert, wenn TLS aus ist.",
|
|
41
|
+
"choices": {
|
|
42
|
+
"auto": "Automatisch",
|
|
43
|
+
"implicit": "Implizites TLS",
|
|
44
|
+
"starttls": "STARTTLS"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"settings_form": {
|
|
3
|
+
"title": "Mail",
|
|
4
|
+
"description": "How outgoing mail is sent and the SMTP account it uses.",
|
|
5
|
+
"fields": {
|
|
6
|
+
"backend": {
|
|
7
|
+
"label": "Delivery method",
|
|
8
|
+
"help": "How mail is delivered. Console sends nothing and only logs the messages (the body only in development and testing).",
|
|
9
|
+
"choices": {
|
|
10
|
+
"console": "Console (log only)",
|
|
11
|
+
"smtp": "SMTP"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"smtp_host": {
|
|
15
|
+
"label": "SMTP host",
|
|
16
|
+
"help": "Hostname of the SMTP server."
|
|
17
|
+
},
|
|
18
|
+
"smtp_port": {
|
|
19
|
+
"label": "SMTP port",
|
|
20
|
+
"help": "Port of the SMTP server, usually 587 or 465."
|
|
21
|
+
},
|
|
22
|
+
"smtp_username": {
|
|
23
|
+
"label": "SMTP username",
|
|
24
|
+
"help": "Account name for the SMTP server. Leave blank if it needs no sign-in."
|
|
25
|
+
},
|
|
26
|
+
"smtp_password": {
|
|
27
|
+
"label": "SMTP password",
|
|
28
|
+
"help": "Password for that account. It is hidden once saved."
|
|
29
|
+
},
|
|
30
|
+
"smtp_from": {
|
|
31
|
+
"label": "Sender address",
|
|
32
|
+
"help": "Address that appears as the sender of outgoing mail."
|
|
33
|
+
},
|
|
34
|
+
"smtp_tls": {
|
|
35
|
+
"label": "Use TLS",
|
|
36
|
+
"help": "Encrypt the connection to the SMTP server."
|
|
37
|
+
},
|
|
38
|
+
"smtp_tls_mode": {
|
|
39
|
+
"label": "TLS mode",
|
|
40
|
+
"help": "Auto uses implicit TLS on port 465 and STARTTLS elsewhere. Or force one mode on any port. Ignored when TLS is off.",
|
|
41
|
+
"choices": {
|
|
42
|
+
"auto": "Automatic",
|
|
43
|
+
"implicit": "Implicit TLS",
|
|
44
|
+
"starttls": "STARTTLS"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -4,17 +4,17 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
from typing import TYPE_CHECKING, Any
|
|
6
6
|
|
|
7
|
-
from simple_module_core.
|
|
8
|
-
from simple_module_core.
|
|
9
|
-
from simple_module_core.
|
|
7
|
+
from simple_module_core.mailer.mail import install_mail_resolver, install_mail_sender
|
|
8
|
+
from simple_module_core.modules.module import ModuleBase, ModuleMeta
|
|
9
|
+
from simple_module_core.web.health import HealthCheck, HealthRegistry
|
|
10
10
|
|
|
11
11
|
from mail.core import constants as c
|
|
12
12
|
|
|
13
13
|
if TYPE_CHECKING:
|
|
14
14
|
from fastapi import FastAPI
|
|
15
|
-
from simple_module_core.
|
|
16
|
-
from simple_module_core.
|
|
17
|
-
from simple_module_core.
|
|
15
|
+
from simple_module_core.eventing.events import EventBus
|
|
16
|
+
from simple_module_core.eventing.invalidation import InvalidationBus
|
|
17
|
+
from simple_module_core.migrations.data_compatibility import DataCompatibilityIssue
|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
class MailModule(ModuleBase):
|
|
@@ -25,7 +25,7 @@ class MailModule(ModuleBase):
|
|
|
25
25
|
)
|
|
26
26
|
|
|
27
27
|
def register_settings(self, app: FastAPI) -> None:
|
|
28
|
-
from simple_module_core.module_settings import register_module_settings
|
|
28
|
+
from simple_module_core.settings.module_settings import register_module_settings
|
|
29
29
|
|
|
30
30
|
from mail.core.settings import MailSettings
|
|
31
31
|
from mail.core.state import MailState
|
|
@@ -76,7 +76,7 @@ class MailModule(ModuleBase):
|
|
|
76
76
|
|
|
77
77
|
def register_invalidations(self, bus: InvalidationBus, app: FastAPI) -> None:
|
|
78
78
|
from settings.core.invalidation import CHANNEL
|
|
79
|
-
from simple_module_core.invalidation_refresh import InvalidationRefresh
|
|
79
|
+
from simple_module_core.eventing.invalidation_refresh import InvalidationRefresh
|
|
80
80
|
|
|
81
81
|
from mail.delivery.runtime import install_app_sender
|
|
82
82
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "simple_module_mail"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.50"
|
|
4
4
|
description = "Outgoing mail (SMTP or console) for simple_module apps, configured from the DB-backed settings"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -9,9 +9,9 @@ requires-python = ">=3.12"
|
|
|
9
9
|
authors = [{ name = "Anto Subash", email = "antosubash@live.com" }]
|
|
10
10
|
keywords = ["simple-module", "mail", "smtp", "email"]
|
|
11
11
|
dependencies = [
|
|
12
|
-
"simple_module_core==0.0.
|
|
13
|
-
"simple_module_settings==0.0.
|
|
14
|
-
"aiosmtplib>=
|
|
12
|
+
"simple_module_core==0.0.50",
|
|
13
|
+
"simple_module_settings==0.0.50",
|
|
14
|
+
"aiosmtplib>=4.0,<6",
|
|
15
15
|
]
|
|
16
16
|
|
|
17
17
|
[project.entry-points.simple_module]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""SMTP tests use a preconnected socket double instead of external networking."""
|
|
2
|
+
|
|
3
|
+
import socket
|
|
4
|
+
from unittest.mock import AsyncMock, MagicMock
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from mail.delivery._destination import _SocketSMTP
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.fixture
|
|
11
|
+
def smtp_socket(monkeypatch):
|
|
12
|
+
sock = MagicMock(spec=socket.socket)
|
|
13
|
+
monkeypatch.setattr("mail.delivery._destination._connect", AsyncMock(return_value=sock))
|
|
14
|
+
return sock
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@pytest.fixture
|
|
18
|
+
def smtp_delivery(monkeypatch, smtp_socket):
|
|
19
|
+
for method in ("connect", "login", "quit"):
|
|
20
|
+
monkeypatch.setattr(_SocketSMTP, method, AsyncMock())
|