From f664cca6b58b3a3e39a200be36144578fa0612ff Mon Sep 17 00:00:00 2001 From: 1sonhador <1sonhador@gmail.com> Date: Wed, 1 Jul 2026 09:15:01 +0100 Subject: [PATCH] fix: forward invoice PDF/XML/ZIP attachments instead of .eml wrapper The outbound SMTP relay rejects message/rfc822 attachments named .eml. Send the matched invoice files directly to BizDocs, which aligns with the allowed relay extensions and the product filter rules. --- README.md | 2 +- admin-ui/src/pages/Accounts.tsx | 2 +- src/forwarder/email/parsing.py | 69 ++++++++++++++++++++++++- src/forwarder/email/smtp_client.py | 71 +++++++++++++++++++++----- src/forwarder/services/sync_service.py | 16 ++++-- tests/test_smtp_forward.py | 51 ++++++++++++++++++ 6 files changed, 191 insertions(+), 20 deletions(-) create mode 100644 tests/test_smtp_forward.py diff --git a/README.md b/README.md index 4e7586e..61a2e8a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # BizDocs Forwarder -Multi-account IMAP → BizDocs forwarder: detect invoice attachments (PDF/XML/ZIP), re-send via SMTP as `.eml`. +Multi-account IMAP → BizDocs forwarder: detect invoice attachments (PDF/XML/ZIP), re-send via SMTP. - **Repo:** https://git.bitreport.pt/BitReport.pt/forwarder - **Paperclip:** http://10.10.50.17:3100/BIT/projects/bizdocs-forwarder diff --git a/admin-ui/src/pages/Accounts.tsx b/admin-ui/src/pages/Accounts.tsx index 1e8f695..e3337b1 100644 --- a/admin-ui/src/pages/Accounts.tsx +++ b/admin-ui/src/pages/Accounts.tsx @@ -131,7 +131,7 @@ function AccountModal({
BizDocs (destino)

- Email para onde as facturas são reencaminhadas via SMTP (.eml). + Email para onde as facturas são reencaminhadas via SMTP (anexos PDF/XML/ZIP).

{field( 'Email destino', diff --git a/src/forwarder/email/parsing.py b/src/forwarder/email/parsing.py index 13a34f2..1a4131b 100644 --- a/src/forwarder/email/parsing.py +++ b/src/forwarder/email/parsing.py @@ -3,6 +3,8 @@ from __future__ import annotations import email +import os +from dataclasses import dataclass from email.header import decode_header, make_header from email.message import EmailMessage @@ -96,8 +98,6 @@ def attachment_allowed( filename = part_filename(part) if filename: - import os - _, ext = os.path.splitext(filename) if ext in allowed_extensions: return True @@ -106,6 +106,71 @@ def attachment_allowed( return content_type in ALLOWED_MIME_TYPES +@dataclass(frozen=True) +class InvoiceAttachment: + filename: str + data: bytes + maintype: str + subtype: str + + +def _split_content_type(content_type: str) -> tuple[str, str]: + maintype, _, subtype = content_type.partition("/") + if not subtype: + return "application", "octet-stream" + return maintype, subtype + + +def collect_matching_attachments( + msg: EmailMessage, + *, + include_all_attachments: bool = False, + allowed_extensions: set[str] | None = None, +) -> list[InvoiceAttachment]: + """Extract invoice attachments (PDF/XML/ZIP) from a message for SMTP relay.""" + if allowed_extensions is None: + allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS + + collected: list[InvoiceAttachment] = [] + seen_names: set[str] = set() + + for part in msg.walk(): + if part.is_multipart(): + continue + if not attachment_allowed( + part, + include_all_attachments=include_all_attachments, + allowed_extensions=allowed_extensions, + ): + continue + + payload = part.get_payload(decode=True) + if not payload: + continue + + filename = part_filename(part) or part.get_filename() or "" + filename = clean_header(filename) or "attachment" + if filename in seen_names: + base, ext = os.path.splitext(filename) + counter = 2 + while f"{base}-{counter}{ext}" in seen_names: + counter += 1 + filename = f"{base}-{counter}{ext}" + + seen_names.add(filename) + maintype, subtype = _split_content_type(part.get_content_type()) + collected.append( + InvoiceAttachment( + filename=filename, + data=payload, + maintype=maintype, + subtype=subtype, + ) + ) + + return collected + + def has_matching_attachment( msg: EmailMessage, *, diff --git a/src/forwarder/email/smtp_client.py b/src/forwarder/email/smtp_client.py index 19352bc..6a4b688 100644 --- a/src/forwarder/email/smtp_client.py +++ b/src/forwarder/email/smtp_client.py @@ -4,9 +4,14 @@ from __future__ import annotations import smtplib from dataclasses import dataclass -from email import policy from email.message import EmailMessage +from forwarder.email.parsing import ( + DEFAULT_ALLOWED_EXTENSIONS, + collect_matching_attachments, + clean_subject, +) + DEFAULT_SMTP_TIMEOUT = 30 CONNECTION_TEST_SMTP_TIMEOUT = 5 @@ -35,21 +40,36 @@ def create_smtp_client( return client -def forward_email_as_eml( +def build_forward_message( original_msg: EmailMessage, *, - smtp_config: SmtpConfig, + from_addr: str, destination_email: str, - smtp: smtplib.SMTP | None = None, -) -> None: - from forwarder.email.parsing import clean_subject + include_all_attachments: bool = False, + allowed_extensions: set[str] | None = None, +) -> EmailMessage: + """Build outbound message with invoice files attached (PDF/XML/ZIP). + + Relays typically allow these extensions; wrapping the whole email as .eml + is rejected by most outbound SMTP filters. + """ + 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 attachments: + raise ValueError("No matching invoice attachments to forward") subject = clean_subject(original_msg.get("Subject")) sender = original_msg.get("From", "") date = original_msg.get("Date", "") fwd = EmailMessage() - fwd["From"] = smtp_config.user + fwd["From"] = from_addr fwd["To"] = destination_email fwd["Subject"] = f"FWD BizDocs: {subject}" @@ -58,15 +78,36 @@ def forward_email_as_eml( 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) - raw_bytes = original_msg.as_bytes(policy=policy.default) - fwd.add_attachment( - raw_bytes, - maintype="message", - subtype="rfc822", - filename="original-email.eml", + for attachment in attachments: + fwd.add_attachment( + attachment.data, + maintype=attachment.maintype, + subtype=attachment.subtype, + filename=attachment.filename, + ) + + return fwd + + +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( + 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 @@ -84,6 +125,10 @@ def forward_email_as_eml( 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, diff --git a/src/forwarder/services/sync_service.py b/src/forwarder/services/sync_service.py index c928581..d96fdf3 100644 --- a/src/forwarder/services/sync_service.py +++ b/src/forwarder/services/sync_service.py @@ -29,7 +29,11 @@ from forwarder.email.parsing import ( get_message_key, has_matching_attachment, ) -from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_email_as_eml +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 +260,13 @@ def sync_account( continue try: - forward_email_as_eml( + 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, @@ -385,12 +391,16 @@ 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_email_as_eml( + 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 diff --git a/tests/test_smtp_forward.py b/tests/test_smtp_forward.py new file mode 100644 index 0000000..9f6fc4b --- /dev/null +++ b/tests/test_smtp_forward.py @@ -0,0 +1,51 @@ +"""SMTP forward sends invoice attachments directly (PDF/XML/ZIP).""" + +from __future__ import annotations + +from email.message import EmailMessage + +from forwarder.email.smtp_client import build_forward_message + + +def test_forward_attaches_invoice_files_not_eml_wrapper(): + original = EmailMessage() + original["From"] = "vendor@example.com" + original["To"] = "inbox@company.pt" + original["Subject"] = "Fatura 123" + original.set_content("body") + original.add_attachment( + b"%PDF-1.4", + maintype="application", + subtype="pdf", + filename="fatura.pdf", + ) + + fwd = build_forward_message( + original, + from_addr="relay@company.pt", + destination_email="inbox.arquivodigital@bizdocs.mobi", + ) + + 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" + + +def test_forward_includes_all_matching_extensions(): + original = EmailMessage() + original["Subject"] = "Docs" + original.set_content("body") + original.add_attachment(b"", maintype="text", subtype="xml", filename="doc.xml") + original.add_attachment(b"PK", maintype="application", subtype="zip", filename="pack.zip") + + fwd = build_forward_message( + original, + from_addr="a@b.pt", + destination_email="inbox.arquivodigital@bizdocs.mobi", + ) + + names = {p.get_filename() for p in fwd.iter_attachments()} + assert names == {"doc.xml", "pack.zip"}