From e7442c89aaeb162127f1b10db7f6787db056c5b5 Mon Sep 17 00:00:00 2001 From: "Adrien Bourmault (neox)" Date: Mon, 16 Sep 2024 16:12:07 +0200 Subject: [PATCH] controle_cotisation/main.py: change sendmail to use actual mail system --- controle_cotisation/main.py | 90 ++++++++++++++++++++++++++----------- 1 file changed, 64 insertions(+), 26 deletions(-) diff --git a/controle_cotisation/main.py b/controle_cotisation/main.py index e04a3d7..6d016c1 100755 --- a/controle_cotisation/main.py +++ b/controle_cotisation/main.py @@ -19,7 +19,13 @@ import os, requests, json, datetime, shutil, quopri, subprocess, base64 from requests.auth import HTTPBasicAuth from requests.auth import HTTPDigestAuth - +import smtplib +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.mime.base import MIMEBase +from email import encoders +from email.utils import formataddr +from pathlib import Path VERSION="1.0.0" GESTION_SECRET_FILE="/home/tresorier/.secret/gestion_api_password" @@ -35,6 +41,12 @@ SENDMAIL_LOCATION = "/usr/sbin/sendmail" # sendmail location BUF=[] GITEA_URL = "https://forge.a-lec.org" +# Update these with your SMTP server details +SMTP_SERVER = 'mail.a-lec.org' +SMTP_PORT = 587 +SMTP_USER = 'tresorier@a-lec.org' +SMTP_SECRET_FILE = "/home/tresorier/.secret/smtp_api_password" + # gestion_read("SELECT * FROM services_users su \ # INNER JOIN membres m ON m.id = su.id_user \ # INNER JOIN services_fees sf ON sf.id = su.id_fee \ @@ -46,6 +58,10 @@ def gestion_get_secret(): with open(GESTION_SECRET_FILE) as sfile: return sfile.readline().replace("\n", "") +def smtp_get_secret(): + with open(SMTP_SECRET_FILE) as sfile: + return sfile.readline().replace("\n", "") + def git_get_secret(): with open(GIT_SECRET_FILE) as sfile: return sfile.readline().replace("\n", "") @@ -84,18 +100,48 @@ def setup_workdir(): if not "transition" in os.listdir(WORKDIR): os.mkdir(WORKDIR+"/transition") -def sendmail(headers, data): - msg = bytes(headers + "\n", 'utf-8') + quopri.encodestring(bytes(data, 'utf-8')) - subprocess.run([SENDMAIL_LOCATION, "-t", "-oi"], input=msg) +# def sendmail(headers, data): +# msg = bytes(headers + "\n", 'utf-8') + quopri.encodestring(bytes(data, 'utf-8')) +# subprocess.run([SENDMAIL_LOCATION, "-t", "-oi"], input=msg) -def sendmail_with_attachment(headers, data, attachment_header, attachment, ending): - msg = bytes(headers + "\n", 'utf-8') \ - + quopri.encodestring(bytes(data, 'utf-8')) \ - + bytes(attachment_header + "\n", 'utf-8') \ - + base64.b64encode(attachment) \ - + bytes(ending, 'utf-8') +# def sendmail_with_attachment(headers, data, attachment_header, attachment, ending): +# msg = bytes(headers + "\n", 'utf-8') \ +# + quopri.encodestring(bytes(data, 'utf-8')) \ +# + bytes(attachment_header + "\n", 'utf-8') \ +# + base64.b64encode(attachment) \ +# + bytes(ending, 'utf-8') - 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): + # Parse headers + msg = MIMEMultipart() + for header in headers.split("\n"): + if ": " in header: + key, value = header.split(": ", 1) + msg[key] = value + + # 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) + + # Send the email + try: + with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server: + server.starttls() # Start TLS encryption + server.login(SMTP_USER, smtp_get_secret()) + server.sendmail(SMTP_USER, msg['To'], msg.as_string()) + print("Email sent successfully") + except Exception as e: + print(f"Failed to send email: {e}") def gestion_get_expired(): request_expired = "SELECT id_user FROM services_users su " +\ @@ -396,23 +442,15 @@ def validate(member): set_file_content(WORKDIR+"/validé/"+filename+".tex", latexfile) os.system("cd {} && pdflatex {}".format(WORKDIR+"/validé/", filename+".tex")) - # Preparing mail - mailheaders = get_file_content_all(RECEPT_MAIL_HEADERS).replace("COURRIEL-COTISANT", - answer["email"]) + "\n" - mailtext = get_file_content_all(RECEPT_MAIL).replace("ANNEE-CIVILE", - answer["date"][:4]) + "\n" - mailtattach = get_file_content_all(RECEPT_MAIL_ATTACHMENT) + "\n" + # Preparing the email + mailheaders = get_file_content_all(RECEPT_MAIL_HEADERS).replace("COURRIEL-COTISANT", answer["email"]) + "\n" + mailtext = get_file_content_all(RECEPT_MAIL).replace("ANNEE-CIVILE", answer["date"][:4]) + "\n" - # Opening PDF file as binary - attachment = open(WORKDIR+"/validé/"+filename+".pdf", "rb") - data = attachment.read() - attachment.close() + # Sending the email with the attached PDF + pdf_path = WORKDIR+"/validé/"+filename+".pdf" + sendmail_with_attachment(mailheaders, mailtext, pdf_path, filename + ".pdf") - ending = "--------------3yxkFgv0AINs5nd0i6BJrWaV--" - - sendmail_with_attachment(mailheaders, mailtext, mailtattach, data, ending) - - # The end + # Cleanup os.remove(WORKDIR+"/transition/"+member) def validate_members():