1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
|
"""
SMTP.sendmail and SMTP.send_message method testing.
"""
import copy
import email.generator
import email.header
import email.message
from typing import Any, Optional, Union
import pytest
from aiosmtplib import (
SMTP,
SMTPNotSupported,
SMTPRecipientsRefused,
SMTPResponseException,
SMTPStatus,
)
from .smtpd import (
mock_response_done,
mock_response_error_disconnect,
mock_response_bad_command_sequence,
)
async def test_sendmail_simple_success(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
) -> None:
async with smtp_client:
errors, response = await smtp_client.sendmail(
sender_str, [recipient_str], message_str
)
assert not errors
assert isinstance(errors, dict)
assert response != ""
async def test_sendmail_binary_content(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
) -> None:
async with smtp_client:
errors, response = await smtp_client.sendmail(
sender_str, [recipient_str], bytes(message_str, "ascii")
)
assert not errors
assert isinstance(errors, dict)
assert response != ""
async def test_sendmail_with_recipients_string(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
) -> None:
async with smtp_client:
errors, response = await smtp_client.sendmail(
sender_str, recipient_str, message_str
)
assert not errors
assert response != ""
async def test_sendmail_with_mail_option(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
) -> None:
async with smtp_client:
errors, response = await smtp_client.sendmail(
sender_str, [recipient_str], message_str, mail_options=["BODY=8BITMIME"]
)
assert not errors
assert response != ""
@pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_done)
async def test_sendmail_without_size_option(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
) -> None:
async with smtp_client:
errors, response = await smtp_client.sendmail(
sender_str, [recipient_str], message_str
)
assert not errors
assert response != ""
async def test_sendmail_with_invalid_mail_option(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
) -> None:
async with smtp_client:
with pytest.raises(SMTPResponseException) as excinfo:
await smtp_client.sendmail(
sender_str,
[recipient_str],
message_str,
mail_options=["BADDATA=0x00000000"],
)
assert excinfo.value.code == SMTPStatus.syntax_error
async def test_sendmail_with_rcpt_option(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
) -> None:
async with smtp_client:
with pytest.raises(SMTPRecipientsRefused) as excinfo:
await smtp_client.sendmail(
sender_str,
[recipient_str],
message_str,
rcpt_options=["NOTIFY=FAILURE,DELAY"],
)
recipient_exc = excinfo.value.recipients[0]
assert recipient_exc.code == SMTPStatus.syntax_error
assert (
recipient_exc.message
== "RCPT TO parameters not recognized or not implemented"
)
async def test_sendmail_simple_failure(smtp_client: SMTP) -> None:
async with smtp_client:
with pytest.raises(SMTPRecipientsRefused):
# @@ is an invalid recipient.
await smtp_client.sendmail("test@example.com", ["@@"], "blah")
async def test_sendmail_smtputf8_not_supported(smtp_client: SMTP) -> None:
async with smtp_client:
with pytest.raises(SMTPNotSupported, match="SMTPUTF8 is not supported"):
await smtp_client.sendmail(
"test@example.com",
["børk@example.com"],
"blah",
mail_options=["SMTPUTF8"],
)
@pytest.mark.smtpd_mocks(smtp_DATA=mock_response_error_disconnect)
async def test_sendmail_error_silent_rset_handles_disconnect(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
) -> None:
async with smtp_client:
with pytest.raises(SMTPResponseException):
await smtp_client.sendmail(sender_str, [recipient_str], message_str)
async def test_rset_after_sendmail_error_response_to_mail(
smtp_client: SMTP,
received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
"""
If an error response is given to the MAIL command in the sendmail method,
test that we reset the server session.
"""
async with smtp_client:
response = await smtp_client.ehlo()
assert response.code == SMTPStatus.completed
with pytest.raises(SMTPResponseException) as excinfo:
await smtp_client.sendmail(">foobar<", ["test@example.com"], "Hello World")
assert excinfo.value.code == SMTPStatus.unrecognized_parameters
assert received_commands[-1][0] == "RSET"
async def test_rset_after_sendmail_error_response_to_rcpt(
smtp_client: SMTP,
received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
"""
If an error response is given to the RCPT command in the sendmail method,
test that we reset the server session.
"""
async with smtp_client:
response = await smtp_client.ehlo()
assert response.code == SMTPStatus.completed
with pytest.raises(SMTPRecipientsRefused) as excinfo:
await smtp_client.sendmail(
"test@example.com", [">not an addr<"], "Hello World"
)
assert excinfo.value.recipients[0].code == SMTPStatus.unrecognized_parameters
assert received_commands[-1][0] == "RSET"
@pytest.mark.smtpd_mocks(smtp_DATA=mock_response_bad_command_sequence)
async def test_rset_after_sendmail_error_response_to_data(
smtp_client: SMTP,
sender_str: str,
recipient_str: str,
message_str: str,
received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
"""
If an error response is given to the DATA command in the sendmail method,
test that we reset the server session.
"""
async with smtp_client:
response = await smtp_client.ehlo()
assert response.code == SMTPStatus.completed
with pytest.raises(SMTPResponseException) as excinfo:
await smtp_client.sendmail(sender_str, [recipient_str], message_str)
assert excinfo.value.code == SMTPStatus.bad_command_sequence
assert received_commands[-1][0] == "RSET"
async def test_send_message(smtp_client: SMTP, message: email.message.Message) -> None:
async with smtp_client:
errors, response = await smtp_client.send_message(message)
assert not errors
assert isinstance(errors, dict)
assert response != ""
async def test_send_message_with_sender_and_recipient_args(
smtp_client: SMTP,
message: email.message.EmailMessage,
received_messages: list[email.message.EmailMessage],
) -> None:
sender = "sender2@example.com"
recipients = ["recipient1@example.com", "recipient2@example.com"]
async with smtp_client:
errors, response = await smtp_client.send_message(
message, sender=sender, recipients=recipients
)
assert not errors
assert isinstance(errors, dict)
assert response != ""
assert len(received_messages) == 1
assert received_messages[0]["X-MailFrom"] == sender
assert received_messages[0]["X-RcptTo"] == ", ".join(recipients)
async def test_send_message_with_cc_recipients(
smtp_client: SMTP,
recipient_str: str,
message: email.message.EmailMessage,
received_messages: list[email.message.EmailMessage],
received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
cc_recipients = ["recipient1@example.com", "recipient2@example.com"]
message["Cc"] = ", ".join(cc_recipients)
async with smtp_client:
errors, _ = await smtp_client.send_message(message)
assert not errors
assert len(received_messages) == 1
assert (
received_messages[0]["X-RcptTo"]
== f"{recipient_str}, {', '.join(cc_recipients)}"
)
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1][0] == recipient_str
assert received_commands[3][0] == "RCPT"
assert received_commands[3][1][0] == cc_recipients[0]
assert received_commands[4][0] == "RCPT"
assert received_commands[4][1][0] == cc_recipients[1]
async def test_send_message_with_bcc_recipients(
smtp_client: SMTP,
recipient_str: str,
message: email.message.EmailMessage,
received_messages: list[email.message.EmailMessage],
received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
bcc_recipients = ["recipient1@example.com", "recipient2@example.com"]
message["Bcc"] = ", ".join(bcc_recipients)
async with smtp_client:
errors, _ = await smtp_client.send_message(message)
assert not errors
assert len(received_messages) == 1
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1][0] == recipient_str
assert received_commands[3][0] == "RCPT"
assert received_commands[3][1][0] == bcc_recipients[0]
assert received_commands[4][0] == "RCPT"
assert received_commands[4][1][0] == bcc_recipients[1]
async def test_send_message_with_cc_and_bcc_recipients(
smtp_client: SMTP,
recipient_str: str,
message: email.message.EmailMessage,
received_messages: list[email.message.EmailMessage],
received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
cc_recipient = "recipient2@example.com"
message["Cc"] = cc_recipient
bcc_recipient = "recipient2@example.com"
message["Bcc"] = bcc_recipient
async with smtp_client:
errors, _ = await smtp_client.send_message(message)
assert not errors
assert len(received_messages) == 1
assert received_messages[0]["To"] == recipient_str
assert received_messages[0]["Cc"] == cc_recipient
# BCC shouldn't be passed through
assert received_messages[0]["Bcc"] is None
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1][0] == recipient_str
assert received_commands[3][0] == "RCPT"
assert received_commands[3][1][0] == cc_recipient
assert received_commands[4][0] == "RCPT"
assert received_commands[4][1][0] == bcc_recipient
async def test_send_message_recipient_str(
smtp_client: SMTP,
message: email.message.EmailMessage,
received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
recipient_str = "1234@example.org"
async with smtp_client:
errors, response = await smtp_client.send_message(
message, recipients=recipient_str
)
assert not errors
assert isinstance(errors, dict)
assert response != ""
assert received_commands[2][1][0] == recipient_str
async def test_send_message_mail_options(
smtp_client: SMTP,
message: email.message.EmailMessage,
) -> None:
async with smtp_client:
errors, response = await smtp_client.send_message(
message, mail_options=["BODY=8BITMIME"]
)
assert not errors
assert isinstance(errors, dict)
assert response != ""
async def test_send_multiple_messages_in_sequence(
smtp_client: SMTP, message: email.message.EmailMessage
) -> None:
message1 = copy.copy(message)
message2 = copy.copy(message)
del message2["To"]
message2["To"] = "recipient2@example.com"
async with smtp_client:
errors1, response1 = await smtp_client.send_message(message1)
assert not errors1
assert isinstance(errors1, dict)
assert response1 != ""
errors2, response2 = await smtp_client.send_message(message2)
assert not errors2
assert isinstance(errors2, dict)
assert response2 != ""
async def test_send_message_without_recipients(
smtp_client: SMTP, message: email.message.EmailMessage
) -> None:
del message["To"]
async with smtp_client:
with pytest.raises(ValueError):
await smtp_client.send_message(message)
async def test_send_message_without_sender(
smtp_client: SMTP, message: email.message.EmailMessage
) -> None:
del message["From"]
async with smtp_client:
with pytest.raises(ValueError):
await smtp_client.send_message(message)
@pytest.mark.parametrize(
"message", ["message", "compat32_message", "mime_message"], indirect=True
)
@pytest.mark.smtpd_options(smtputf8=True)
async def test_send_message_smtputf8_sender(
smtp_client: SMTP,
message: Union[email.message.EmailMessage, email.message.Message],
received_commands: list[tuple[str, tuple[Any, ...]]],
received_messages: list[email.message.EmailMessage],
) -> None:
del message["From"]
message["From"] = "séndër@exåmple.com"
async with smtp_client:
errors, response = await smtp_client.send_message(message)
assert not errors
assert response != ""
assert received_commands[1][0] == "MAIL"
assert received_commands[1][1][0] == message["From"]
# Size varies depending on the message type
assert received_commands[1][1][1][0].startswith("SIZE=")
assert received_commands[1][1][1][1:] == ["SMTPUTF8", "BODY=8BITMIME"]
assert len(received_messages) == 1
assert received_messages[0]["X-MailFrom"] == message["From"]
@pytest.mark.smtpd_options(smtputf8=True)
@pytest.mark.parametrize(
"mail_options",
(None, ["SMTPUTF8"]),
ids=("no_mail_options", "smtputf8_option"),
)
async def test_send_mime_message_smtputf8_recipient(
smtp_client: SMTP,
mime_message: email.message.EmailMessage,
received_commands: list[tuple[str, tuple[Any, ...]]],
received_messages: list[email.message.EmailMessage],
mail_options: Optional[list[str]],
) -> None:
mime_message["To"] = "reçipïént@exåmple.com"
async with smtp_client:
errors, response = await smtp_client.send_message(
mime_message, mail_options=mail_options
)
assert not errors
assert response != ""
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1][0] == mime_message["To"]
assert len(received_messages) == 1
assert received_messages[0]["X-RcptTo"] == ", ".join(mime_message.get_all("To"))
@pytest.mark.smtpd_options(smtputf8=True)
async def test_send_compat32_message_smtputf8_recipient(
smtp_client: SMTP,
compat32_message: email.message.Message,
received_commands: list[tuple[str, tuple[Any, ...]]],
received_messages: list[email.message.EmailMessage],
) -> None:
recipient_bytes = bytes("reçipïént@exåmple.com", "utf-8")
compat32_message["To"] = email.header.Header(recipient_bytes, "utf-8")
async with smtp_client:
errors, response = await smtp_client.send_message(compat32_message)
assert not errors
assert response != ""
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1][0] == compat32_message["To"]
assert len(received_messages) == 1
assert (
received_messages[0]["X-RcptTo"]
== "recipient@example.com, reçipïént@exåmple.com"
)
@pytest.mark.smtpd_options(smtputf8=False)
async def test_send_message_smtputf8_not_supported(
smtp_client: SMTP, message: email.message.EmailMessage
) -> None:
del message["To"]
message["To"] = "reçipïént2@exåmple.com"
async with smtp_client:
with pytest.raises(SMTPNotSupported):
await smtp_client.send_message(message)
@pytest.mark.smtpd_options(smtputf8=False)
async def test_send_compat32_message_utf8_text_without_smtputf8(
smtp_client: SMTP,
compat32_message: email.message.Message,
received_commands: list[tuple[str, tuple[Any, ...]]],
received_messages: list[email.message.EmailMessage],
) -> None:
compat32_message["To"] = email.header.Header(
"reçipïént <recipient2@example.com>", "utf-8"
)
async with smtp_client:
errors, response = await smtp_client.send_message(compat32_message)
assert not errors
assert response != ""
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1][0] == compat32_message["To"].encode()
assert len(received_messages) == 1
assert (
received_messages[0]["X-RcptTo"]
== "recipient@example.com, recipient2@example.com"
)
# Name should be encoded
assert received_messages[0].get_all("To") == [
"recipient@example.com",
"=?utf-8?b?cmXDp2lww6/DqW50IDxyZWNpcGllbnQyQGV4YW1wbGUuY29tPg==?=",
]
@pytest.mark.smtpd_options(smtputf8=False)
async def test_send_mime_message_utf8_text_without_smtputf8(
smtp_client: SMTP,
mime_message: email.message.EmailMessage,
received_commands: list[tuple[str, tuple[Any, ...]]],
received_messages: list[email.message.EmailMessage],
) -> None:
mime_message["To"] = "reçipïént <recipient2@example.com>"
async with smtp_client:
errors, response = await smtp_client.send_message(mime_message)
assert not errors
assert response != ""
assert received_commands[2][0] == "RCPT"
assert received_commands[2][1][0] == mime_message["To"]
assert len(received_messages) == 1
assert (
received_messages[0]["X-RcptTo"]
== "recipient@example.com, recipient2@example.com"
)
# Name should be encoded
assert received_messages[0].get_all("To") == [
"recipient@example.com",
"=?utf-8?b?cmXDp2lww6/DqW50IDxyZWNpcGllbnQyQGV4YW1wbGUuY29tPg==?=",
]
@pytest.mark.parametrize(
"message", ["message", "compat32_message", "mime_message"], indirect=True
)
@pytest.mark.smtpd_options(**{"smtputf8": False, "7bit": True})
async def test_send_message_7bit(
smtp_client: SMTP,
message: Union[email.message.EmailMessage, email.message.Message],
received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
async with smtp_client:
errors, response = await smtp_client.send_message(message)
assert not errors
assert response != ""
assert "BODY=8BITMIME" not in received_commands[1][1][1]
async def test_sendmail_empty_sender(
smtp_client: SMTP, recipient_str: str, message_str: str
) -> None:
async with smtp_client:
errors, response = await smtp_client.sendmail("", [recipient_str], message_str)
assert not errors
assert isinstance(errors, dict)
assert response != ""
|