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
This commit is contained in:
+25
-17
@@ -223,27 +223,27 @@ def send_email(
|
|||||||
|
|
||||||
subject = subject.strip()
|
subject = subject.strip()
|
||||||
|
|
||||||
# Build message
|
has_attachments = bool(attachments)
|
||||||
msg = MIMEMultipart("alternative")
|
|
||||||
msg["From"] = cfg["from_address"]
|
|
||||||
msg["To"] = ", ".join(to_list)
|
|
||||||
if cc_list:
|
|
||||||
msg["Cc"] = ", ".join(cc_list)
|
|
||||||
msg["Subject"] = subject
|
|
||||||
|
|
||||||
# Attach plain text
|
# Build the text/HTML part (alternative)
|
||||||
msg.attach(MIMEText(body, "plain"))
|
alt = MIMEMultipart("alternative")
|
||||||
|
alt.attach(MIMEText(body, "plain"))
|
||||||
# Attach HTML if provided
|
|
||||||
if html:
|
if html:
|
||||||
msg.attach(MIMEText(html, "html"))
|
alt.attach(MIMEText(html, "html"))
|
||||||
|
|
||||||
# Attach files in a separate multipart/mixed part
|
if has_attachments:
|
||||||
if attachments:
|
# Outer message: multipart/mixed with headers
|
||||||
mixed = MIMEMultipart("mixed")
|
msg = MIMEMultipart("mixed")
|
||||||
mixed.attach(msg)
|
msg["From"] = cfg["from_address"]
|
||||||
msg = mixed
|
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:
|
for file_path in attachments:
|
||||||
if not os.path.isfile(file_path):
|
if not os.path.isfile(file_path):
|
||||||
logger.warning("Attachment file not found, skipping: %s", file_path)
|
logger.warning("Attachment file not found, skipping: %s", file_path)
|
||||||
@@ -262,6 +262,14 @@ def send_email(
|
|||||||
msg.attach(part)
|
msg.attach(part)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Failed to attach file %s: %s", file_path, 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
|
# Connect and send
|
||||||
try:
|
try:
|
||||||
|
|||||||
Reference in New Issue
Block a user