fix: strip Cc/Bcc on forward to prevent mailbox loop

Re-sending the original MIME kept Cc/Bcc (e.g. faturas@) so copies
returned to the monitored inbox. Drop extra recipient headers and
send SMTP RCPT only to the BizDocs destination.
This commit is contained in:
1sonhador committed 2026-07-01 09:51:00 +01:00
1 parent ea88e8833d
commit f19886d78e
2 files changed
+52 -1

No files matched your search

+30 -1
View File
@@ -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:
+22
View File
@@ -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"] = "[email protected]"
original["To"] = "[email protected]"
original["Cc"] = "[email protected], [email protected]"
original["Bcc"] = "[email protected]"
original["Reply-To"] = "[email protected]"
original["Subject"] = "Fatura loop"
original.set_content("test")
fwd = build_forward_message(
original,
from_addr="[email protected]",
destination_email="[email protected]",
)
assert fwd["To"] == "[email protected]"
assert fwd.get("Cc") is None
assert fwd.get("Bcc") is None
assert fwd.get("Reply-To") is None