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:
1 parent
f664cca6b5
commit
b070af8503
5 files changed
+64
-83
No files matched your search
@@ -1,6 +1,6 @@
|
|||||||
# BizDocs Forwarder
|
# 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
|
- **Repo:** https://git.bitreport.pt/BitReport.pt/forwarder
|
||||||
- **Paperclip:** http://10.10.50.17:3100/BIT/projects/bizdocs-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">
|
<fieldset className="border border-gray-200 rounded-md p-3">
|
||||||
<legend className="text-xs font-semibold text-gray-500 px-1">BizDocs (destino)</legend>
|
<legend className="text-xs font-semibold text-gray-500 px-1">BizDocs (destino)</legend>
|
||||||
<p className="text-xs text-gray-500 mb-2">
|
<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>
|
</p>
|
||||||
{field(
|
{field(
|
||||||
'Email destino',
|
'Email destino',
|
||||||
|
|||||||
@@ -4,18 +4,24 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import smtplib
|
import smtplib
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from email import message_from_bytes, policy
|
||||||
from email.message import EmailMessage
|
from email.message import EmailMessage
|
||||||
|
|
||||||
from forwarder.email.parsing import (
|
from forwarder.email.parsing import clean_subject
|
||||||
DEFAULT_ALLOWED_EXTENSIONS,
|
|
||||||
collect_matching_attachments,
|
|
||||||
clean_subject,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_SMTP_TIMEOUT = 30
|
DEFAULT_SMTP_TIMEOUT = 30
|
||||||
CONNECTION_TEST_SMTP_TIMEOUT = 5
|
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
|
@dataclass
|
||||||
class SmtpConfig:
|
class SmtpConfig:
|
||||||
@@ -40,74 +46,55 @@ def create_smtp_client(
|
|||||||
return 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(
|
def build_forward_message(
|
||||||
original_msg: EmailMessage,
|
original_msg: EmailMessage,
|
||||||
*,
|
*,
|
||||||
from_addr: str,
|
from_addr: str,
|
||||||
destination_email: str,
|
destination_email: str,
|
||||||
include_all_attachments: bool = False,
|
|
||||||
allowed_extensions: set[str] | None = None,
|
|
||||||
) -> EmailMessage:
|
) -> 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
|
Same MIME body and attachments as received — no .eml wrapper, no re-packaging.
|
||||||
is rejected by most outbound SMTP filters.
|
|
||||||
"""
|
"""
|
||||||
if allowed_extensions is None:
|
fwd = message_from_bytes(
|
||||||
allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS
|
original_msg.as_bytes(policy=policy.default),
|
||||||
|
policy=policy.default,
|
||||||
attachments = collect_matching_attachments(
|
|
||||||
original_msg,
|
|
||||||
include_all_attachments=include_all_attachments,
|
|
||||||
allowed_extensions=allowed_extensions,
|
|
||||||
)
|
)
|
||||||
if not attachments:
|
if not isinstance(fwd, EmailMessage):
|
||||||
raise ValueError("No matching invoice attachments to forward")
|
fwd = EmailMessage(fwd)
|
||||||
|
|
||||||
subject = clean_subject(original_msg.get("Subject"))
|
for header in _RESUBMIT_DROP_HEADERS:
|
||||||
sender = original_msg.get("From", "")
|
while fwd.get(header) is not None:
|
||||||
date = original_msg.get("Date", "")
|
del fwd[header]
|
||||||
|
|
||||||
fwd = EmailMessage()
|
subject = clean_subject(fwd.get("Subject"))
|
||||||
fwd["From"] = from_addr
|
if subject and not subject.lower().startswith(("fwd:", "fw:", "re:")):
|
||||||
fwd["To"] = destination_email
|
subject = f"Fwd: {subject}"
|
||||||
fwd["Subject"] = f"FWD BizDocs: {subject}"
|
|
||||||
|
|
||||||
body = (
|
_set_header(fwd, "From", from_addr)
|
||||||
"Forwarded automatically to BizDocs.\n\n"
|
_set_header(fwd, "To", destination_email)
|
||||||
f"Original From: {sender}\n"
|
_set_header(fwd, "Subject", subject)
|
||||||
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,
|
|
||||||
)
|
|
||||||
|
|
||||||
return fwd
|
return fwd
|
||||||
|
|
||||||
|
|
||||||
def forward_invoice_attachments(
|
def forward_original_message(
|
||||||
original_msg: EmailMessage,
|
original_msg: EmailMessage,
|
||||||
*,
|
*,
|
||||||
smtp_config: SmtpConfig,
|
smtp_config: SmtpConfig,
|
||||||
destination_email: str,
|
destination_email: str,
|
||||||
smtp: smtplib.SMTP | None = None,
|
smtp: smtplib.SMTP | None = None,
|
||||||
include_all_attachments: bool = False,
|
|
||||||
allowed_extensions: set[str] | None = None,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
fwd = build_forward_message(
|
fwd = build_forward_message(
|
||||||
original_msg,
|
original_msg,
|
||||||
from_addr=smtp_config.user,
|
from_addr=smtp_config.user,
|
||||||
destination_email=destination_email,
|
destination_email=destination_email,
|
||||||
include_all_attachments=include_all_attachments,
|
|
||||||
allowed_extensions=allowed_extensions,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
owns_client = smtp is None
|
owns_client = smtp is None
|
||||||
@@ -125,10 +112,6 @@ def forward_invoice_attachments(
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
# Backwards-compatible alias used by sync_service.
|
|
||||||
forward_email_as_eml = forward_invoice_attachments
|
|
||||||
|
|
||||||
|
|
||||||
def test_smtp_connection(
|
def test_smtp_connection(
|
||||||
config: SmtpConfig,
|
config: SmtpConfig,
|
||||||
timeout: float = CONNECTION_TEST_SMTP_TIMEOUT,
|
timeout: float = CONNECTION_TEST_SMTP_TIMEOUT,
|
||||||
|
|||||||
@@ -29,11 +29,7 @@ from forwarder.email.parsing import (
|
|||||||
get_message_key,
|
get_message_key,
|
||||||
has_matching_attachment,
|
has_matching_attachment,
|
||||||
)
|
)
|
||||||
from forwarder.email.smtp_client import (
|
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_original_message
|
||||||
SmtpConfig,
|
|
||||||
create_smtp_client,
|
|
||||||
forward_invoice_attachments,
|
|
||||||
)
|
|
||||||
from forwarder.error_reporter import report_error, report_error_with_cooldown
|
from forwarder.error_reporter import report_error, report_error_with_cooldown
|
||||||
from forwarder.services.account_service import get_account
|
from forwarder.services.account_service import get_account
|
||||||
|
|
||||||
@@ -260,13 +256,11 @@ def sync_account(
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
forward_invoice_attachments(
|
forward_original_message(
|
||||||
msg,
|
msg,
|
||||||
smtp_config=smtp_config,
|
smtp_config=smtp_config,
|
||||||
destination_email=account.destination_email,
|
destination_email=account.destination_email,
|
||||||
smtp=smtp,
|
smtp=smtp,
|
||||||
include_all_attachments=account.include_all_attachments,
|
|
||||||
allowed_extensions=allowed_extensions,
|
|
||||||
)
|
)
|
||||||
message_row = _upsert_message(
|
message_row = _upsert_message(
|
||||||
db,
|
db,
|
||||||
@@ -391,16 +385,12 @@ def retry_single_message(db: Session, message_id: int) -> Message:
|
|||||||
if msg is None:
|
if msg is None:
|
||||||
raise ValueError(f"Could not fetch message UID {message.uid}")
|
raise ValueError(f"Could not fetch message UID {message.uid}")
|
||||||
|
|
||||||
allowed_extensions = set(account.allowed_extensions or [])
|
|
||||||
|
|
||||||
smtp = create_smtp_client(smtp_config)
|
smtp = create_smtp_client(smtp_config)
|
||||||
forward_invoice_attachments(
|
forward_original_message(
|
||||||
msg,
|
msg,
|
||||||
smtp_config=smtp_config,
|
smtp_config=smtp_config,
|
||||||
destination_email=account.destination_email,
|
destination_email=account.destination_email,
|
||||||
smtp=smtp,
|
smtp=smtp,
|
||||||
include_all_attachments=account.include_all_attachments,
|
|
||||||
allowed_extensions=allowed_extensions,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
message.status = MessageStatus.forwarded
|
message.status = MessageStatus.forwarded
|
||||||
|
|||||||
+25
-17
@@ -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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -7,12 +7,12 @@ from email.message import EmailMessage
|
|||||||
from forwarder.email.smtp_client import build_forward_message
|
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 = EmailMessage()
|
||||||
original["From"] = "[email protected]"
|
original["From"] = "[email protected]"
|
||||||
original["To"] = "[email protected]"
|
original["To"] = "[email protected]"
|
||||||
original["Subject"] = "Fatura 123"
|
original["Subject"] = "Fatura 123"
|
||||||
original.set_content("body")
|
original.set_content("corpo original")
|
||||||
original.add_attachment(
|
original.add_attachment(
|
||||||
b"%PDF-1.4",
|
b"%PDF-1.4",
|
||||||
maintype="application",
|
maintype="application",
|
||||||
@@ -26,26 +26,34 @@ def test_forward_attaches_invoice_files_not_eml_wrapper():
|
|||||||
destination_email="[email protected]",
|
destination_email="[email protected]",
|
||||||
)
|
)
|
||||||
|
|
||||||
parts = list(fwd.iter_attachments())
|
assert fwd["From"] == "[email protected]"
|
||||||
assert len(parts) == 1
|
assert fwd["To"] == "[email protected]"
|
||||||
part = parts[0]
|
assert fwd["Subject"] == "Fwd: Fatura 123"
|
||||||
assert part.get_content_type() == "application/pdf"
|
|
||||||
assert part.get_filename() == "fatura.pdf"
|
attachments = list(fwd.iter_attachments())
|
||||||
assert part.get_payload(decode=True) == b"%PDF-1.4"
|
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 = EmailMessage()
|
||||||
original["Subject"] = "Docs"
|
original["Subject"] = "Fwd: Already forwarded"
|
||||||
original.set_content("body")
|
original.set_content("x")
|
||||||
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(
|
fwd = build_forward_message(
|
||||||
original,
|
original,
|
||||||
from_addr="[email protected]",
|
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 fwd["Subject"] == "Fwd: Already forwarded"
|
||||||
assert names == {"doc.xml", "pack.zip"}
|
|
||||||
Reference in new issue
Block a user