simple-module-mail 0.0.47__tar.gz → 0.0.48__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.47 → simple_module_mail-0.0.48}/.gitignore +6 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/PKG-INFO +3 -3
- simple_module_mail-0.0.48/mail/contracts/__init__.py +5 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/core/data_compatibility.py +5 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/core/settings.py +4 -3
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/core/state.py +1 -0
- simple_module_mail-0.0.48/mail/core/transports.py +89 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/delivery/runtime.py +44 -3
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/delivery/sender.py +30 -16
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/module.py +27 -2
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/pyproject.toml +3 -3
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/tests/core/data_compatibility/test_mail_data_compatibility.py +3 -0
- simple_module_mail-0.0.48/tests/delivery/runtime/test_mail_reload_failures.py +102 -0
- simple_module_mail-0.0.48/tests/delivery/runtime/test_mail_transports.py +257 -0
- simple_module_mail-0.0.48/tests/delivery/sender/test_mail_address_headers.py +80 -0
- simple_module_mail-0.0.48/tests/delivery/sender/test_mail_outbox.py +82 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/tests/delivery/sender/test_mail_sender.py +66 -2
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/LICENSE +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/README.md +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/__init__.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/core/__init__.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/core/constants.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/delivery/__init__.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/mail/py.typed +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/tests/core/module/test_mail_lifecycle.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/tests/core/settings/test_mail_settings_migration.py +0 -0
- {simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/tests/delivery/runtime/test_mail_health.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.48
|
|
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
|
|
@@ -12,8 +12,8 @@ License-File: LICENSE
|
|
|
12
12
|
Keywords: email,mail,simple-module,smtp
|
|
13
13
|
Requires-Python: >=3.12
|
|
14
14
|
Requires-Dist: aiosmtplib<6,>=3.0
|
|
15
|
-
Requires-Dist: simple-module-core==0.0.
|
|
16
|
-
Requires-Dist: simple-module-settings==0.0.
|
|
15
|
+
Requires-Dist: simple-module-core==0.0.48
|
|
16
|
+
Requires-Dist: simple-module-settings==0.0.48
|
|
17
17
|
Description-Content-Type: text/markdown
|
|
18
18
|
|
|
19
19
|
# simple_module_mail
|
|
@@ -34,5 +34,10 @@ async def check_data_compatibility(db: AsyncSession) -> list[DataCompatibilityIs
|
|
|
34
34
|
message="Obsolete system users.mailer/SMTP settings must move to mail.*; "
|
|
35
35
|
"target values win.",
|
|
36
36
|
severity="warning",
|
|
37
|
+
remediation_text=(
|
|
38
|
+
"From the host's development environment, run "
|
|
39
|
+
f"`uv run smpy migrations prepare {UPGRADE_SETTINGS_NAMESPACE} "
|
|
40
|
+
"--head <host-head-or-label@head>`."
|
|
41
|
+
),
|
|
37
42
|
)
|
|
38
43
|
]
|
|
@@ -6,13 +6,12 @@ secret-field pattern (``simple_module_core.secret_fields.is_secret_field``).
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
-
from typing import Literal
|
|
10
|
-
|
|
11
9
|
from pydantic import Field
|
|
12
10
|
from pydantic_settings import SettingsConfigDict
|
|
13
11
|
from simple_module_core.settings_base import DbBackedSettings
|
|
14
12
|
|
|
15
13
|
from mail.core import constants as c
|
|
14
|
+
from mail.core.transports import TRANSPORT_NAMES
|
|
16
15
|
|
|
17
16
|
|
|
18
17
|
class MailSettings(DbBackedSettings):
|
|
@@ -21,7 +20,9 @@ class MailSettings(DbBackedSettings):
|
|
|
21
20
|
# ``DbBackedSettings`` so the DB is the only source (GH #283).
|
|
22
21
|
model_config = SettingsConfigDict(extra="ignore")
|
|
23
22
|
|
|
24
|
-
|
|
23
|
+
# Keep unknown stored names intact: lenient hydration must not silently
|
|
24
|
+
# turn an uninstalled production provider into successful console delivery.
|
|
25
|
+
backend: str = Field(default=c.BACKEND_CONSOLE, json_schema_extra={"choices": TRANSPORT_NAMES})
|
|
25
26
|
smtp_host: str = ""
|
|
26
27
|
smtp_port: int = Field(default=c.DEFAULT_SMTP_PORT, ge=c.MIN_PORT, le=c.MAX_PORT)
|
|
27
28
|
smtp_username: str = ""
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Process-local factories, registered in hooks shared by web and workers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from simple_module_core.mail import ConsoleMailSender, MailSender
|
|
12
|
+
from simple_module_core.settings_base import DbBackedSettings
|
|
13
|
+
|
|
14
|
+
from mail.core import constants as c
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
MailTransportFactory = Callable[[Any, bool], MailSender]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class MailTransport:
|
|
22
|
+
factory: MailTransportFactory
|
|
23
|
+
settings_model: type[DbBackedSettings] | None = None
|
|
24
|
+
package: str | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _console(settings: Any, log_bodies: bool) -> MailSender:
|
|
28
|
+
return ConsoleMailSender(include_body=log_bodies)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _smtp(settings: Any, log_bodies: bool) -> MailSender:
|
|
32
|
+
from mail.delivery.sender import SmtpMailSender
|
|
33
|
+
|
|
34
|
+
return SmtpMailSender(
|
|
35
|
+
host=settings.smtp_host,
|
|
36
|
+
port=settings.smtp_port,
|
|
37
|
+
username=settings.smtp_username,
|
|
38
|
+
password=settings.smtp_password,
|
|
39
|
+
from_address=settings.smtp_from,
|
|
40
|
+
use_tls=settings.smtp_tls,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_transports: dict[str, MailTransport] = {
|
|
45
|
+
c.BACKEND_CONSOLE: MailTransport(_console),
|
|
46
|
+
c.BACKEND_SMTP: MailTransport(_smtp),
|
|
47
|
+
}
|
|
48
|
+
# Shared with field metadata so the generic admin select sees later registrations.
|
|
49
|
+
TRANSPORT_NAMES = sorted(_transports)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def register_mail_transport(
|
|
53
|
+
name: str,
|
|
54
|
+
factory: MailTransportFactory,
|
|
55
|
+
*,
|
|
56
|
+
settings_model: type[DbBackedSettings] | None = None,
|
|
57
|
+
package: str | None = None,
|
|
58
|
+
) -> None:
|
|
59
|
+
"""Register a synchronous factory(options, log_bodies) in each process.
|
|
60
|
+
|
|
61
|
+
Call in ``register_event_handlers`` before returning for ``app is None``.
|
|
62
|
+
With a settings model, *package* names its registered module settings;
|
|
63
|
+
otherwise the factory receives ``MailSettings``. Identical registration
|
|
64
|
+
is idempotent; conflicting names (including built-ins) are rejected.
|
|
65
|
+
"""
|
|
66
|
+
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", name):
|
|
67
|
+
raise ValueError("Mail transport names must be lowercase slugs")
|
|
68
|
+
if (settings_model is None) != (package is None):
|
|
69
|
+
raise ValueError("Mail transport settings_model and package must be supplied together")
|
|
70
|
+
if settings_model is not None and not issubclass(settings_model, DbBackedSettings):
|
|
71
|
+
raise TypeError("Mail transport settings must inherit DbBackedSettings")
|
|
72
|
+
transport = MailTransport(factory, settings_model, package)
|
|
73
|
+
if name in _transports and _transports[name] != transport:
|
|
74
|
+
raise ValueError(f"Mail transport {name!r} is already registered")
|
|
75
|
+
_transports[name] = transport
|
|
76
|
+
TRANSPORT_NAMES[:] = sorted(_transports)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_mail_transport(name: str, *, development: bool = False) -> MailTransport:
|
|
80
|
+
"""Fail clearly for a missing provider; development may log instead."""
|
|
81
|
+
if name in _transports:
|
|
82
|
+
return _transports[name]
|
|
83
|
+
message = (
|
|
84
|
+
f"Unknown mail transport {name!r}; registered transports: {', '.join(TRANSPORT_NAMES)}"
|
|
85
|
+
)
|
|
86
|
+
if not development:
|
|
87
|
+
raise ValueError(message)
|
|
88
|
+
logger.warning("%s; falling back to console", message)
|
|
89
|
+
return _transports[c.BACKEND_CONSOLE]
|
|
@@ -9,11 +9,17 @@ from settings.core.service import SettingService
|
|
|
9
9
|
from settings.module_settings.store import SettingsStore
|
|
10
10
|
from simple_module_core.environments import NON_PROD_ENVIRONMENTS
|
|
11
11
|
from simple_module_core.health import HealthCheckResult, HealthStatus
|
|
12
|
-
from simple_module_core.mail import
|
|
12
|
+
from simple_module_core.mail import (
|
|
13
|
+
MailMessage,
|
|
14
|
+
MailSender,
|
|
15
|
+
current_mail_sender,
|
|
16
|
+
install_default_mail_sender,
|
|
17
|
+
)
|
|
13
18
|
from simple_module_core.settings_hydrate import hydrate_settings
|
|
14
19
|
|
|
15
20
|
from mail.core import constants as c
|
|
16
21
|
from mail.core.settings import MailSettings
|
|
22
|
+
from mail.core.transports import get_mail_transport
|
|
17
23
|
from mail.delivery.sender import build_sender
|
|
18
24
|
|
|
19
25
|
|
|
@@ -24,7 +30,16 @@ async def resolve_sender_from_db(db: Any) -> MailSender:
|
|
|
24
30
|
"""
|
|
25
31
|
store = SettingsStore(SettingService(db))
|
|
26
32
|
settings = await hydrate_settings(MailSettings, store, c.MODULE_PACKAGE, lenient=True)
|
|
27
|
-
|
|
33
|
+
development = os.environ.get("SM_ENVIRONMENT", "development") == "development"
|
|
34
|
+
transport = get_mail_transport(settings.backend, development=development)
|
|
35
|
+
options = None
|
|
36
|
+
if transport.settings_model is not None and transport.package is not None:
|
|
37
|
+
options = await hydrate_settings(
|
|
38
|
+
transport.settings_model, store, transport.package, lenient=True
|
|
39
|
+
)
|
|
40
|
+
return build_sender(
|
|
41
|
+
settings, options=options, log_bodies=_worker_is_non_prod(), development=development
|
|
42
|
+
)
|
|
28
43
|
|
|
29
44
|
|
|
30
45
|
def _worker_is_non_prod() -> bool:
|
|
@@ -33,13 +48,39 @@ def _worker_is_non_prod() -> bool:
|
|
|
33
48
|
return os.environ.get("SM_ENVIRONMENT", "development") in NON_PROD_ENVIRONMENTS
|
|
34
49
|
|
|
35
50
|
|
|
51
|
+
class _UnavailableMailSender:
|
|
52
|
+
# Keep callers on the send path so durable delivery fails and retries.
|
|
53
|
+
delivers_email = True
|
|
54
|
+
|
|
55
|
+
async def send(self, message: MailMessage) -> None:
|
|
56
|
+
await self.verify_connection()
|
|
57
|
+
|
|
58
|
+
async def verify_connection(self) -> None:
|
|
59
|
+
raise RuntimeError("Mail transport is unavailable: configured sender construction failed")
|
|
60
|
+
|
|
61
|
+
|
|
36
62
|
def install_app_sender(app: Any) -> None:
|
|
37
63
|
"""Install a sender built from *app*'s current mail settings.
|
|
38
64
|
|
|
39
65
|
Bodies are logged only in development or testing (host ``environment``).
|
|
40
66
|
"""
|
|
41
67
|
log_bodies = app.state.sm.settings.environment in NON_PROD_ENVIRONMENTS
|
|
42
|
-
|
|
68
|
+
development = app.state.sm.settings.environment == "development"
|
|
69
|
+
settings = app.state.mail.settings
|
|
70
|
+
try:
|
|
71
|
+
transport = get_mail_transport(settings.backend, development=development)
|
|
72
|
+
options = None
|
|
73
|
+
if transport.package is not None:
|
|
74
|
+
options = getattr(app.state, transport.package).settings
|
|
75
|
+
sender = build_sender(
|
|
76
|
+
settings, options=options, log_bodies=log_bodies, development=development
|
|
77
|
+
)
|
|
78
|
+
except Exception:
|
|
79
|
+
app.state.mail.sender_failed = True
|
|
80
|
+
install_default_mail_sender(_UnavailableMailSender())
|
|
81
|
+
raise
|
|
82
|
+
app.state.mail.sender_failed = False
|
|
83
|
+
install_default_mail_sender(sender)
|
|
43
84
|
|
|
44
85
|
|
|
45
86
|
async def check_smtp() -> HealthCheckResult:
|
|
@@ -4,12 +4,18 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import contextlib
|
|
6
6
|
from email.message import EmailMessage
|
|
7
|
+
from typing import Any
|
|
7
8
|
|
|
8
9
|
import aiosmtplib
|
|
9
|
-
from simple_module_core.mail import
|
|
10
|
+
from simple_module_core.mail import (
|
|
11
|
+
MailMessage,
|
|
12
|
+
MailSender,
|
|
13
|
+
smtp_address_header,
|
|
14
|
+
)
|
|
10
15
|
|
|
11
16
|
from mail.core import constants as c
|
|
12
17
|
from mail.core.settings import MailSettings
|
|
18
|
+
from mail.core.transports import get_mail_transport
|
|
13
19
|
|
|
14
20
|
|
|
15
21
|
class SmtpMailSender:
|
|
@@ -35,12 +41,22 @@ class SmtpMailSender:
|
|
|
35
41
|
|
|
36
42
|
async def send(self, message: MailMessage) -> None:
|
|
37
43
|
email = EmailMessage()
|
|
38
|
-
email["From"] = self._from
|
|
39
|
-
email["To"] = message.to
|
|
44
|
+
email["From"] = smtp_address_header(self._from)
|
|
45
|
+
email["To"] = smtp_address_header(message.to)
|
|
46
|
+
if message.reply_to is not None:
|
|
47
|
+
email["Reply-To"] = smtp_address_header(message.reply_to)
|
|
40
48
|
email["Subject"] = message.subject
|
|
41
49
|
email.set_content(message.text)
|
|
42
50
|
if message.html:
|
|
43
51
|
email.add_alternative(message.html, subtype="html")
|
|
52
|
+
for attachment in message.attachments:
|
|
53
|
+
maintype, subtype = attachment.content_type.split("/")
|
|
54
|
+
email.add_attachment(
|
|
55
|
+
attachment.content,
|
|
56
|
+
maintype=maintype,
|
|
57
|
+
subtype=subtype,
|
|
58
|
+
filename=attachment.filename,
|
|
59
|
+
)
|
|
44
60
|
|
|
45
61
|
await aiosmtplib.send(
|
|
46
62
|
email,
|
|
@@ -75,20 +91,18 @@ class SmtpMailSender:
|
|
|
75
91
|
await client.quit()
|
|
76
92
|
|
|
77
93
|
|
|
78
|
-
def build_sender(
|
|
79
|
-
|
|
94
|
+
def build_sender(
|
|
95
|
+
settings: MailSettings,
|
|
96
|
+
*,
|
|
97
|
+
log_bodies: bool = True,
|
|
98
|
+
development: bool = True,
|
|
99
|
+
options: Any = None,
|
|
100
|
+
) -> MailSender:
|
|
101
|
+
"""Build the selected registered transport with its module-owned options.
|
|
80
102
|
|
|
81
103
|
*log_bodies* is false outside development and testing: a console backend
|
|
82
104
|
left in place in production must not write reset and invite tokens to the
|
|
83
|
-
log, so there it logs only recipient and
|
|
105
|
+
log, so there it logs only recipient, subject and attachment metadata.
|
|
84
106
|
"""
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
host=settings.smtp_host,
|
|
88
|
-
port=settings.smtp_port,
|
|
89
|
-
username=settings.smtp_username,
|
|
90
|
-
password=settings.smtp_password,
|
|
91
|
-
from_address=settings.smtp_from,
|
|
92
|
-
use_tls=settings.smtp_tls,
|
|
93
|
-
)
|
|
94
|
-
return ConsoleMailSender(include_body=log_bodies)
|
|
107
|
+
transport = get_mail_transport(settings.backend, development=development)
|
|
108
|
+
return transport.factory(settings if options is None else options, log_bodies)
|
|
@@ -14,6 +14,7 @@ if TYPE_CHECKING:
|
|
|
14
14
|
from fastapi import FastAPI
|
|
15
15
|
from simple_module_core.data_compatibility import DataCompatibilityIssue
|
|
16
16
|
from simple_module_core.events import EventBus
|
|
17
|
+
from simple_module_core.invalidation import InvalidationBus
|
|
17
18
|
|
|
18
19
|
|
|
19
20
|
class MailModule(ModuleBase):
|
|
@@ -46,7 +47,7 @@ class MailModule(ModuleBase):
|
|
|
46
47
|
)
|
|
47
48
|
)
|
|
48
49
|
|
|
49
|
-
def register_event_handlers(self, bus: EventBus, app: FastAPI | None
|
|
50
|
+
def register_event_handlers(self, bus: EventBus, app: FastAPI | None) -> None:
|
|
50
51
|
# Before the ``app is None`` return: the outbox worker builds modules
|
|
51
52
|
# without an app and still has to send durable mail.
|
|
52
53
|
from mail.delivery.runtime import resolve_sender_from_db
|
|
@@ -60,12 +61,32 @@ class MailModule(ModuleBase):
|
|
|
60
61
|
from mail.delivery.runtime import install_app_sender
|
|
61
62
|
|
|
62
63
|
async def _reinstall(event: SettingsReloaded) -> None:
|
|
64
|
+
from mail.core.transports import get_mail_transport
|
|
65
|
+
|
|
63
66
|
if event.package != c.MODULE_PACKAGE:
|
|
64
|
-
|
|
67
|
+
transport = get_mail_transport(
|
|
68
|
+
app.state.mail.settings.backend,
|
|
69
|
+
development=app.state.sm.settings.environment == "development",
|
|
70
|
+
)
|
|
71
|
+
if event.package != transport.package:
|
|
72
|
+
return
|
|
65
73
|
install_app_sender(app)
|
|
66
74
|
|
|
67
75
|
bus.subscribe(SettingsReloaded, _reinstall)
|
|
68
76
|
|
|
77
|
+
def register_invalidations(self, bus: InvalidationBus, app: FastAPI) -> None:
|
|
78
|
+
from settings.core.invalidation import CHANNEL
|
|
79
|
+
from simple_module_core.invalidation_refresh import InvalidationRefresh
|
|
80
|
+
|
|
81
|
+
from mail.delivery.runtime import install_app_sender
|
|
82
|
+
|
|
83
|
+
async def retry_failed_sender(key: str | None) -> None:
|
|
84
|
+
# Hydration can succeed while construction fails, leaving no later change event.
|
|
85
|
+
if app.state.mail.sender_failed:
|
|
86
|
+
install_app_sender(app)
|
|
87
|
+
|
|
88
|
+
self._refresh = InvalidationRefresh(bus, CHANNEL, retry_failed_sender)
|
|
89
|
+
|
|
69
90
|
async def check_data_compatibility(self, db: Any) -> list[DataCompatibilityIssue]:
|
|
70
91
|
from mail.core.data_compatibility import check_data_compatibility
|
|
71
92
|
|
|
@@ -75,7 +96,11 @@ class MailModule(ModuleBase):
|
|
|
75
96
|
from mail.delivery.runtime import install_app_sender
|
|
76
97
|
|
|
77
98
|
install_app_sender(app)
|
|
99
|
+
if hasattr(self, "_refresh"):
|
|
100
|
+
self._refresh.start()
|
|
78
101
|
|
|
79
102
|
async def on_shutdown(self, app: FastAPI) -> None:
|
|
103
|
+
if hasattr(self, "_refresh"):
|
|
104
|
+
await self._refresh.stop()
|
|
80
105
|
install_mail_sender(None)
|
|
81
106
|
install_mail_resolver(None)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "simple_module_mail"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.48"
|
|
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,8 +9,8 @@ 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.
|
|
12
|
+
"simple_module_core==0.0.48",
|
|
13
|
+
"simple_module_settings==0.0.48",
|
|
14
14
|
"aiosmtplib>=3.0,<6",
|
|
15
15
|
]
|
|
16
16
|
|
|
@@ -34,5 +34,8 @@ async def test_mail_obsolete_system_keys(scope, scope_id, key, expected):
|
|
|
34
34
|
if expected:
|
|
35
35
|
assert issues[0].upgrade_id == "mail.settings_namespace_v1"
|
|
36
36
|
assert issues[0].severity == "warning"
|
|
37
|
+
assert "uv run smpy migrations prepare mail.settings_namespace_v1 --head" in (
|
|
38
|
+
issues[0].remediation_text or ""
|
|
39
|
+
)
|
|
37
40
|
finally:
|
|
38
41
|
await engine.dispose()
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Failed transport construction blocks delivery until an unchanged refresh recovers."""
|
|
2
|
+
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from mail.contracts import register_mail_transport
|
|
7
|
+
from mail.core import transports
|
|
8
|
+
from mail.core.settings import MailSettings
|
|
9
|
+
from mail.core.state import MailState
|
|
10
|
+
from mail.module import MailModule
|
|
11
|
+
from settings.contracts.events import SettingsReloaded
|
|
12
|
+
from settings.core.invalidation import reload_package
|
|
13
|
+
from simple_module_core import mail as core_mail
|
|
14
|
+
from simple_module_core.events import EventBus
|
|
15
|
+
from simple_module_core.health import HealthStatus
|
|
16
|
+
from simple_module_core.invalidation import InvalidationBus
|
|
17
|
+
from simple_module_core.module_settings import register_module_settings
|
|
18
|
+
from simple_module_core.settings_base import DbBackedSettings
|
|
19
|
+
from simple_module_test.mail import CapturedMail
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ProviderSettings(DbBackedSettings):
|
|
23
|
+
from_address: str = "old@test"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.mark.parametrize("refresh_key", [None, "mail"])
|
|
27
|
+
@pytest.mark.parametrize("package", ["mail", "provider"])
|
|
28
|
+
async def test_failed_reload_blocks_delivery_and_unchanged_refresh_recovers(
|
|
29
|
+
monkeypatch, refresh_key, package
|
|
30
|
+
):
|
|
31
|
+
from mail.delivery.runtime import check_smtp
|
|
32
|
+
|
|
33
|
+
monkeypatch.setattr(transports, "_transports", dict(transports._transports))
|
|
34
|
+
monkeypatch.setattr(transports, "TRANSPORT_NAMES", list(transports.TRANSPORT_NAMES))
|
|
35
|
+
available = True
|
|
36
|
+
recovered = CapturedMail()
|
|
37
|
+
|
|
38
|
+
def factory(options, log_bodies):
|
|
39
|
+
if not available:
|
|
40
|
+
raise RuntimeError("provider unavailable")
|
|
41
|
+
return recovered
|
|
42
|
+
|
|
43
|
+
register_mail_transport(
|
|
44
|
+
"recovering", factory, settings_model=ProviderSettings, package="provider"
|
|
45
|
+
)
|
|
46
|
+
app = SimpleNamespace(
|
|
47
|
+
state=SimpleNamespace(
|
|
48
|
+
sm=SimpleNamespace(settings=SimpleNamespace(environment="testing")),
|
|
49
|
+
mail=MailState(settings=MailSettings()),
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
register_module_settings(app, "mail", MailSettings, lambda s: MailState(settings=s))
|
|
53
|
+
register_module_settings(
|
|
54
|
+
app, "provider", ProviderSettings, lambda s: SimpleNamespace(settings=s)
|
|
55
|
+
)
|
|
56
|
+
if package == "provider":
|
|
57
|
+
app.state.mail.settings = MailSettings(backend="recovering")
|
|
58
|
+
module = MailModule()
|
|
59
|
+
events = EventBus()
|
|
60
|
+
module.register_event_handlers(events, app)
|
|
61
|
+
module.register_invalidations(InvalidationBus(), app)
|
|
62
|
+
await module.on_startup(app)
|
|
63
|
+
available = False
|
|
64
|
+
|
|
65
|
+
class Overrides:
|
|
66
|
+
async def get_overrides(self, package):
|
|
67
|
+
if package == "mail":
|
|
68
|
+
return {"backend": ("recovering", "string")}
|
|
69
|
+
return {"from_address": ("new@test", "string")}
|
|
70
|
+
|
|
71
|
+
changed = []
|
|
72
|
+
|
|
73
|
+
async def record(event):
|
|
74
|
+
changed.append(event)
|
|
75
|
+
|
|
76
|
+
events.subscribe(SettingsReloaded, record)
|
|
77
|
+
message = core_mail.MailMessage("to@test", "Subject", "Body")
|
|
78
|
+
try:
|
|
79
|
+
await reload_package(app, events, Overrides(), package)
|
|
80
|
+
assert app.state.mail.settings.backend == "recovering"
|
|
81
|
+
for sender in (
|
|
82
|
+
core_mail.current_mail_sender(),
|
|
83
|
+
await core_mail.resolve_mail_sender(object()),
|
|
84
|
+
):
|
|
85
|
+
with pytest.raises(RuntimeError, match=r"Mail transport.*unavailable"):
|
|
86
|
+
await sender.send(message)
|
|
87
|
+
assert (await check_smtp()).status is HealthStatus.UNHEALTHY
|
|
88
|
+
with pytest.raises(RuntimeError, match="provider unavailable"):
|
|
89
|
+
await module._refresh.refresh(refresh_key)
|
|
90
|
+
with pytest.raises(RuntimeError, match=r"Mail transport.*unavailable"):
|
|
91
|
+
await core_mail.current_mail_sender().send(message)
|
|
92
|
+
|
|
93
|
+
# No new SettingsReloaded event: the settings already contain this backend.
|
|
94
|
+
available = True
|
|
95
|
+
await reload_package(app, events, Overrides(), package)
|
|
96
|
+
assert len(changed) == 1
|
|
97
|
+
await module._refresh.refresh(refresh_key)
|
|
98
|
+
await core_mail.current_mail_sender().send(message)
|
|
99
|
+
assert recovered.messages == [message]
|
|
100
|
+
assert (await check_smtp()).status is HealthStatus.HEALTHY
|
|
101
|
+
finally:
|
|
102
|
+
await module.on_shutdown(app)
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Registered transports survive startup, worker resolution and settings reloads."""
|
|
2
|
+
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from mail.core.settings import MailSettings
|
|
7
|
+
from mail.delivery.runtime import install_app_sender, resolve_sender_from_db
|
|
8
|
+
from mail.delivery.sender import build_sender
|
|
9
|
+
from mail.module import MailModule
|
|
10
|
+
from pydantic import ValidationError
|
|
11
|
+
from settings.core.service import SettingService
|
|
12
|
+
from settings.module_settings.discovery import collect_module_settings
|
|
13
|
+
from settings.module_settings.reload import apply_changes_and_reload
|
|
14
|
+
from settings.module_settings.store import SettingsStore
|
|
15
|
+
from simple_module_core import mail as core_mail
|
|
16
|
+
from simple_module_core.events import EventBus
|
|
17
|
+
from simple_module_core.module_settings import register_module_settings
|
|
18
|
+
from simple_module_core.settings_base import DbBackedSettings
|
|
19
|
+
from simple_module_db.transaction import finalize_session
|
|
20
|
+
from simple_module_test.mail import CapturedMail
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ProviderSettings(DbBackedSettings):
|
|
24
|
+
from_address: str = "default@example.com"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ProviderSender(CapturedMail):
|
|
28
|
+
def __init__(self, options, log_bodies):
|
|
29
|
+
super().__init__()
|
|
30
|
+
self.from_address = options.from_address
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@pytest.fixture
|
|
34
|
+
def provider(monkeypatch):
|
|
35
|
+
from mail.contracts import register_mail_transport
|
|
36
|
+
from mail.core import transports
|
|
37
|
+
|
|
38
|
+
monkeypatch.setattr(transports, "_transports", dict(transports._transports))
|
|
39
|
+
previous_names = list(transports.TRANSPORT_NAMES)
|
|
40
|
+
register_mail_transport(
|
|
41
|
+
"http-api", ProviderSender, settings_model=ProviderSettings, package="provider"
|
|
42
|
+
)
|
|
43
|
+
yield
|
|
44
|
+
transports.TRANSPORT_NAMES[:] = previous_names
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_custom_transport_can_be_selected(provider):
|
|
48
|
+
sender = build_sender(
|
|
49
|
+
MailSettings(backend="http-api"), options=ProviderSettings(from_address="api@test")
|
|
50
|
+
)
|
|
51
|
+
assert isinstance(sender, ProviderSender)
|
|
52
|
+
assert sender.from_address == "api@test"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_repeated_registration_is_safe_but_conflicts_fail(provider):
|
|
56
|
+
from mail.contracts import register_mail_transport
|
|
57
|
+
|
|
58
|
+
register_mail_transport(
|
|
59
|
+
"http-api", ProviderSender, settings_model=ProviderSettings, package="provider"
|
|
60
|
+
)
|
|
61
|
+
for name in ("http-api", "console", "smtp"):
|
|
62
|
+
with pytest.raises(ValueError, match="already registered"):
|
|
63
|
+
register_mail_transport(name, lambda options, log_bodies: CapturedMail())
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_provider_settings_require_a_package(provider):
|
|
67
|
+
from mail.contracts import register_mail_transport
|
|
68
|
+
|
|
69
|
+
with pytest.raises(ValueError, match="supplied together"):
|
|
70
|
+
register_mail_transport("invalid", ProviderSender, settings_model=ProviderSettings)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_unknown_transport_fails_in_production_and_logs_in_development(caplog):
|
|
74
|
+
settings = MailSettings(backend="uninstalled")
|
|
75
|
+
with pytest.raises(ValueError, match=r"Unknown mail transport.*uninstalled"):
|
|
76
|
+
build_sender(settings, development=False)
|
|
77
|
+
assert isinstance(build_sender(settings), core_mail.ConsoleMailSender)
|
|
78
|
+
assert "uninstalled" in caplog.text
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def test_explicit_sender_survives_startup_and_reload(app):
|
|
82
|
+
explicit = CapturedMail()
|
|
83
|
+
core_mail.install_mail_sender(explicit)
|
|
84
|
+
install_app_sender(app)
|
|
85
|
+
async with app.state.sm.db.session_factory() as db:
|
|
86
|
+
await apply_changes_and_reload(
|
|
87
|
+
app,
|
|
88
|
+
app.state.sm.event_bus,
|
|
89
|
+
SettingsStore(SettingService(db)),
|
|
90
|
+
package="mail",
|
|
91
|
+
changes={"backend": "smtp"},
|
|
92
|
+
)
|
|
93
|
+
await finalize_session(db)
|
|
94
|
+
assert core_mail.current_mail_sender() is explicit
|
|
95
|
+
assert await core_mail.resolve_mail_sender(object()) is explicit
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def test_registered_transport_reload_and_admin_choices(app, provider):
|
|
99
|
+
register_module_settings(
|
|
100
|
+
app, "provider", ProviderSettings, lambda s: SimpleNamespace(settings=s)
|
|
101
|
+
)
|
|
102
|
+
async with app.state.sm.db.session_factory() as db:
|
|
103
|
+
store = SettingsStore(SettingService(db))
|
|
104
|
+
await apply_changes_and_reload(
|
|
105
|
+
app,
|
|
106
|
+
app.state.sm.event_bus,
|
|
107
|
+
store,
|
|
108
|
+
package="provider",
|
|
109
|
+
changes={"from_address": "first@test"},
|
|
110
|
+
)
|
|
111
|
+
await finalize_session(db)
|
|
112
|
+
await apply_changes_and_reload(
|
|
113
|
+
app,
|
|
114
|
+
app.state.sm.event_bus,
|
|
115
|
+
store,
|
|
116
|
+
package="mail",
|
|
117
|
+
changes={"backend": "http-api"},
|
|
118
|
+
)
|
|
119
|
+
await finalize_session(db)
|
|
120
|
+
assert core_mail.current_mail_sender().from_address == "first@test"
|
|
121
|
+
await apply_changes_and_reload(
|
|
122
|
+
app,
|
|
123
|
+
app.state.sm.event_bus,
|
|
124
|
+
store,
|
|
125
|
+
package="provider",
|
|
126
|
+
changes={"from_address": "second@test"},
|
|
127
|
+
)
|
|
128
|
+
await finalize_session(db)
|
|
129
|
+
assert core_mail.current_mail_sender().from_address == "second@test"
|
|
130
|
+
view = next(v for v in collect_module_settings(app) if v.package == "mail")
|
|
131
|
+
assert next(f for f in view.fields if f.name == "backend").choices == [
|
|
132
|
+
"console",
|
|
133
|
+
"http-api",
|
|
134
|
+
"smtp",
|
|
135
|
+
]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@pytest.mark.parametrize(
|
|
139
|
+
("raw", "value_type", "expected"),
|
|
140
|
+
[("worker@test", "string", "worker@test"), ("3", "int", "default@example.com")],
|
|
141
|
+
)
|
|
142
|
+
async def test_worker_registration_and_resolver_use_provider_settings(
|
|
143
|
+
provider, db_session, raw, value_type, expected
|
|
144
|
+
):
|
|
145
|
+
MailModule().register_event_handlers(EventBus(), None)
|
|
146
|
+
store = SettingsStore(SettingService(db_session))
|
|
147
|
+
await store.set_override("mail", "backend", "http-api", "string")
|
|
148
|
+
await store.set_override("provider", "from_address", raw, value_type)
|
|
149
|
+
sender = await core_mail.resolve_mail_sender(db_session)
|
|
150
|
+
assert isinstance(sender, ProviderSender)
|
|
151
|
+
assert sender.from_address == expected
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
async def test_unknown_transport_is_rejected_by_admin(app, db_session):
|
|
155
|
+
with pytest.raises(ValidationError, match="Unknown choice for backend"):
|
|
156
|
+
await apply_changes_and_reload(
|
|
157
|
+
app,
|
|
158
|
+
app.state.sm.event_bus,
|
|
159
|
+
SettingsStore(SettingService(db_session)),
|
|
160
|
+
package="mail",
|
|
161
|
+
changes={"backend": "uninstalled"},
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
async def test_worker_unknown_transport_does_not_silently_use_console(db_session, monkeypatch):
|
|
166
|
+
await SettingsStore(SettingService(db_session)).set_override(
|
|
167
|
+
"mail", "backend", "uninstalled", "string"
|
|
168
|
+
)
|
|
169
|
+
monkeypatch.setenv("SM_ENVIRONMENT", "production")
|
|
170
|
+
with pytest.raises(ValueError, match="Unknown mail transport"):
|
|
171
|
+
await resolve_sender_from_db(db_session)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def test_unknown_transport_refuses_app_startup_outside_development():
|
|
175
|
+
app = SimpleNamespace(
|
|
176
|
+
state=SimpleNamespace(
|
|
177
|
+
sm=SimpleNamespace(settings=SimpleNamespace(environment="testing")),
|
|
178
|
+
mail=SimpleNamespace(settings=MailSettings(backend="uninstalled")),
|
|
179
|
+
)
|
|
180
|
+
)
|
|
181
|
+
with pytest.raises(ValueError, match="Unknown mail transport"):
|
|
182
|
+
install_app_sender(app)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
async def test_startup_and_provider_reload_build_selected_transport(provider):
|
|
186
|
+
from settings.contracts.events import SettingsReloaded
|
|
187
|
+
|
|
188
|
+
app = SimpleNamespace(
|
|
189
|
+
state=SimpleNamespace(
|
|
190
|
+
sm=SimpleNamespace(settings=SimpleNamespace(environment="development")),
|
|
191
|
+
mail=SimpleNamespace(settings=MailSettings(backend="http-api")),
|
|
192
|
+
provider=SimpleNamespace(settings=ProviderSettings(from_address="startup@test")),
|
|
193
|
+
)
|
|
194
|
+
)
|
|
195
|
+
bus = EventBus()
|
|
196
|
+
module = MailModule()
|
|
197
|
+
module.register_event_handlers(bus, app)
|
|
198
|
+
await module.on_startup(app)
|
|
199
|
+
assert core_mail.current_mail_sender().from_address == "startup@test"
|
|
200
|
+
app.state.provider.settings = ProviderSettings(from_address="reload@test")
|
|
201
|
+
await bus.publish(SettingsReloaded(package="provider", changed=("from_address",)))
|
|
202
|
+
assert core_mail.current_mail_sender().from_address == "reload@test"
|
|
203
|
+
await bus.publish(SettingsReloaded(package="mail", changed=("smtp_host",)))
|
|
204
|
+
assert core_mail.current_mail_sender().from_address == "reload@test"
|
|
205
|
+
explicit = CapturedMail()
|
|
206
|
+
core_mail.install_mail_sender(explicit)
|
|
207
|
+
await bus.publish(SettingsReloaded(package="mail", changed=("smtp_host",)))
|
|
208
|
+
assert core_mail.current_mail_sender() is explicit
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
async def test_outbox_delivers_through_registered_transport(
|
|
212
|
+
provider, db_session, db_state, monkeypatch
|
|
213
|
+
):
|
|
214
|
+
from dataclasses import dataclass
|
|
215
|
+
|
|
216
|
+
from background_tasks.outbox.claim import OutboxPolicy
|
|
217
|
+
from background_tasks.outbox.dispatch import dispatch
|
|
218
|
+
from background_tasks.outbox.transport import WorkerOutboxTransport
|
|
219
|
+
from mail.contracts import register_mail_transport
|
|
220
|
+
from simple_module_core.events import Event
|
|
221
|
+
|
|
222
|
+
@dataclass
|
|
223
|
+
class SendViaProvider(Event):
|
|
224
|
+
message: core_mail.MailMessage
|
|
225
|
+
|
|
226
|
+
delivered = []
|
|
227
|
+
|
|
228
|
+
class RecordingProvider(ProviderSender):
|
|
229
|
+
async def send(self, message):
|
|
230
|
+
delivered.append((self.from_address, message))
|
|
231
|
+
|
|
232
|
+
register_mail_transport(
|
|
233
|
+
"outbox-http", RecordingProvider, settings_model=ProviderSettings, package="provider"
|
|
234
|
+
)
|
|
235
|
+
bus = EventBus()
|
|
236
|
+
MailModule().register_event_handlers(bus, None)
|
|
237
|
+
|
|
238
|
+
async def deliver(event, ctx):
|
|
239
|
+
await (await core_mail.resolve_mail_sender(ctx.db)).send(event.message)
|
|
240
|
+
|
|
241
|
+
bus.subscribe_durable(SendViaProvider, deliver, name="registered-transport-test")
|
|
242
|
+
transport = WorkerOutboxTransport()
|
|
243
|
+
monkeypatch.setattr(transport, "schedule", lambda db, ids: None)
|
|
244
|
+
bus.durable_transport = transport
|
|
245
|
+
store = SettingsStore(SettingService(db_session))
|
|
246
|
+
await store.set_override("mail", "backend", "outbox-http", "string")
|
|
247
|
+
await store.set_override("provider", "from_address", "outbox@test", "string")
|
|
248
|
+
await bus.publish_durable(
|
|
249
|
+
SendViaProvider(core_mail.MailMessage("to@test", "Provider", "Body")), db_session
|
|
250
|
+
)
|
|
251
|
+
await db_session.commit()
|
|
252
|
+
result = await dispatch(
|
|
253
|
+
db_state.session_factory, bus, OutboxPolicy(max_attempts=8, lease_seconds=300)
|
|
254
|
+
)
|
|
255
|
+
assert result.delivered == 1
|
|
256
|
+
assert delivered[0][0] == "outbox@test"
|
|
257
|
+
assert delivered[0][1].subject == "Provider"
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""SMTP wire headers and envelopes preserve mailbox syntax and IDN domains."""
|
|
2
|
+
|
|
3
|
+
from email import policy
|
|
4
|
+
from email.parser import BytesParser
|
|
5
|
+
from unittest.mock import AsyncMock
|
|
6
|
+
|
|
7
|
+
import aiosmtplib
|
|
8
|
+
import pytest
|
|
9
|
+
from mail.delivery.sender import SmtpMailSender
|
|
10
|
+
from simple_module_core.mail import MailMessage
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@pytest.mark.parametrize(
|
|
14
|
+
"to, reply_to, from_address, expected_to, expected_reply, expected_from, display_name",
|
|
15
|
+
[
|
|
16
|
+
(
|
|
17
|
+
"visitor@example.com",
|
|
18
|
+
"guide@bücher.de",
|
|
19
|
+
"platform@example.com",
|
|
20
|
+
["visitor@example.com"],
|
|
21
|
+
"guide@xn--bcher-kva.de",
|
|
22
|
+
"platform@example.com",
|
|
23
|
+
"",
|
|
24
|
+
),
|
|
25
|
+
(
|
|
26
|
+
"Visitor <visitor@bücher.de>",
|
|
27
|
+
r'"Jane \"JJ\", Doe" <guide@bücher.de>',
|
|
28
|
+
"Platform <platform@bücher.de>",
|
|
29
|
+
["visitor@xn--bcher-kva.de"],
|
|
30
|
+
"guide@xn--bcher-kva.de",
|
|
31
|
+
"platform@xn--bcher-kva.de",
|
|
32
|
+
'Jane "JJ", Doe',
|
|
33
|
+
),
|
|
34
|
+
(
|
|
35
|
+
"Visitors: First <first@bücher.de>, second@example.com;",
|
|
36
|
+
"Jäne <guide@bücher.de>",
|
|
37
|
+
"platform@example.com",
|
|
38
|
+
["first@xn--bcher-kva.de", "second@example.com"],
|
|
39
|
+
"guide@xn--bcher-kva.de",
|
|
40
|
+
"platform@example.com",
|
|
41
|
+
"Jäne",
|
|
42
|
+
),
|
|
43
|
+
],
|
|
44
|
+
)
|
|
45
|
+
async def test_idn_domains_are_ascii_in_smtp_headers_and_envelopes(
|
|
46
|
+
monkeypatch,
|
|
47
|
+
to,
|
|
48
|
+
reply_to,
|
|
49
|
+
from_address,
|
|
50
|
+
expected_to,
|
|
51
|
+
expected_reply,
|
|
52
|
+
expected_from,
|
|
53
|
+
display_name,
|
|
54
|
+
) -> None:
|
|
55
|
+
smtp = aiosmtplib.SMTP()
|
|
56
|
+
monkeypatch.setattr(smtp, "_ehlo_or_helo_if_needed", AsyncMock())
|
|
57
|
+
sendmail = AsyncMock(return_value=({}, "OK"))
|
|
58
|
+
monkeypatch.setattr(smtp, "sendmail", sendmail)
|
|
59
|
+
|
|
60
|
+
async def send(email, **kwargs):
|
|
61
|
+
return await smtp.send_message(email)
|
|
62
|
+
|
|
63
|
+
monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
|
|
64
|
+
sender = SmtpMailSender("smtp.test", 25, "", "", from_address, False)
|
|
65
|
+
await sender.send(MailMessage(to, "Booking", "Confirmed", reply_to=reply_to))
|
|
66
|
+
|
|
67
|
+
envelope_from, envelope_to, wire = sendmail.call_args.args
|
|
68
|
+
assert envelope_from == expected_from
|
|
69
|
+
assert envelope_to == expected_to
|
|
70
|
+
assert "SMTPUTF8" not in sendmail.call_args.kwargs["mail_options"]
|
|
71
|
+
email = BytesParser(policy=policy.default).parsebytes(wire)
|
|
72
|
+
for name in ("From", "To", "Reply-To"):
|
|
73
|
+
assert not email[name].defects
|
|
74
|
+
assert all(address.domain.isascii() for address in email[name].addresses)
|
|
75
|
+
assert [address.addr_spec for address in email["To"].addresses] == expected_to
|
|
76
|
+
assert email["From"].addresses[0].addr_spec == expected_from
|
|
77
|
+
assert email["Reply-To"].addresses[0].addr_spec == expected_reply
|
|
78
|
+
assert email["Reply-To"].addresses[0].display_name == display_name
|
|
79
|
+
if to.startswith("Visitors:"):
|
|
80
|
+
assert email["To"].groups[0].display_name == "Visitors"
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Mail metadata travels through the persisted durable outbox (#1006, #1025)."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from background_tasks.models import OutboxMessage
|
|
7
|
+
from background_tasks.outbox.claim import OutboxPolicy
|
|
8
|
+
from background_tasks.outbox.dispatch import dispatch
|
|
9
|
+
from background_tasks.outbox.transport import WorkerOutboxTransport
|
|
10
|
+
from simple_module_core.durable_events import DurableContext
|
|
11
|
+
from simple_module_core.events import Event, EventBus
|
|
12
|
+
from simple_module_core.mail import MailAttachment, MailMessage, resolve_mail_sender
|
|
13
|
+
from sqlmodel import select
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class RegistrationConfirmed(Event):
|
|
18
|
+
message: MailMessage
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.mark.parametrize("legacy", [False, True])
|
|
22
|
+
@pytest.mark.parametrize("legacy_reply_to", [False, True])
|
|
23
|
+
async def test_outbox_delivers_attachments_and_legacy_payload(
|
|
24
|
+
db_session, db_state, captured_mail, monkeypatch, legacy, legacy_reply_to
|
|
25
|
+
) -> None:
|
|
26
|
+
bus = EventBus()
|
|
27
|
+
|
|
28
|
+
async def deliver(event: RegistrationConfirmed, ctx: DurableContext) -> None:
|
|
29
|
+
await (await resolve_mail_sender(ctx.db)).send(event.message)
|
|
30
|
+
|
|
31
|
+
bus.subscribe_durable(RegistrationConfirmed, deliver, name="mail-attachment-test")
|
|
32
|
+
transport = WorkerOutboxTransport()
|
|
33
|
+
monkeypatch.setattr(transport, "schedule", lambda db, ids: None)
|
|
34
|
+
bus.durable_transport = transport
|
|
35
|
+
attachments = (
|
|
36
|
+
[]
|
|
37
|
+
if legacy
|
|
38
|
+
else [
|
|
39
|
+
MailAttachment(
|
|
40
|
+
filename="invite.ics",
|
|
41
|
+
content_type="text/calendar",
|
|
42
|
+
content=b"BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n",
|
|
43
|
+
)
|
|
44
|
+
]
|
|
45
|
+
)
|
|
46
|
+
await bus.publish_durable(
|
|
47
|
+
RegistrationConfirmed(
|
|
48
|
+
MailMessage(
|
|
49
|
+
"a@test",
|
|
50
|
+
"Confirmation",
|
|
51
|
+
"Body",
|
|
52
|
+
attachments=attachments,
|
|
53
|
+
reply_to="guide@example.com",
|
|
54
|
+
)
|
|
55
|
+
),
|
|
56
|
+
db_session,
|
|
57
|
+
)
|
|
58
|
+
row = (await db_session.execute(select(OutboxMessage))).scalar_one()
|
|
59
|
+
assert row.payload["message"]["reply_to"] == "guide@example.com"
|
|
60
|
+
if legacy_reply_to:
|
|
61
|
+
payload = {**row.payload, "message": dict(row.payload["message"])}
|
|
62
|
+
del payload["message"]["reply_to"]
|
|
63
|
+
row.payload = payload
|
|
64
|
+
if legacy:
|
|
65
|
+
payload = {**row.payload, "message": dict(row.payload["message"])}
|
|
66
|
+
del payload["message"]["attachments"]
|
|
67
|
+
row.payload = payload
|
|
68
|
+
else:
|
|
69
|
+
assert row.payload["message"]["attachments"][0]["filename"] == "invite.ics"
|
|
70
|
+
assert isinstance(row.payload["message"]["attachments"][0]["content"], str)
|
|
71
|
+
await db_session.commit()
|
|
72
|
+
result = await dispatch(
|
|
73
|
+
db_state.session_factory, bus, OutboxPolicy(max_attempts=8, lease_seconds=300)
|
|
74
|
+
)
|
|
75
|
+
assert result.delivered == 1
|
|
76
|
+
message = captured_mail.to("a@test")[0]
|
|
77
|
+
assert message.subject == "Confirmation"
|
|
78
|
+
assert message.reply_to == (None if legacy_reply_to else "guide@example.com")
|
|
79
|
+
if legacy:
|
|
80
|
+
assert message.attachments == ()
|
|
81
|
+
else:
|
|
82
|
+
assert message.attachments[0].content == b"BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n"
|
{simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/tests/delivery/sender/test_mail_sender.py
RENAMED
|
@@ -7,7 +7,7 @@ from unittest.mock import AsyncMock
|
|
|
7
7
|
import pytest
|
|
8
8
|
from mail.core.settings import MailSettings
|
|
9
9
|
from mail.delivery.sender import SmtpMailSender, build_sender
|
|
10
|
-
from simple_module_core.mail import ConsoleMailSender, MailMessage
|
|
10
|
+
from simple_module_core.mail import ConsoleMailSender, MailAttachment, MailMessage
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
def test_defaults() -> None:
|
|
@@ -33,7 +33,7 @@ def test_smtp_backend_builds_an_smtp_sender() -> None:
|
|
|
33
33
|
|
|
34
34
|
def test_unknown_backend_is_rejected() -> None:
|
|
35
35
|
with pytest.raises(ValueError):
|
|
36
|
-
MailSettings(backend="carrier-pigeon")
|
|
36
|
+
build_sender(MailSettings(backend="carrier-pigeon"), development=False)
|
|
37
37
|
|
|
38
38
|
|
|
39
39
|
def _smtp() -> SmtpMailSender:
|
|
@@ -72,6 +72,29 @@ async def test_send_adds_an_html_alternative(monkeypatch) -> None:
|
|
|
72
72
|
assert parts == {"text/plain": "Body", "text/html": "<b>Body</b>"}
|
|
73
73
|
|
|
74
74
|
|
|
75
|
+
@pytest.mark.parametrize(
|
|
76
|
+
"reply_to",
|
|
77
|
+
[
|
|
78
|
+
None,
|
|
79
|
+
"guide@example.com",
|
|
80
|
+
"Guide <guide@example.com>",
|
|
81
|
+
'"Doe, Jane" <guide@example.com>',
|
|
82
|
+
r'"Jane \"JJ\", Doe" <guide@example.com>',
|
|
83
|
+
],
|
|
84
|
+
)
|
|
85
|
+
async def test_smtp_reply_to_header(monkeypatch, reply_to) -> None:
|
|
86
|
+
from email import policy
|
|
87
|
+
from email.parser import BytesParser
|
|
88
|
+
|
|
89
|
+
send = AsyncMock()
|
|
90
|
+
monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
|
|
91
|
+
await _smtp().send(MailMessage("to@test", "Booking", "Confirmed", reply_to=reply_to))
|
|
92
|
+
email = BytesParser(policy=policy.default).parsebytes(send.call_args.args[0].as_bytes())
|
|
93
|
+
assert email["Reply-To"] == reply_to
|
|
94
|
+
assert email["From"] == "from@test"
|
|
95
|
+
assert email["To"] == "to@test"
|
|
96
|
+
|
|
97
|
+
|
|
75
98
|
async def test_blank_credentials_are_sent_as_none(monkeypatch) -> None:
|
|
76
99
|
send = AsyncMock()
|
|
77
100
|
monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
|
|
@@ -83,6 +106,47 @@ async def test_blank_credentials_are_sent_as_none(monkeypatch) -> None:
|
|
|
83
106
|
assert kwargs["username"] is None and kwargs["password"] is None
|
|
84
107
|
|
|
85
108
|
|
|
109
|
+
@pytest.mark.parametrize("html", [None, "<b>Body</b>"])
|
|
110
|
+
async def test_smtp_attachment_parts_preserve_filename_type_and_bytes(monkeypatch, html) -> None:
|
|
111
|
+
from email import policy
|
|
112
|
+
from email.parser import BytesParser
|
|
113
|
+
|
|
114
|
+
send = AsyncMock()
|
|
115
|
+
monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
|
|
116
|
+
await _smtp().send(
|
|
117
|
+
MailMessage(
|
|
118
|
+
"to@test",
|
|
119
|
+
"Hi",
|
|
120
|
+
"Body",
|
|
121
|
+
html=html,
|
|
122
|
+
attachments=[
|
|
123
|
+
MailAttachment(
|
|
124
|
+
filename="invite.ics",
|
|
125
|
+
content_type="text/calendar",
|
|
126
|
+
content=b"BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n",
|
|
127
|
+
),
|
|
128
|
+
MailAttachment(
|
|
129
|
+
filename="r\u00e9sum\u00e9.bin",
|
|
130
|
+
content_type="application/octet-stream",
|
|
131
|
+
content=b"\x00\xff",
|
|
132
|
+
),
|
|
133
|
+
],
|
|
134
|
+
)
|
|
135
|
+
)
|
|
136
|
+
email = BytesParser(policy=policy.default).parsebytes(send.call_args.args[0].as_bytes())
|
|
137
|
+
parts = list(email.iter_attachments())
|
|
138
|
+
assert [
|
|
139
|
+
(p.get_filename(), p.get_content_type(), p.get_payload(decode=True)) for p in parts
|
|
140
|
+
] == [
|
|
141
|
+
("invite.ics", "text/calendar", b"BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n"),
|
|
142
|
+
("r\u00e9sum\u00e9.bin", "application/octet-stream", b"\x00\xff"),
|
|
143
|
+
]
|
|
144
|
+
assert all(p.get_content_disposition() == "attachment" for p in parts)
|
|
145
|
+
assert email.get_body(preferencelist=("plain",)).get_content().strip() == "Body"
|
|
146
|
+
if html:
|
|
147
|
+
assert email.get_body(preferencelist=("html",)).get_content().strip() == html
|
|
148
|
+
|
|
149
|
+
|
|
86
150
|
def test_console_backend_outside_development_does_not_log_bodies() -> None:
|
|
87
151
|
"""Reset and invite bodies carry one-time tokens (production console backend)."""
|
|
88
152
|
from mail.core.settings import MailSettings
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/tests/core/module/test_mail_lifecycle.py
RENAMED
|
File without changes
|
|
File without changes
|
{simple_module_mail-0.0.47 → simple_module_mail-0.0.48}/tests/delivery/runtime/test_mail_health.py
RENAMED
|
File without changes
|