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.
This commit is contained in:
1 parent
87b1ad4b8a
commit
f664cca6b5
6 files changed
+191
-20
No files matched your search
@@ -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
|
||||
|
||||
@@ -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 (.eml).
|
||||
Email para onde as facturas são reencaminhadas via SMTP (anexos PDF/XML/ZIP).
|
||||
</p>
|
||||
{field(
|
||||
'Email destino',
|
||||
|
||||
@@ -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,
|
||||
*,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"] = "[email protected]"
|
||||
original["To"] = "[email protected]"
|
||||
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="[email protected]",
|
||||
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"
|
||||
|
||||
|
||||
def test_forward_includes_all_matching_extensions():
|
||||
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")
|
||||
|
||||
fwd = build_forward_message(
|
||||
original,
|
||||
from_addr="[email protected]",
|
||||
destination_email="[email protected]",
|
||||
)
|
||||
|
||||
names = {p.get_filename() for p in fwd.iter_attachments()}
|
||||
assert names == {"doc.xml", "pack.zip"}
|
||||
Reference in new issue
Block a user