fix sendmail

This commit is contained in:
Adrien Bourmault 2024-09-16 17:15:25 +02:00
parent babd3d1688
commit e1b20eca87
Signed by: neox
GPG Key ID: 57BC26A3687116F6
2 changed files with 12 additions and 9 deletions

View File

@ -114,21 +114,23 @@ def setup_workdir():
# subprocess.run([SENDMAIL_LOCATION, "-t", "-oi"], input=msg) # subprocess.run([SENDMAIL_LOCATION, "-t", "-oi"], input=msg)
def sendmail_with_attachment(headers, data, attachment_path, filename): def sendmail_with_attachment(headers, data, attachment_path=None, filename=None):
# Parse headers # Parse headers
msg = MIMEMultipart() msg = MIMEMultipart()
for header in headers.split("\n"): for header in headers.split("\n"):
if ": " in header: if ": " in header:
key, value = header.split(": ", 1) key, value = header.split(": ", 1)
msg[key] = value msg[key] = value.strip()
# Add the email body # Add the email body
body = MIMEText(data, 'plain', 'utf-8') body = MIMEText(data, 'plain', 'utf-8')
msg.attach(body) msg.attach(body)
# Add the attachment # Add the attachment only if attachment_path is provided
if attachment_path and filename:
attachment = MIMEBase('application', 'octet-stream') attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(Path(attachment_path).read_bytes()) with open(attachment_path, "rb") as attach_file:
attachment.set_payload(attach_file.read())
encoders.encode_base64(attachment) encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', f'attachment; filename={filename}') attachment.add_header('Content-Disposition', f'attachment; filename={filename}')
msg.attach(attachment) msg.attach(attachment)
@ -143,6 +145,7 @@ def sendmail_with_attachment(headers, data, attachment_path, filename):
except Exception as e: except Exception as e:
print(f"Failed to send email: {e}") print(f"Failed to send email: {e}")
def gestion_get_expired(): def gestion_get_expired():
request_expired = "SELECT id_user FROM services_users su " +\ request_expired = "SELECT id_user FROM services_users su " +\
"INNER JOIN users m ON m.id = su.id_user " +\ "INNER JOIN users m ON m.id = su.id_user " +\

View File

@ -105,7 +105,7 @@ def sendmail_with_attachment(headers, body, attachment_path, attachment_filename
server.starttls() # Secure the connection server.starttls() # Secure the connection
server.login(SMTP_USER, smtp_get_secret()) # Fetch SMTP password from file server.login(SMTP_USER, smtp_get_secret()) # Fetch SMTP password from file
server.sendmail(SMTP_USER, msg['To'], msg.as_string()) server.sendmail(SMTP_USER, msg['To'], msg.as_string())
#print(f"Email sent to {msg['To']}") print(f"Email sent to {msg['To']}")
except Exception as e: except Exception as e:
print(f"Error sending email: {e}") print(f"Error sending email: {e}")