From e1b20eca87b8c020328ea8db982bd5d89fb8fc7b Mon Sep 17 00:00:00 2001 From: "Adrien Bourmault (neox)" Date: Mon, 16 Sep 2024 17:15:25 +0200 Subject: [PATCH] fix sendmail --- controle_cotisation/main.py | 19 +++++++++++-------- controle_don/main.py | 2 +- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/controle_cotisation/main.py b/controle_cotisation/main.py index 9a865d6..c7fb007 100755 --- a/controle_cotisation/main.py +++ b/controle_cotisation/main.py @@ -114,24 +114,26 @@ def setup_workdir(): # 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 msg = MIMEMultipart() for header in headers.split("\n"): if ": " in header: key, value = header.split(": ", 1) - msg[key] = value + msg[key] = value.strip() # Add the email body body = MIMEText(data, 'plain', 'utf-8') msg.attach(body) - # Add the attachment - attachment = MIMEBase('application', 'octet-stream') - attachment.set_payload(Path(attachment_path).read_bytes()) - encoders.encode_base64(attachment) - attachment.add_header('Content-Disposition', f'attachment; filename={filename}') - msg.attach(attachment) + # Add the attachment only if attachment_path is provided + if attachment_path and filename: + attachment = MIMEBase('application', 'octet-stream') + with open(attachment_path, "rb") as attach_file: + attachment.set_payload(attach_file.read()) + encoders.encode_base64(attachment) + attachment.add_header('Content-Disposition', f'attachment; filename={filename}') + msg.attach(attachment) # Send the email try: @@ -143,6 +145,7 @@ def sendmail_with_attachment(headers, data, attachment_path, filename): except Exception as e: print(f"Failed to send email: {e}") + def gestion_get_expired(): request_expired = "SELECT id_user FROM services_users su " +\ "INNER JOIN users m ON m.id = su.id_user " +\ diff --git a/controle_don/main.py b/controle_don/main.py index caa56ff..d18d875 100755 --- a/controle_don/main.py +++ b/controle_don/main.py @@ -105,7 +105,7 @@ def sendmail_with_attachment(headers, body, attachment_path, attachment_filename server.starttls() # Secure the connection server.login(SMTP_USER, smtp_get_secret()) # Fetch SMTP password from file 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: print(f"Error sending email: {e}")