From 5dd56a3368cac3d90a398d105cabfa6d3ed5e13a Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 15 Jun 2026 15:03:50 +0000 Subject: [PATCH] Fix missing subject on emails with attachments - Ensure Subject header is set on the outermost MIME part when attachments are present - Restructure send_email to use multipart/mixed as root with headers when attachments exist --- scraibe/email_sender.py | 42 ++++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/scraibe/email_sender.py b/scraibe/email_sender.py index f0cf3db..975452b 100644 --- a/scraibe/email_sender.py +++ b/scraibe/email_sender.py @@ -223,27 +223,27 @@ def send_email( subject = subject.strip() - # Build message - msg = MIMEMultipart("alternative") - msg["From"] = cfg["from_address"] - msg["To"] = ", ".join(to_list) - if cc_list: - msg["Cc"] = ", ".join(cc_list) - msg["Subject"] = subject + has_attachments = bool(attachments) - # Attach plain text - msg.attach(MIMEText(body, "plain")) - - # Attach HTML if provided + # Build the text/HTML part (alternative) + alt = MIMEMultipart("alternative") + alt.attach(MIMEText(body, "plain")) if html: - msg.attach(MIMEText(html, "html")) + alt.attach(MIMEText(html, "html")) - # Attach files in a separate multipart/mixed part - if attachments: - mixed = MIMEMultipart("mixed") - mixed.attach(msg) - msg = mixed + if has_attachments: + # Outer message: multipart/mixed with headers + msg = MIMEMultipart("mixed") + msg["From"] = cfg["from_address"] + msg["To"] = ", ".join(to_list) + if cc_list: + msg["Cc"] = ", ".join(cc_list) + msg["Subject"] = subject + # Attach the alternative (text/HTML) part + msg.attach(alt) + + # Attach files for file_path in attachments: if not os.path.isfile(file_path): logger.warning("Attachment file not found, skipping: %s", file_path) @@ -262,6 +262,14 @@ def send_email( msg.attach(part) except Exception as e: logger.warning("Failed to attach file %s: %s", file_path, e) + else: + # No attachments: use the alternative part as the root message + msg = alt + msg["From"] = cfg["from_address"] + msg["To"] = ", ".join(to_list) + if cc_list: + msg["Cc"] = ", ".join(cc_list) + msg["Subject"] = subject # Connect and send try: