controle_cotisation/main.py: change sendmail to use actual mail system

This commit is contained in:
Adrien Bourmault 2024-09-16 16:12:07 +02:00
parent 652e7b1f20
commit e7442c89aa
Signed by: neox
GPG Key ID: 57BC26A3687116F6
1 changed files with 64 additions and 26 deletions

View File

@ -19,7 +19,13 @@
import os, requests, json, datetime, shutil, quopri, subprocess, base64 import os, requests, json, datetime, shutil, quopri, subprocess, base64
from requests.auth import HTTPBasicAuth from requests.auth import HTTPBasicAuth
from requests.auth import HTTPDigestAuth 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" VERSION="1.0.0"
GESTION_SECRET_FILE="/home/tresorier/.secret/gestion_api_password" GESTION_SECRET_FILE="/home/tresorier/.secret/gestion_api_password"
@ -35,6 +41,12 @@ SENDMAIL_LOCATION = "/usr/sbin/sendmail" # sendmail location
BUF=[] BUF=[]
GITEA_URL = "https://forge.a-lec.org" 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 \ # gestion_read("SELECT * FROM services_users su \
# INNER JOIN membres m ON m.id = su.id_user \ # INNER JOIN membres m ON m.id = su.id_user \
# INNER JOIN services_fees sf ON sf.id = su.id_fee \ # 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: with open(GESTION_SECRET_FILE) as sfile:
return sfile.readline().replace("\n", "") 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(): def git_get_secret():
with open(GIT_SECRET_FILE) as sfile: with open(GIT_SECRET_FILE) as sfile:
return sfile.readline().replace("\n", "") return sfile.readline().replace("\n", "")
@ -84,18 +100,48 @@ def setup_workdir():
if not "transition" in os.listdir(WORKDIR): if not "transition" in os.listdir(WORKDIR):
os.mkdir(WORKDIR+"/transition") os.mkdir(WORKDIR+"/transition")
def sendmail(headers, data): # def sendmail(headers, data):
msg = bytes(headers + "\n", 'utf-8') + quopri.encodestring(bytes(data, 'utf-8')) # msg = bytes(headers + "\n", 'utf-8') + quopri.encodestring(bytes(data, '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_header, attachment, ending): # def sendmail_with_attachment(headers, data, attachment_header, attachment, ending):
msg = bytes(headers + "\n", 'utf-8') \ # msg = bytes(headers + "\n", 'utf-8') \
+ quopri.encodestring(bytes(data, 'utf-8')) \ # + quopri.encodestring(bytes(data, 'utf-8')) \
+ bytes(attachment_header + "\n", 'utf-8') \ # + bytes(attachment_header + "\n", 'utf-8') \
+ base64.b64encode(attachment) \ # + base64.b64encode(attachment) \
+ bytes(ending, 'utf-8') # + 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(): def gestion_get_expired():
request_expired = "SELECT id_user FROM services_users su " +\ request_expired = "SELECT id_user FROM services_users su " +\
@ -396,23 +442,15 @@ def validate(member):
set_file_content(WORKDIR+"/validé/"+filename+".tex", latexfile) set_file_content(WORKDIR+"/validé/"+filename+".tex", latexfile)
os.system("cd {} && pdflatex {}".format(WORKDIR+"/validé/", filename+".tex")) os.system("cd {} && pdflatex {}".format(WORKDIR+"/validé/", filename+".tex"))
# Preparing mail # Preparing the email
mailheaders = get_file_content_all(RECEPT_MAIL_HEADERS).replace("COURRIEL-COTISANT", mailheaders = get_file_content_all(RECEPT_MAIL_HEADERS).replace("COURRIEL-COTISANT", answer["email"]) + "\n"
answer["email"]) + "\n" mailtext = get_file_content_all(RECEPT_MAIL).replace("ANNEE-CIVILE", answer["date"][:4]) + "\n"
mailtext = get_file_content_all(RECEPT_MAIL).replace("ANNEE-CIVILE",
answer["date"][:4]) + "\n"
mailtattach = get_file_content_all(RECEPT_MAIL_ATTACHMENT) + "\n"
# Opening PDF file as binary # Sending the email with the attached PDF
attachment = open(WORKDIR+"/validé/"+filename+".pdf", "rb") pdf_path = WORKDIR+"/validé/"+filename+".pdf"
data = attachment.read() sendmail_with_attachment(mailheaders, mailtext, pdf_path, filename + ".pdf")
attachment.close()
ending = "--------------3yxkFgv0AINs5nd0i6BJrWaV--" # Cleanup
sendmail_with_attachment(mailheaders, mailtext, mailtattach, data, ending)
# The end
os.remove(WORKDIR+"/transition/"+member) os.remove(WORKDIR+"/transition/"+member)
def validate_members(): def validate_members():