simple-module-mail 0.0.48__tar.gz → 0.0.49__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.
Files changed (28) hide show
  1. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/PKG-INFO +3 -3
  2. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/delivery/sender.py +37 -1
  3. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/pyproject.toml +3 -3
  4. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/delivery/sender/test_mail_address_headers.py +46 -6
  5. simple_module_mail-0.0.49/tests/delivery/sender/test_mail_headers.py +153 -0
  6. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/delivery/sender/test_mail_outbox.py +15 -7
  7. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/delivery/sender/test_mail_sender.py +10 -10
  8. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/.gitignore +0 -0
  9. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/LICENSE +0 -0
  10. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/README.md +0 -0
  11. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/__init__.py +0 -0
  12. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/contracts/__init__.py +0 -0
  13. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/core/__init__.py +0 -0
  14. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/core/constants.py +0 -0
  15. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/core/data_compatibility.py +0 -0
  16. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/core/settings.py +0 -0
  17. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/core/state.py +0 -0
  18. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/core/transports.py +0 -0
  19. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/delivery/__init__.py +0 -0
  20. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/delivery/runtime.py +0 -0
  21. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/module.py +0 -0
  22. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/mail/py.typed +0 -0
  23. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/core/data_compatibility/test_mail_data_compatibility.py +0 -0
  24. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/core/module/test_mail_lifecycle.py +0 -0
  25. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/core/settings/test_mail_settings_migration.py +0 -0
  26. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/delivery/runtime/test_mail_health.py +0 -0
  27. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/delivery/runtime/test_mail_reload_failures.py +0 -0
  28. {simple_module_mail-0.0.48 → simple_module_mail-0.0.49}/tests/delivery/runtime/test_mail_transports.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_mail
3
- Version: 0.0.48
3
+ Version: 0.0.49
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.48
16
- Requires-Dist: simple-module-settings==0.0.48
15
+ Requires-Dist: simple-module-core==0.0.49
16
+ Requires-Dist: simple-module-settings==0.0.49
17
17
  Description-Content-Type: text/markdown
18
18
 
19
19
  # simple_module_mail
@@ -3,7 +3,9 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import contextlib
6
+ from email import policy
6
7
  from email.message import EmailMessage
8
+ from email.utils import formatdate, make_msgid
7
9
  from typing import Any
8
10
 
9
11
  import aiosmtplib
@@ -11,6 +13,7 @@ from simple_module_core.mail import (
11
13
  MailMessage,
12
14
  MailSender,
13
15
  smtp_address_header,
16
+ validate_mail_headers,
14
17
  )
15
18
 
16
19
  from mail.core import constants as c
@@ -18,6 +21,17 @@ from mail.core.settings import MailSettings
18
21
  from mail.core.transports import get_mail_transport
19
22
 
20
23
 
24
+ class _SmtpPolicy(policy.EmailPolicy):
25
+ """Keep UTF-8 header lines within SMTP's byte limit."""
26
+
27
+ def fold_binary(self, name: str, value: Any) -> bytes:
28
+ folded = super().fold_binary(name, value)
29
+ if self.utf8 and any(len(line) > 998 for line in folded.split(b"\r\n")):
30
+ # The stdlib counts characters; UTF-8 needs up to four bytes each.
31
+ return policy.EmailPolicy.fold_binary(self.clone(max_line_length=998 // 4), name, value)
32
+ return folded
33
+
34
+
21
35
  class SmtpMailSender:
22
36
  """Delivers through an SMTP server with aiosmtplib."""
23
37
 
@@ -46,6 +60,15 @@ class SmtpMailSender:
46
60
  if message.reply_to is not None:
47
61
  email["Reply-To"] = smtp_address_header(message.reply_to)
48
62
  email["Subject"] = message.subject
63
+ email["Date"] = formatdate(localtime=False, usegmt=True)
64
+ from_header = email["From"]
65
+ domain = None
66
+ if not from_header.defects and len(from_header.addresses) == 1:
67
+ domain = from_header.addresses[0].domain or None
68
+ email["Message-ID"] = make_msgid(domain=domain)
69
+ # Revalidate because a frozen dataclass can still contain a mutable dictionary.
70
+ for name, value in validate_mail_headers(message.headers).items():
71
+ email[name] = value
49
72
  email.set_content(message.text)
50
73
  if message.html:
51
74
  email.add_alternative(message.html, subtype="html")
@@ -58,8 +81,21 @@ class SmtpMailSender:
58
81
  filename=attachment.filename,
59
82
  )
60
83
 
84
+ # Never infer the SMTP envelope from custom or trace headers.
85
+ sender = from_header.addresses[0].addr_spec
86
+ recipients = [address.addr_spec for address in email["To"].addresses]
87
+ utf8_required = not (sender.isascii() and all(address.isascii() for address in recipients))
88
+ # Typeshed's EmailPolicy constructor self type excludes subclasses.
89
+ wire_policy = _SmtpPolicy( # ty: ignore[invalid-argument-type]
90
+ utf8=utf8_required, linesep="\r\n"
91
+ )
92
+ # Avoid encoded words in long RFC 2369 URLs; bytes bypass aiosmtplib's refolding.
93
+ wire = email.as_bytes(policy=wire_policy.clone(max_line_length=998, cte_type="7bit"))
61
94
  await aiosmtplib.send(
62
- email,
95
+ wire,
96
+ sender=sender,
97
+ recipients=recipients,
98
+ mail_options=["SMTPUTF8"] if utf8_required else [],
63
99
  hostname=self._host,
64
100
  port=self._port,
65
101
  username=self._username or None,
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simple_module_mail"
3
- version = "0.0.48"
3
+ version = "0.0.49"
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.48",
13
- "simple_module_settings==0.0.48",
12
+ "simple_module_core==0.0.49",
13
+ "simple_module_settings==0.0.49",
14
14
  "aiosmtplib>=3.0,<6",
15
15
  ]
16
16
 
@@ -1,15 +1,56 @@
1
1
  """SMTP wire headers and envelopes preserve mailbox syntax and IDN domains."""
2
2
 
3
3
  from email import policy
4
- from email.parser import BytesParser
4
+ from email.parser import BytesParser, Parser
5
5
  from unittest.mock import AsyncMock
6
6
 
7
7
  import aiosmtplib
8
8
  import pytest
9
+ from aiosmtplib.response import SMTPResponse
9
10
  from mail.delivery.sender import SmtpMailSender
10
11
  from simple_module_core.mail import MailMessage
11
12
 
12
13
 
14
+ @pytest.mark.parametrize("supported", [False, True])
15
+ @pytest.mark.parametrize(
16
+ "from_address, to", [("jäne@example.com", "a@test"), ("a@test", "jäne@example.com")]
17
+ )
18
+ async def test_non_ascii_local_parts_require_smtputf8(
19
+ monkeypatch, supported, from_address, to
20
+ ) -> None:
21
+ smtp = aiosmtplib.SMTP()
22
+ monkeypatch.setattr("aiosmtplib.api.SMTP", lambda **kwargs: smtp)
23
+ monkeypatch.setattr(smtp, "connect", AsyncMock())
24
+ monkeypatch.setattr(smtp, "quit", AsyncMock())
25
+ monkeypatch.setattr(smtp, "_ehlo_or_helo_if_needed", AsyncMock())
26
+ monkeypatch.setattr(
27
+ smtp, "supports_extension", lambda name: supported and name.lower() == "smtputf8"
28
+ )
29
+ mail = AsyncMock()
30
+ monkeypatch.setattr(smtp, "mail", mail)
31
+ monkeypatch.setattr(smtp, "_send_recipients", AsyncMock(return_value={}))
32
+ data = AsyncMock(return_value=SMTPResponse(250, "OK"))
33
+ monkeypatch.setattr(smtp, "data", data)
34
+ sender = SmtpMailSender("smtp.test", 25, "", "", from_address, False)
35
+ message = MailMessage(to, "Grüße", "Body")
36
+
37
+ if not supported:
38
+ with pytest.raises(aiosmtplib.SMTPNotSupported, match="SMTPUTF8"):
39
+ await sender.send(message)
40
+ mail.assert_not_awaited()
41
+ data.assert_not_awaited()
42
+ return
43
+
44
+ await sender.send(message)
45
+ assert mail.call_args.args[0] == from_address
46
+ assert "SMTPUTF8" in mail.call_args.kwargs["options"]
47
+ assert mail.call_args.kwargs["encoding"] == "utf-8"
48
+ email = Parser(policy=policy.SMTPUTF8).parsestr(data.call_args.args[0].decode("utf-8"))
49
+ assert email["From"].addresses[0].addr_spec == from_address
50
+ assert email["To"].addresses[0].addr_spec == to
51
+ assert email["Subject"] == "Grüße"
52
+
53
+
13
54
  @pytest.mark.parametrize(
14
55
  "to, reply_to, from_address, expected_to, expected_reply, expected_from, display_name",
15
56
  [
@@ -53,14 +94,12 @@ async def test_idn_domains_are_ascii_in_smtp_headers_and_envelopes(
53
94
  display_name,
54
95
  ) -> None:
55
96
  smtp = aiosmtplib.SMTP()
56
- monkeypatch.setattr(smtp, "_ehlo_or_helo_if_needed", AsyncMock())
97
+ monkeypatch.setattr("aiosmtplib.api.SMTP", lambda **kwargs: smtp)
98
+ monkeypatch.setattr(smtp, "connect", AsyncMock())
99
+ monkeypatch.setattr(smtp, "quit", AsyncMock())
57
100
  sendmail = AsyncMock(return_value=({}, "OK"))
58
101
  monkeypatch.setattr(smtp, "sendmail", sendmail)
59
102
 
60
- async def send(email, **kwargs):
61
- return await smtp.send_message(email)
62
-
63
- monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
64
103
  sender = SmtpMailSender("smtp.test", 25, "", "", from_address, False)
65
104
  await sender.send(MailMessage(to, "Booking", "Confirmed", reply_to=reply_to))
66
105
 
@@ -68,6 +107,7 @@ async def test_idn_domains_are_ascii_in_smtp_headers_and_envelopes(
68
107
  assert envelope_from == expected_from
69
108
  assert envelope_to == expected_to
70
109
  assert "SMTPUTF8" not in sendmail.call_args.kwargs["mail_options"]
110
+ assert wire.isascii()
71
111
  email = BytesParser(policy=policy.default).parsebytes(wire)
72
112
  for name in ("From", "To", "Reply-To"):
73
113
  assert not email[name].defects
@@ -0,0 +1,153 @@
1
+ """SMTP emits required and custom headers on the wire (#1053)."""
2
+
3
+ from datetime import UTC, datetime
4
+ from email import policy
5
+ from email.message import EmailMessage
6
+ from email.parser import BytesParser
7
+ from email.utils import parsedate_to_datetime
8
+ from unittest.mock import AsyncMock
9
+
10
+ import pytest
11
+ from mail.delivery.sender import SmtpMailSender
12
+ from simple_module_core.mail import MailAttachment, MailMessage
13
+
14
+
15
+ @pytest.mark.parametrize(
16
+ "from_address, domain",
17
+ [
18
+ ("sender@example.com", "example.com"),
19
+ ('"Doe, Jane" <sender@example.org>', "example.org"),
20
+ ("Platform <sender@bücher.de>", "xn--bcher-kva.de"),
21
+ ("sender", "fallback.example"),
22
+ ],
23
+ )
24
+ async def test_smtp_date_and_unique_message_id(monkeypatch, from_address, domain) -> None:
25
+ send = AsyncMock()
26
+ monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
27
+ monkeypatch.setattr("email.utils.socket.getfqdn", lambda: "fallback.example")
28
+ sender = SmtpMailSender("smtp.test", 25, "", "", from_address, False)
29
+ before = datetime.now(UTC).replace(microsecond=0)
30
+ await sender.send(MailMessage("a@test", "Hi", "Body"))
31
+ await sender.send(MailMessage("a@test", "Hi", "Body"))
32
+ messages = [
33
+ BytesParser(policy=policy.default).parsebytes(call.args[0]) for call in send.call_args_list
34
+ ]
35
+ for message in messages:
36
+ assert message["Date"] is not None
37
+ assert message["Message-ID"] is not None
38
+ assert not message["Date"].defects
39
+ assert not message["Message-ID"].defects
40
+ date = parsedate_to_datetime(message["Date"])
41
+ assert before <= date <= datetime.now(UTC)
42
+ assert date.utcoffset().total_seconds() == 0
43
+ assert message["Message-ID"].startswith("<")
44
+ assert message["Message-ID"].endswith(f"@{domain}>")
45
+ assert messages[0]["Message-ID"] != messages[1]["Message-ID"]
46
+
47
+
48
+ @pytest.mark.parametrize("resent", [False, True])
49
+ async def test_smtp_envelope_uses_only_from_and_to(monkeypatch, resent) -> None:
50
+ email = EmailMessage()
51
+ # Exercise the envelope guard even if future code introduces routing headers.
52
+ email["Sender"] = "attacker@example.net"
53
+ email["Cc"] = "copy@example.net"
54
+ email["Bcc"] = "hidden@example.net"
55
+ if resent:
56
+ email["Resent-Date"] = "Tue, 01 Jan 2030 00:00:00 +0000"
57
+ email["Resent-From"] = "attacker@example.net"
58
+ email["Resent-To"] = "redirect@example.net"
59
+ monkeypatch.setattr("mail.delivery.sender.EmailMessage", lambda: email)
60
+ send = AsyncMock()
61
+ monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
62
+ await SmtpMailSender("smtp.test", 25, "", "", "Platform <sender@bücher.de>", False).send(
63
+ MailMessage(
64
+ 'Readers: "Doe, Jane" <jane@bücher.de>, second@example.com;',
65
+ "Hi",
66
+ "Body",
67
+ reply_to="reply@example.net",
68
+ headers={"List-Unsubscribe": "<https://example.com/unsubscribe>"},
69
+ )
70
+ )
71
+ assert send.call_args.kwargs["sender"] == "sender@xn--bcher-kva.de"
72
+ assert send.call_args.kwargs["recipients"] == ["jane@xn--bcher-kva.de", "second@example.com"]
73
+
74
+
75
+ @pytest.mark.parametrize("attached", [False, True])
76
+ async def test_custom_header_delivered_on_outer_message(monkeypatch, attached) -> None:
77
+ send = AsyncMock()
78
+ monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
79
+ message = MailMessage(
80
+ "a@test",
81
+ "Newsletter",
82
+ "Body",
83
+ html="<p>Body</p>",
84
+ headers={"List-Unsubscribe": "<https://example.com/unsubscribe>"},
85
+ attachments=[MailAttachment(filename="a.txt", content_type="text/plain", content=b"a")]
86
+ if attached
87
+ else [],
88
+ )
89
+ await SmtpMailSender("smtp.test", 25, "", "", "sender@example.com", False).send(message)
90
+ email = BytesParser(policy=policy.default).parsebytes(send.call_args.args[0])
91
+ assert email["List-Unsubscribe"] == "<https://example.com/unsubscribe>"
92
+ assert all(part["List-Unsubscribe"] is None for part in list(email.walk())[1:])
93
+
94
+
95
+ @pytest.mark.parametrize(
96
+ "headers",
97
+ [
98
+ {"Bcc": "hidden@test"},
99
+ {"Resent-To": "attacker@example.net"},
100
+ {"X-Test": "value\r\nBcc: hidden@test"},
101
+ ],
102
+ )
103
+ async def test_smtp_rejects_headers_mutated_after_construction(monkeypatch, headers) -> None:
104
+ send = AsyncMock()
105
+ monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
106
+ message = MailMessage("a@test", "Hi", "Body")
107
+ message.headers.update(headers)
108
+ with pytest.raises(ValueError, match="header"):
109
+ await SmtpMailSender("smtp.test", 25, "", "", "sender@example.com", False).send(message)
110
+ send.assert_not_awaited()
111
+
112
+
113
+ @pytest.mark.parametrize("to", ["a@test", "ä@test"])
114
+ @pytest.mark.parametrize("value", ["Grüße " * 100, "a" * 1500, "é" * 700, "😀" * 300])
115
+ async def test_long_and_non_ascii_header_values_survive_wire_encoding(
116
+ monkeypatch, value, to
117
+ ) -> None:
118
+ send = AsyncMock()
119
+ monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
120
+ await SmtpMailSender("smtp.test", 25, "", "", "sender@example.com", False).send(
121
+ MailMessage(to, "Hi", "Body", headers={"X-Description": value})
122
+ )
123
+ wire = send.call_args.args[0]
124
+ assert all(len(line) <= 998 for line in wire.split(b"\r\n"))
125
+ restored = BytesParser(policy=policy.default).parsebytes(wire)
126
+ assert str(restored["X-Description"]) == value
127
+
128
+
129
+ @pytest.mark.parametrize("to", ["a@test", "ä@test"])
130
+ async def test_long_unsubscribe_url_is_unencoded_on_the_wire(monkeypatch, to) -> None:
131
+ send = AsyncMock()
132
+ monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
133
+ value = f"<https://example.com/u?token={'a' * 800}>"
134
+ await SmtpMailSender("smtp.test", 25, "", "", "sender@example.com", False).send(
135
+ MailMessage(
136
+ to,
137
+ "Grüße",
138
+ "Grüße",
139
+ headers={"List-Unsubscribe": value, "X-Description": "😀" * 300},
140
+ )
141
+ )
142
+ wire = send.call_args.args[0]
143
+ headers = wire.split(b"\r\n\r\n", 1)[0]
144
+ unsubscribe = next(line for line in headers.split(b"\r\n") if line.startswith(b"List-"))
145
+ assert unsubscribe == f"List-Unsubscribe: {value}".encode("ascii")
146
+ assert b"=?" not in unsubscribe
147
+ if to.isascii():
148
+ assert b"Subject: =?utf-8?" in headers
149
+ assert wire.isascii()
150
+ restored = BytesParser(policy=policy.default).parsebytes(wire)
151
+ assert restored["Subject"] == "Grüße"
152
+ assert restored["List-Unsubscribe"] == value
153
+ assert restored.get_content().strip() == "Grüße"
@@ -1,4 +1,4 @@
1
- """Mail metadata travels through the persisted durable outbox (#1006, #1025)."""
1
+ """Mail metadata travels through the persisted durable outbox (#1006, #1025, #1053)."""
2
2
 
3
3
  from dataclasses import dataclass
4
4
 
@@ -20,8 +20,9 @@ class RegistrationConfirmed(Event):
20
20
 
21
21
  @pytest.mark.parametrize("legacy", [False, True])
22
22
  @pytest.mark.parametrize("legacy_reply_to", [False, True])
23
+ @pytest.mark.parametrize("legacy_headers", [False, True])
23
24
  async def test_outbox_delivers_attachments_and_legacy_payload(
24
- db_session, db_state, captured_mail, monkeypatch, legacy, legacy_reply_to
25
+ db_session, db_state, captured_mail, monkeypatch, legacy, legacy_reply_to, legacy_headers
25
26
  ) -> None:
26
27
  bus = EventBus()
27
28
 
@@ -51,21 +52,25 @@ async def test_outbox_delivers_attachments_and_legacy_payload(
51
52
  "Body",
52
53
  attachments=attachments,
53
54
  reply_to="guide@example.com",
55
+ headers={"List-Unsubscribe": "<https://example.com/unsubscribe>"},
54
56
  )
55
57
  ),
56
58
  db_session,
57
59
  )
58
60
  row = (await db_session.execute(select(OutboxMessage))).scalar_one()
59
61
  assert row.payload["message"]["reply_to"] == "guide@example.com"
62
+ assert row.payload["message"]["headers"] == {
63
+ "List-Unsubscribe": "<https://example.com/unsubscribe>"
64
+ }
65
+ payload = {**row.payload, "message": dict(row.payload["message"])}
66
+ if legacy_headers:
67
+ del payload["message"]["headers"]
60
68
  if legacy_reply_to:
61
- payload = {**row.payload, "message": dict(row.payload["message"])}
62
69
  del payload["message"]["reply_to"]
63
- row.payload = payload
64
70
  if legacy:
65
- payload = {**row.payload, "message": dict(row.payload["message"])}
66
71
  del payload["message"]["attachments"]
67
- row.payload = payload
68
- else:
72
+ row.payload = payload
73
+ if not legacy:
69
74
  assert row.payload["message"]["attachments"][0]["filename"] == "invite.ics"
70
75
  assert isinstance(row.payload["message"]["attachments"][0]["content"], str)
71
76
  await db_session.commit()
@@ -76,6 +81,9 @@ async def test_outbox_delivers_attachments_and_legacy_payload(
76
81
  message = captured_mail.to("a@test")[0]
77
82
  assert message.subject == "Confirmation"
78
83
  assert message.reply_to == (None if legacy_reply_to else "guide@example.com")
84
+ assert message.headers == (
85
+ {} if legacy_headers else {"List-Unsubscribe": "<https://example.com/unsubscribe>"}
86
+ )
79
87
  if legacy:
80
88
  assert message.attachments == ()
81
89
  else:
@@ -2,6 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from email import policy
6
+ from email.parser import BytesParser
5
7
  from unittest.mock import AsyncMock
6
8
 
7
9
  import pytest
@@ -46,11 +48,15 @@ async def test_send_builds_a_plain_text_message(monkeypatch) -> None:
46
48
 
47
49
  await _smtp().send(MailMessage(to="to@test", subject="Hi", text="Body"))
48
50
 
49
- (email,), kwargs = send.call_args
51
+ (wire,), kwargs = send.call_args
52
+ email = BytesParser(policy=policy.default).parsebytes(wire)
50
53
  assert (email["From"], email["To"], email["Subject"]) == ("from@test", "to@test", "Hi")
51
54
  assert email.get_content_type() == "text/plain"
52
55
  assert email.get_content().strip() == "Body"
53
56
  assert kwargs == {
57
+ "sender": "from@test",
58
+ "recipients": ["to@test"],
59
+ "mail_options": [],
54
60
  "hostname": "smtp.test",
55
61
  "port": 2525,
56
62
  "username": "user",
@@ -66,7 +72,7 @@ async def test_send_adds_an_html_alternative(monkeypatch) -> None:
66
72
 
67
73
  await _smtp().send(MailMessage(to="to@test", subject="Hi", text="Body", html="<b>Body</b>"))
68
74
 
69
- (email,), _ = send.call_args
75
+ email = BytesParser(policy=policy.default).parsebytes(send.call_args.args[0])
70
76
  assert email.get_content_type() == "multipart/alternative"
71
77
  parts = {p.get_content_type(): p.get_content().strip() for p in email.iter_parts()}
72
78
  assert parts == {"text/plain": "Body", "text/html": "<b>Body</b>"}
@@ -83,13 +89,10 @@ async def test_send_adds_an_html_alternative(monkeypatch) -> None:
83
89
  ],
84
90
  )
85
91
  async def test_smtp_reply_to_header(monkeypatch, reply_to) -> None:
86
- from email import policy
87
- from email.parser import BytesParser
88
-
89
92
  send = AsyncMock()
90
93
  monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
91
94
  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())
95
+ email = BytesParser(policy=policy.default).parsebytes(send.call_args.args[0])
93
96
  assert email["Reply-To"] == reply_to
94
97
  assert email["From"] == "from@test"
95
98
  assert email["To"] == "to@test"
@@ -108,9 +111,6 @@ async def test_blank_credentials_are_sent_as_none(monkeypatch) -> None:
108
111
 
109
112
  @pytest.mark.parametrize("html", [None, "<b>Body</b>"])
110
113
  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
114
  send = AsyncMock()
115
115
  monkeypatch.setattr("mail.delivery.sender.aiosmtplib.send", send)
116
116
  await _smtp().send(
@@ -133,7 +133,7 @@ async def test_smtp_attachment_parts_preserve_filename_type_and_bytes(monkeypatc
133
133
  ],
134
134
  )
135
135
  )
136
- email = BytesParser(policy=policy.default).parsebytes(send.call_args.args[0].as_bytes())
136
+ email = BytesParser(policy=policy.default).parsebytes(send.call_args.args[0])
137
137
  parts = list(email.iter_attachments())
138
138
  assert [
139
139
  (p.get_filename(), p.get_content_type(), p.get_payload(decode=True)) for p in parts