diff --git a/README.md b/README.md index 61a2e8a..e992f41 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. +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 diff --git a/admin-ui/src/pages/Accounts.tsx b/admin-ui/src/pages/Accounts.tsx index e3337b1..967f7a8 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 (anexos PDF/XML/ZIP). + Email para onde os emails reencaminhados são enviados (forward normal SMTP).

{field( 'Email destino', diff --git a/src/forwarder/email/smtp_client.py b/src/forwarder/email/smtp_client.py index 6a4b688..b41a9c6 100644 --- a/src/forwarder/email/smtp_client.py +++ b/src/forwarder/email/smtp_client.py @@ -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, diff --git a/src/forwarder/services/sync_service.py b/src/forwarder/services/sync_service.py index d96fdf3..3717920 100644 --- a/src/forwarder/services/sync_service.py +++ b/src/forwarder/services/sync_service.py @@ -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 diff --git a/tests/test_smtp_forward.py b/tests/test_smtp_forward.py index 9f6fc4b..1302ced 100644 --- a/tests/test_smtp_forward.py +++ b/tests/test_smtp_forward.py @@ -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"] = "vendor@example.com" original["To"] = "inbox@company.pt" 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="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" + assert fwd["From"] == "relay@company.pt" + assert fwd["To"] == "inbox.arquivodigital@bizdocs.mobi" + 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"", 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="a@b.pt", - 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"