Debian Codegraph @

tests/test_email_utils.py

raw
1 """
2 Test message and address parsing/formatting functions.
3 """
4
5 import email.errors
6 import sys
7 from email.header import Header
8 from email.headerregistry import Address
9 from email.message import EmailMessage, Message
10
11 import pytest
12 from hypothesis import example, given
13 from hypothesis.strategies import emails
14
15 from aiosmtplib.email import (
16 extract_recipients,
17 extract_sender,
18 flatten_message,
19 parse_address,
20 quote_address,
21 )
22
23
24 @pytest.mark.parametrize(
25 "address, expected_address",
26 (
27 ('"A.Smith" <[email protected]>', "[email protected]"),
28 ("Pepé Le Pew <pé[email protected]>", "pé[email protected]"),
29 ("<[email protected]>", "[email protected]"),
30 ("B. Smith <[email protected]", "[email protected]"),
31 ),
32 ids=("quotes", "nonascii", "newtld", "missing_end_<"),
33 )
34 def test_parse_address_with_display_names(address: str, expected_address: str) -> None:
35 parsed_address = parse_address(address)
36 assert parsed_address == expected_address
37
38
39 @given(emails())
40 @example("email@[123.123.123.123]")
41 @example("[email protected]")
42 def test_parse_address(email: str) -> None:
43 assert parse_address(email) == email
44
45
46 @pytest.mark.parametrize(
47 "address, expected_address",
48 (
49 ('"A.Smith" <[email protected]>', "<[email protected]>"),
50 ("Pepé Le Pew <pé[email protected]>", "<pé[email protected]>"),
51 ("<[email protected]>", "<[email protected]>"),
52 ("email@[123.123.123.123]", "<email@[123.123.123.123]>"),
53 ("[email protected]", "<[email protected]>"),
54 ("B. Smith <[email protected]", "<[email protected]>"),
55 ),
56 ids=("quotes", "nonascii", "newtld", "ipaddr", "underscores", "missing_end_quote"),
57 )
58 def test_quote_address_with_display_names(address: str, expected_address: str) -> None:
59 quoted_address = quote_address(address)
60 assert quoted_address == expected_address
61
62
63 @given(emails())
64 @example("email@[123.123.123.123]")
65 @example("[email protected]")
66 def test_quote_address(email: str) -> None:
67 assert quote_address(email) == f"<{email}>"
68
69
70 @pytest.mark.parametrize(
71 "address",
72 (
73 "[email protected]> AUTH=<[email protected]",
74 "[email protected]> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;<[email protected]",
75 "[email protected]>\tNOTIFY=SUCCESS",
76 "[email protected]>",
77 "[email protected] >",
78 "[email protected]\r\nRCPT TO:<[email protected]>",
79 ),
80 ids=("auth_param", "dsn_params", "tab", "trailing_>", "space_then_>", "crlf"),
81 )
82 def test_parse_address_rejects_injection(address: str) -> None:
83 with pytest.raises(ValueError):
84 parse_address(address)
85
86 with pytest.raises(ValueError):
87 quote_address(address)
88
89
90 @pytest.mark.parametrize(
91 "address, expected_address",
92 (
93 ('"a b"@example.com', '"a b"@example.com'),
94 ('"a>b"@example.com', '"a>b"@example.com'),
95 ('"a<b"@example.com', '"a<b"@example.com'),
96 ('"a\\"b"@example.com', '"a\\"b"@example.com'),
97 ('Display Name <"a b"@example.com>', '"a b"@example.com'),
98 ("", ""),
99 ),
100 ids=(
101 "quoted_space",
102 "quoted_>",
103 "quoted_<",
104 "quoted_escaped_quote",
105 "quoted_with_display_name",
106 "empty",
107 ),
108 )
109 def test_parse_address_allows_quoted_local_part(
110 address: str, expected_address: str
111 ) -> None:
112 assert parse_address(address) == expected_address
113 assert quote_address(address) == f"<{expected_address}>"
114
115
116 def test_flatten_message() -> None:
117 message = EmailMessage()
118 message["To"] = "[email protected]"
119 message["Subject"] = "Hello, World."
120 message["From"] = "[email protected]"
121 message.set_content("This is a test")
122
123 flat_message = flatten_message(message)
124
125 expected_message = b"""To: [email protected]\r
126 Subject: Hello, World.\r
127 From: [email protected]\r
128 Content-Type: text/plain; charset="utf-8"\r
129 Content-Transfer-Encoding: 7bit\r
130 MIME-Version: 1.0\r
131 \r
132 This is a test\r
133 """
134 assert flat_message == expected_message
135
136
137 @pytest.mark.parametrize(
138 "message_class, utf8, cte_type, expected_chunk",
139 (
140 (Message, False, "7bit", b"=?utf-8?b?w6VsaWNlQGV4YW1wbGUuY29t?="),
141 (Message, True, "7bit", b"=?utf-8?b?w6VsaWNlQGV4YW1wbGUuY29t?="),
142 (Message, False, "8bit", b"=?utf-8?b?w6VsaWNlQGV4YW1wbGUuY29t?="),
143 (Message, True, "8bit", b"=?utf-8?b?w6VsaWNlQGV4YW1wbGUuY29t?="),
144 (EmailMessage, False, "7bit", b"=?utf-8?q?=C3=A5lice?="),
145 (EmailMessage, True, "7bit", b"\xc3\[email protected]"),
146 (EmailMessage, False, "8bit", b"=?utf-8?q?=C3=A5lice?="),
147 (EmailMessage, True, "8bit", b"\xc3\[email protected]"),
148 ),
149 ids=(
150 "compat32-ascii-7bit",
151 "compat32-utf8-7bit",
152 "compat32-ascii-8bit",
153 "compat32-utf8-8bit",
154 "mime-ascii-7bit",
155 "mime-utf8-7bit",
156 "mime-ascii-8bit",
157 "mime-utf8-8bit",
158 ),
159 )
160 def test_flatten_message_utf8_options(
161 message_class: type[EmailMessage] | type[Message],
162 utf8: bool,
163 cte_type: str,
164 expected_chunk: bytes,
165 ) -> None:
166 message = message_class()
167 message["From"] = "å[email protected]"
168
169 # Python 3.15+ refuses to flatten a non-ASCII address under a non-UTF8
170 # EmailPolicy rather than emitting an invalid encoded-word (gh-122540).
171 if message_class is EmailMessage and not utf8 and sys.version_info >= (3, 15):
172 with pytest.raises(email.errors.HeaderWriteError):
173 flatten_message(message, utf8=utf8, cte_type=cte_type)
174 return
175
176 flat_message = flatten_message(message, utf8=utf8, cte_type=cte_type)
177
178 assert expected_chunk in flat_message
179
180
181 def test_flatten_message_removes_bcc_from_message_text() -> None:
182 message = EmailMessage()
183 message["Bcc"] = "[email protected]"
184
185 flat_message = flatten_message(message)
186
187 assert flat_message == b"\r\n" # empty message
188
189
190 def test_flatten_resent_message() -> None:
191 message = EmailMessage()
192 message["To"] = "[email protected]"
193 message["Cc"] = "[email protected]"
194 message["Bcc"] = "[email protected]"
195
196 message["Subject"] = "Hello, World."
197 message["From"] = "[email protected]"
198 message.set_content("This is a test")
199
200 message["Resent-Date"] = "Mon, 20 Nov 2017 21:04:27 -0000"
201 message["Resent-To"] = "[email protected]"
202 message["Resent-Cc"] = "[email protected]"
203 message["Resent-Bcc"] = "[email protected]"
204 message["Resent-Subject"] = "Fwd: Hello, World."
205 message["Resent-From"] = "[email protected]"
206
207 flat_message = flatten_message(message)
208
209 expected_message = b"""To: [email protected]\r
210 Cc: [email protected]\r
211 Subject: Hello, World.\r
212 From: [email protected]\r
213 Content-Type: text/plain; charset="utf-8"\r
214 Content-Transfer-Encoding: 7bit\r
215 MIME-Version: 1.0\r
216 Resent-Date: Mon, 20 Nov 2017 21:04:27 -0000\r
217 Resent-To: [email protected]\r
218 Resent-Cc: [email protected]\r
219 Resent-Subject: Fwd: Hello, World.\r
220 Resent-From: [email protected]\r
221 \r
222 This is a test\r
223 """
224 assert flat_message == expected_message
225
226
227 @pytest.mark.parametrize(
228 "mime_to_header,mime_cc_header,compat32_to_header,"
229 "compat32_cc_header,expected_recipients",
230 (
231 (
232 "Alice Smith <[email protected]>, [email protected]",
233 "Bob <[email protected]>",
234 "Alice Smith <[email protected]>, [email protected]",
235 "Bob <[email protected]>",
236 ["[email protected]", "[email protected]", "[email protected]"],
237 ),
238 (
239 Address(display_name="Alice Smith", username="alice", domain="example.com"),
240 Address(display_name="Bob", username="Bob", domain="example.com"),
241 Header("Alice Smith <[email protected]>"),
242 Header("Bob <[email protected]>"),
243 ["[email protected]", "[email protected]"],
244 ),
245 (
246 Address(display_name="ålice Smith", username="ålice", domain="example.com"),
247 Address(display_name="Bøb", username="Bøb", domain="example.com"),
248 Header("ålice Smith <å[email protected]>"),
249 Header("Bøb <Bø[email protected]>"),
250 ["å[email protected]", "Bø[email protected]"],
251 ),
252 (
253 Address(display_name="ålice Smith", username="alice", domain="example.com"),
254 Address(display_name="Bøb", username="Bob", domain="example.com"),
255 Header("ålice Smith <[email protected]>"),
256 Header("Bøb <[email protected]>"),
257 ["[email protected]", "[email protected]"],
258 ),
259 ),
260 ids=("str", "ascii", "utf8_address", "utf8_display_name"),
261 )
262 def test_extract_recipients(
263 mime_to_header: str | Address,
264 mime_cc_header: str | Address,
265 compat32_to_header: str | Header,
266 compat32_cc_header: str | Header,
267 expected_recipients: list[str],
268 ) -> None:
269 mime_message = EmailMessage()
270 mime_message["To"] = mime_to_header
271 mime_message["Cc"] = mime_cc_header
272
273 mime_recipients = extract_recipients(mime_message)
274
275 assert mime_recipients == expected_recipients
276
277 compat32_message = Message()
278 compat32_message["To"] = compat32_to_header
279 compat32_message["Cc"] = compat32_cc_header
280
281 compat32_recipients = extract_recipients(compat32_message)
282
283 assert compat32_recipients == expected_recipients
284
285
286 def test_extract_recipients_includes_bcc() -> None:
287 message = EmailMessage()
288 message["Bcc"] = "[email protected]"
289
290 recipients = extract_recipients(message)
291
292 assert recipients == [message["Bcc"]]
293
294
295 def test_extract_recipients_invalid_email() -> None:
296 message = EmailMessage()
297 message["Cc"] = "me"
298
299 recipients = extract_recipients(message)
300
301 assert recipients == ["me"]
302
303
304 def test_extract_recipients_with_iterable_of_strings() -> None:
305 message = EmailMessage()
306 message["To"] = ("[email protected]", "you")
307
308 recipients = extract_recipients(message)
309
310 assert recipients == ["[email protected]", "you"]
311
312
313 def test_extract_recipients_resent_message() -> None:
314 message = EmailMessage()
315 message["To"] = "[email protected]"
316 message["Cc"] = "[email protected]"
317 message["Bcc"] = "[email protected]"
318
319 message["Resent-Date"] = "Mon, 20 Nov 2017 21:04:27 -0000"
320 message["Resent-To"] = "[email protected]"
321 message["Resent-Cc"] = "[email protected]"
322 message["Resent-Bcc"] = "[email protected]"
323
324 recipients = extract_recipients(message)
325
326 assert message["Resent-To"] in recipients
327 assert message["Resent-Cc"] in recipients
328 assert message["Resent-Bcc"] in recipients
329 assert message["To"] not in recipients
330 assert message["Cc"] not in recipients
331 assert message["Bcc"] not in recipients
332
333
334 def test_extract_recipients_valueerror_on_multiple_resent_message() -> None:
335 message = EmailMessage()
336 message["Resent-Date"] = "Mon, 20 Nov 2016 21:04:27 -0000"
337 message["Resent-Date"] = "Mon, 20 Nov 2017 21:04:27 -0000"
338
339 with pytest.raises(ValueError):
340 extract_recipients(message)
341
342
343 @pytest.mark.parametrize(
344 "mime_header,compat32_header,expected_sender",
345 (
346 (
347 "Alice Smith <[email protected]>",
348 "Alice Smith <[email protected]>",
349 "[email protected]",
350 ),
351 (
352 Address(display_name="Alice Smith", username="alice", domain="example.com"),
353 Header("Alice Smith <[email protected]>"),
354 "[email protected]",
355 ),
356 (
357 Address(display_name="ålice Smith", username="ålice", domain="example.com"),
358 Header("ålice Smith <å[email protected]>", "utf-8"),
359 "å[email protected]",
360 ),
361 (
362 Address(display_name="ålice Smith", username="alice", domain="example.com"),
363 Header("ålice Smith <[email protected]>", "utf-8"),
364 "[email protected]",
365 ),
366 ),
367 ids=("str", "ascii", "utf8_address", "utf8_display_name"),
368 )
369 def test_extract_sender(
370 mime_header: str | Address,
371 compat32_header: str | Header,
372 expected_sender: str,
373 ) -> None:
374 mime_message = EmailMessage()
375 mime_message["From"] = mime_header
376
377 mime_sender = extract_sender(mime_message)
378
379 assert mime_sender == expected_sender
380
381 compat32_message = Message()
382 compat32_message["From"] = compat32_header
383
384 compat32_sender = extract_sender(compat32_message)
385
386 assert compat32_sender == expected_sender
387
388
389 def test_extract_sender_prefers_sender_header() -> None:
390 message = EmailMessage()
391 message["From"] = "[email protected]"
392 message["Sender"] = "[email protected]"
393
394 sender = extract_sender(message)
395
396 assert sender != message["From"]
397 assert sender == message["Sender"]
398
399
400 def test_extract_sender_resent_message() -> None:
401 message = EmailMessage()
402 message["From"] = "[email protected]"
403
404 message["Resent-Date"] = "Mon, 20 Nov 2017 21:04:27 -0000"
405 message["Resent-From"] = "[email protected]"
406
407 sender = extract_sender(message)
408
409 assert sender == message["Resent-From"]
410 assert sender != message["From"]
411
412
413 def test_extract_sender_valueerror_on_multiple_resent_message() -> None:
414 message = EmailMessage()
415 message["Resent-Date"] = "Mon, 20 Nov 2016 21:04:27 -0000"
416 message["Resent-Date"] = "Mon, 20 Nov 2017 21:04:27 -0000"
417
418 with pytest.raises(ValueError):
419 extract_sender(message)
420
421
422 def test_extract_sender_empty_address_returns_none() -> None:
423 """
424 Test that extract_sender returns None when the From header contains no valid addresses.
425
426 If extract_addresses() returns an empty list (e.g., malformed From header),
427 extract_sender should return None instead of raising IndexError.
428 """
429 message = EmailMessage()
430 # Use undisclosed-recipients which parses to an empty list
431 message["From"] = "undisclosed-recipients:;"
432
433 sender = extract_sender(message)
434 assert sender is None