fix: forward original email via SMTP instead of .eml attachment

Re-send the received RFC822 message with normal Fwd headers (To, From,
Subject). The previous code wrapped the message in message/rfc822 with
filename original-email.eml, which the relay rejected.
This commit is contained in:
1sonhador committed 2026-07-01 09:18:11 +01:00
1 parent f664cca6b5
commit b070af8503
5 files changed
+64 -83

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
# BizDocs Forwarder
Multi-account IMAP → BizDocs forwarder: detect invoice attachments (PDF/XML/ZIP), re-send via SMTP.
Multi-account IMAP → BizDocs forwarder: detect invoice attachments (PDF/XML/ZIP), forward original email via SMTP.
- **Repo:** https://git.bitreport.pt/BitReport.pt/forwarder
- **Paperclip:** http://10.10.50.17:3100/BIT/projects/bizdocs-forwarder
+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 as facturas são reencaminhadas via SMTP (anexos PDF/XML/ZIP).
Email para onde os emails reencaminhados são enviados (forward normal SMTP).
</p>
{field(
'Email destino',
+34 -51
View File
@@ -4,18 +4,24 @@ 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 (
DEFAULT_ALLOWED_EXTENSIONS,
collect_matching_attachments,
clean_subject,
)
from forwarder.email.parsing import clean_subject
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",
)
@dataclass
class SmtpConfig:
@@ -40,74 +46,55 @@ 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 build_forward_message(
original_msg: EmailMessage,
*,
from_addr: str,
destination_email: str,
include_all_attachments: bool = False,
allowed_extensions: set[str] | None = None,
) -> EmailMessage:
"""Build outbound message with invoice files attached (PDF/XML/ZIP).
"""Re-send the original RFC822 message with normal forward headers.
Relays typically allow these extensions; wrapping the whole email as .eml
is rejected by most outbound SMTP filters.
Same MIME body and attachments as received — no .eml wrapper, no re-packaging.
"""
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,
fwd = message_from_bytes(
original_msg.as_bytes(policy=policy.default),
policy=policy.default,
)
if not attachments:
raise ValueError("No matching invoice attachments to forward")
if not isinstance(fwd, EmailMessage):
fwd = EmailMessage(fwd)
subject = clean_subject(original_msg.get("Subject"))
sender = original_msg.get("From", "")
date = original_msg.get("Date", "")
for header in _RESUBMIT_DROP_HEADERS:
while fwd.get(header) is not None:
del fwd[header]
fwd = EmailMessage()
fwd["From"] = from_addr
fwd["To"] = destination_email
fwd["Subject"] = f"FWD BizDocs: {subject}"
subject = clean_subject(fwd.get("Subject"))
if subject and not subject.lower().startswith(("fwd:", "fw:", "re:")):
subject = f"Fwd: {subject}"
body = (
"Forwarded automatically to BizDocs.\n\n"
f"Original From: {sender}\n"
f"Original Date: {date}\n"
f"Original Subject: {subject}\n"
f"Attachments: {', '.join(a.filename for a in attachments)}\n"
)
fwd.set_content(body)
for attachment in attachments:
fwd.add_attachment(
attachment.data,
maintype=attachment.maintype,
subtype=attachment.subtype,
filename=attachment.filename,
)
_set_header(fwd, "From", from_addr)
_set_header(fwd, "To", destination_email)
_set_header(fwd, "Subject", subject)
return fwd
def forward_invoice_attachments(
def forward_original_message(
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(
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
@@ -125,10 +112,6 @@ def forward_invoice_attachments(
pass
# Backwards-compatible alias used by sync_service.
forward_email_as_eml = forward_invoice_attachments
def test_smtp_connection(
config: SmtpConfig,
timeout: float = CONNECTION_TEST_SMTP_TIMEOUT,
+3 -13
View File
@@ -29,11 +29,7 @@ from forwarder.email.parsing import (
get_message_key,
has_matching_attachment,
)
from forwarder.email.smtp_client import (
SmtpConfig,
create_smtp_client,
forward_invoice_attachments,
)
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_original_message
from forwarder.error_reporter import report_error, report_error_with_cooldown
from forwarder.services.account_service import get_account
@@ -260,13 +256,11 @@ def sync_account(
continue
try:
forward_invoice_attachments(
forward_original_message(
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,
@@ -391,16 +385,12 @@ def retry_single_message(db: Session, message_id: int) -> Message:
if msg is None:
raise ValueError(f"Could not fetch message UID {message.uid}")
allowed_extensions = set(account.allowed_extensions or [])
smtp = create_smtp_client(smtp_config)
forward_invoice_attachments(
forward_original_message(
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
+25 -17
View File
@@ -1,4 +1,4 @@
"""SMTP forward sends invoice attachments directly (PDF/XML/ZIP)."""
"""Forward re-sends the original message — no .eml wrapper."""
from __future__ import annotations
@@ -7,12 +7,12 @@ from email.message import EmailMessage
from forwarder.email.smtp_client import build_forward_message
def test_forward_attaches_invoice_files_not_eml_wrapper():
def test_forward_resends_original_with_updated_headers():
original = EmailMessage()
original["From"] = "[email protected]"
original["To"] = "[email protected]"
original["Subject"] = "Fatura 123"
original.set_content("body")
original.set_content("corpo original")
original.add_attachment(
b"%PDF-1.4",
maintype="application",
@@ -26,26 +26,34 @@ def test_forward_attaches_invoice_files_not_eml_wrapper():
destination_email="[email protected]",
)
parts = list(fwd.iter_attachments())
assert len(parts) == 1
part = parts[0]
assert part.get_content_type() == "application/pdf"
assert part.get_filename() == "fatura.pdf"
assert part.get_payload(decode=True) == b"%PDF-1.4"
assert fwd["From"] == "[email protected]"
assert fwd["To"] == "[email protected]"
assert fwd["Subject"] == "Fwd: Fatura 123"
attachments = list(fwd.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()
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)
def test_forward_includes_all_matching_extensions():
def test_forward_does_not_double_prefix_subject():
original = EmailMessage()
original["Subject"] = "Docs"
original.set_content("body")
original.add_attachment(b"<xml/>", maintype="text", subtype="xml", filename="doc.xml")
original.add_attachment(b"PK", maintype="application", subtype="zip", filename="pack.zip")
original["Subject"] = "Fwd: Already forwarded"
original.set_content("x")
fwd = build_forward_message(
original,
from_addr="[email protected]",
destination_email="inbox.arquivodigital@bizdocs.mobi",
destination_email="dest@bizdocs.mobi",
)
names = {p.get_filename() for p in fwd.iter_attachments()}
assert names == {"doc.xml", "pack.zip"}
assert fwd["Subject"] == "Fwd: Already forwarded"