diff --git a/src/forwarder/email/smtp_client.py b/src/forwarder/email/smtp_client.py index b41a9c6..da8dff3 100644 --- a/src/forwarder/email/smtp_client.py +++ b/src/forwarder/email/smtp_client.py @@ -22,6 +22,22 @@ _RESUBMIT_DROP_HEADERS = ( "Authentication-Results", ) +# Extra recipients on a resend would loop back into the monitored mailbox. +_RECIPIENT_HEADERS_TO_STRIP = ( + "Cc", + "Bcc", + "Reply-To", + "Delivered-To", + "X-Original-To", + "X-Forwarded-To", + "Resent-To", + "Resent-From", + "Resent-Date", + "Resent-Message-ID", + "Return-Receipt-To", + "Disposition-Notification-To", +) + @dataclass class SmtpConfig: @@ -52,6 +68,12 @@ def _set_header(msg: EmailMessage, name: str, value: str) -> None: msg[name] = value +def _strip_headers(msg: EmailMessage, names: tuple[str, ...]) -> None: + for header in names: + while msg.get(header) is not None: + del msg[header] + + def build_forward_message( original_msg: EmailMessage, *, @@ -73,6 +95,8 @@ def build_forward_message( while fwd.get(header) is not None: del fwd[header] + _strip_headers(fwd, _RECIPIENT_HEADERS_TO_STRIP) + subject = clean_subject(fwd.get("Subject")) if subject and not subject.lower().startswith(("fwd:", "fw:", "re:")): subject = f"Fwd: {subject}" @@ -103,7 +127,12 @@ def forward_original_message( client = create_smtp_client(smtp_config) try: - client.send_message(fwd) + # to_addrs: only BizDocs — ignore any stray recipient headers in the MIME copy. + client.send_message( + fwd, + from_addr=smtp_config.user, + to_addrs=[destination_email], + ) finally: if owns_client: try: diff --git a/tests/test_smtp_forward.py b/tests/test_smtp_forward.py index 1302ced..4d49bbd 100644 --- a/tests/test_smtp_forward.py +++ b/tests/test_smtp_forward.py @@ -57,3 +57,25 @@ def test_forward_does_not_double_prefix_subject(): ) assert fwd["Subject"] == "Fwd: Already forwarded" + + +def test_forward_strips_cc_bcc_to_prevent_loop(): + original = EmailMessage() + original["From"] = "vendor@example.com" + original["To"] = "faturas@empresa.pt" + original["Cc"] = "faturas@empresa.pt, contabilidade@empresa.pt" + original["Bcc"] = "faturas@empresa.pt" + original["Reply-To"] = "faturas@empresa.pt" + original["Subject"] = "Fatura loop" + original.set_content("test") + + fwd = build_forward_message( + original, + from_addr="faturas@empresa.pt", + destination_email="inbox.arquivodigital@bizdocs.mobi", + ) + + assert fwd["To"] == "inbox.arquivodigital@bizdocs.mobi" + assert fwd.get("Cc") is None + assert fwd.get("Bcc") is None + assert fwd.get("Reply-To") is None