fix: send clean invoice-only emails to avoid MailChannels spam blocks

Stop relaying the original RFC822 (SendGrid headers, Fwd: subject, etc.).
Send a new message with PDF/XML/ZIP attachments and minimal metadata body.
This commit is contained in:
1sonhador committed 2026-07-01 09:56:38 +01:00
1 parent f19886d78e
commit 95edd74d9f
4 files changed
+86 -108

No files matched your search

+1 -1
View File
@@ -131,7 +131,7 @@ function AccountModal({
<fieldset className="border border-gray-200 rounded-md p-3">
<legend className="text-xs font-semibold text-gray-500 px-1">BizDocs (destino)</legend>
<p className="text-xs text-gray-500 mb-2">
Email para onde os emails reencaminhados são enviados (forward normal SMTP).
Email para onde são enviados os anexos de fatura (PDF/XML/ZIP) — email limpo, sem reencaminhar o original.
</p>
{field(
'Email destino',
+49 -61
View File
@@ -4,40 +4,18 @@ from __future__ import annotations
import smtplib
from dataclasses import dataclass
from email import message_from_bytes, policy
from email.message import EmailMessage
from forwarder.email.parsing import clean_subject
from forwarder.email.parsing import (
DEFAULT_ALLOWED_EXTENSIONS,
clean_subject,
collect_matching_attachments,
)
DEFAULT_SMTP_TIMEOUT = 30
CONNECTION_TEST_SMTP_TIMEOUT = 5
# Signatures added by the inbound path — drop before resubmitting via SMTP.
_RESUBMIT_DROP_HEADERS = (
"DKIM-Signature",
"ARC-Authentication-Results",
"ARC-Message-Signature",
"ARC-Seal",
"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:
@@ -62,63 +40,74 @@ def create_smtp_client(
return client
def _set_header(msg: EmailMessage, name: str, value: str) -> None:
if msg.get(name) is not None:
del msg[name]
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,
*,
from_addr: str,
destination_email: str,
include_all_attachments: bool = False,
allowed_extensions: set[str] | None = None,
) -> EmailMessage:
"""Re-send the original RFC822 message with normal forward headers.
"""Build a clean outbound message with invoice files only.
Same MIME body and attachments as received — no .eml wrapper, no re-packaging.
Does not relay the original RFC822 (avoids spam filters, loops, and MailChannels
blocks on inherited bulk-mail headers). Keeps the original subject without Fwd:.
"""
fwd = message_from_bytes(
original_msg.as_bytes(policy=policy.default),
policy=policy.default,
if allowed_extensions is None:
allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS
attachments = collect_matching_attachments(
original_msg,
include_all_attachments=include_all_attachments,
allowed_extensions=allowed_extensions,
)
if not isinstance(fwd, EmailMessage):
fwd = EmailMessage(fwd)
if not attachments:
raise ValueError("No matching invoice attachments to forward")
for header in _RESUBMIT_DROP_HEADERS:
while fwd.get(header) is not None:
del fwd[header]
subject = clean_subject(original_msg.get("Subject"))
sender = original_msg.get("From", "")
date = original_msg.get("Date", "")
_strip_headers(fwd, _RECIPIENT_HEADERS_TO_STRIP)
outbound = EmailMessage()
outbound["From"] = from_addr
outbound["To"] = destination_email
outbound["Subject"] = subject
subject = clean_subject(fwd.get("Subject"))
if subject and not subject.lower().startswith(("fwd:", "fw:", "re:")):
subject = f"Fwd: {subject}"
body = (
"Documento reencaminhado para arquivo digital.\n\n"
f"Remetente original: {sender}\n"
f"Data original: {date}\n"
f"Assunto original: {subject}\n"
f"Anexos: {', '.join(a.filename for a in attachments)}\n"
)
outbound.set_content(body)
_set_header(fwd, "From", from_addr)
_set_header(fwd, "To", destination_email)
_set_header(fwd, "Subject", subject)
for attachment in attachments:
outbound.add_attachment(
attachment.data,
maintype=attachment.maintype,
subtype=attachment.subtype,
filename=attachment.filename,
)
return fwd
return outbound
def forward_original_message(
def forward_invoice_attachments(
original_msg: EmailMessage,
*,
smtp_config: SmtpConfig,
destination_email: str,
smtp: smtplib.SMTP | None = None,
include_all_attachments: bool = False,
allowed_extensions: set[str] | None = None,
) -> None:
fwd = build_forward_message(
outbound = build_forward_message(
original_msg,
from_addr=smtp_config.user,
destination_email=destination_email,
include_all_attachments=include_all_attachments,
allowed_extensions=allowed_extensions,
)
owns_client = smtp is None
@@ -127,9 +116,8 @@ def forward_original_message(
client = create_smtp_client(smtp_config)
try:
# to_addrs: only BizDocs — ignore any stray recipient headers in the MIME copy.
client.send_message(
fwd,
outbound,
from_addr=smtp_config.user,
to_addrs=[destination_email],
)
+8 -3
View File
@@ -29,7 +29,7 @@ from forwarder.email.parsing import (
get_message_key,
has_matching_attachment,
)
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_original_message
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_invoice_attachments
from forwarder.error_reporter import report_error, report_error_with_cooldown
from forwarder.services.account_service import get_account
@@ -256,11 +256,13 @@ def sync_account(
continue
try:
forward_original_message(
forward_invoice_attachments(
msg,
smtp_config=smtp_config,
destination_email=account.destination_email,
smtp=smtp,
include_all_attachments=account.include_all_attachments,
allowed_extensions=allowed_extensions,
)
message_row = _upsert_message(
db,
@@ -386,11 +388,14 @@ def retry_single_message(db: Session, message_id: int) -> Message:
raise ValueError(f"Could not fetch message UID {message.uid}")
smtp = create_smtp_client(smtp_config)
forward_original_message(
allowed_extensions = set(account.allowed_extensions or [])
forward_invoice_attachments(
msg,
smtp_config=smtp_config,
destination_email=account.destination_email,
smtp=smtp,
include_all_attachments=account.include_all_attachments,
allowed_extensions=allowed_extensions,
)
message.status = MessageStatus.forwarded
+28 -43
View File
@@ -1,4 +1,4 @@
"""Forward re-sends the original message — no .eml wrapper."""
"""Outbound forward sends a clean message with invoice attachments only."""
from __future__ import annotations
@@ -7,12 +7,13 @@ from email.message import EmailMessage
from forwarder.email.smtp_client import build_forward_message
def test_forward_resends_original_with_updated_headers():
def test_forward_sends_clean_message_with_pdf_only():
original = EmailMessage()
original["From"] = "[email protected]"
original["To"] = "inbox@company.pt"
original["Subject"] = "Fatura 123"
original.set_content("corpo original")
original["From"] = "[email protected]"
original["To"] = "faturas@bitreport.pt"
original["Subject"] = "Invoice & Ticket Delivery"
original["X-SG-EID"] = "spam-marker"
original.set_content("marketing body")
original.add_attachment(
b"%PDF-1.4",
maintype="application",
@@ -20,62 +21,46 @@ def test_forward_resends_original_with_updated_headers():
filename="fatura.pdf",
)
fwd = build_forward_message(
outbound = build_forward_message(
original,
from_addr="relay@company.pt",
from_addr="faturas@bitreport.pt",
destination_email="[email protected]",
)
assert fwd["From"] == "relay@company.pt"
assert fwd["To"] == "[email protected]"
assert fwd["Subject"] == "Fwd: Fatura 123"
assert outbound["From"] == "faturas@bitreport.pt"
assert outbound["To"] == "[email protected]"
assert outbound["Subject"] == "Invoice & Ticket Delivery"
assert not outbound["Subject"].lower().startswith("fwd:")
assert outbound.get("Cc") is None
assert outbound.get("X-SG-EID") is None
attachments = list(fwd.iter_attachments())
attachments = list(outbound.iter_attachments())
assert len(attachments) == 1
assert attachments[0].get_filename() == "fatura.pdf"
assert attachments[0].get_content_type() == "application/pdf"
assert not any((p.get_filename() or "").endswith(".eml") for p in attachments)
# Body preserved from original.
text_parts = [
p.get_payload(decode=True)
for p in fwd.walk()
p.get_content()
for p in outbound.walk()
if not p.is_multipart() and p.get_content_type() == "text/plain"
]
assert any(b"corpo original" in (part or b"") for part in text_parts)
assert text_parts
assert "Remetente original" in text_parts[0]
assert "marketing body" not in text_parts[0]
def test_forward_does_not_double_prefix_subject():
def test_forward_includes_multiple_invoice_types():
original = EmailMessage()
original["Subject"] = "Fwd: Already forwarded"
original["Subject"] = "Docs"
original.set_content("x")
original.add_attachment(b"%PDF", maintype="application", subtype="pdf", filename="a.pdf")
original.add_attachment(b"<x/>", maintype="text", subtype="xml", filename="b.xml")
fwd = build_forward_message(
outbound = build_forward_message(
original,
from_addr="[email protected]",
destination_email="[email protected]",
)
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
names = {p.get_filename() for p in outbound.iter_attachments()}
assert names == {"a.pdf", "b.xml"}