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:
+22
-14
@@ -223,27 +223,27 @@ def send_email(
|
||||
|
||||
subject = subject.strip()
|
||||
|
||||
# Build message
|
||||
msg = MIMEMultipart("alternative")
|
||||
has_attachments = bool(attachments)
|
||||
|
||||
# Build the text/HTML part (alternative)
|
||||
alt = MIMEMultipart("alternative")
|
||||
alt.attach(MIMEText(body, "plain"))
|
||||
if html:
|
||||
alt.attach(MIMEText(html, "html"))
|
||||
|
||||
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 plain text
|
||||
msg.attach(MIMEText(body, "plain"))
|
||||
|
||||
# Attach HTML if provided
|
||||
if html:
|
||||
msg.attach(MIMEText(html, "html"))
|
||||
|
||||
# Attach files in a separate multipart/mixed part
|
||||
if attachments:
|
||||
mixed = MIMEMultipart("mixed")
|
||||
mixed.attach(msg)
|
||||
msg = mixed
|
||||
# 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:
|
||||
|
||||
Reference in New Issue
Block a user