mirror of
https://git.v0id.ovh/n3wt-innov/n3wt-school.git
synced 2026-01-28 23:43:22 +00:00
feat: Messagerie WIP [#17]
This commit is contained in:
@ -0,0 +1,8 @@
|
||||
{
|
||||
"hostSMTP": "",
|
||||
"portSMTP": 25,
|
||||
"username": "",
|
||||
"password": "",
|
||||
"useSSL": false,
|
||||
"useTLS": false
|
||||
}
|
||||
139
Back-End/N3wtSchool/mailManager.py
Normal file
139
Back-End/N3wtSchool/mailManager.py
Normal file
@ -0,0 +1,139 @@
|
||||
from django.core.mail import send_mail, get_connection, EmailMultiAlternatives, EmailMessage
|
||||
from django.template.loader import render_to_string
|
||||
from django.utils.html import strip_tags
|
||||
from django.conf import settings
|
||||
import re
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import status
|
||||
from rest_framework.exceptions import NotFound
|
||||
from Settings.models import SMTPSettings
|
||||
from Establishment.models import Establishment # Importer le modèle Establishment
|
||||
|
||||
def getConnection(id_establishement):
|
||||
try:
|
||||
# Récupérer l'instance de l'établissement
|
||||
establishment = Establishment.objects.get(id=id_establishement)
|
||||
|
||||
# Récupérer les paramètres SMTP associés à l'établissement
|
||||
smtp_settings = SMTPSettings.objects.get(establishment=establishment)
|
||||
|
||||
# Créer une connexion SMTP avec les paramètres récupérés
|
||||
connection = get_connection(
|
||||
host=smtp_settings.smtp_server,
|
||||
port=smtp_settings.smtp_port,
|
||||
username=smtp_settings.smtp_user,
|
||||
password=smtp_settings.smtp_password,
|
||||
use_tls=smtp_settings.use_tls,
|
||||
use_ssl=smtp_settings.use_ssl
|
||||
)
|
||||
return connection
|
||||
|
||||
except Establishment.DoesNotExist:
|
||||
raise NotFound(f"Aucun établissement trouvé avec l'ID {id_establishement}")
|
||||
except SMTPSettings.DoesNotExist:
|
||||
raise NotFound(f"Aucun paramètre SMTP trouvé pour l'établissement {id_establishement}")
|
||||
|
||||
|
||||
def sendMail(recipients, subject, message, connection=None):
|
||||
try:
|
||||
plain_message = strip_tags(message)
|
||||
from_email = settings.EMAIL_HOST_USER
|
||||
if connection is None:
|
||||
send_mail(subject, plain_message, from_email, recipients, html_message=message, fail_silently=False)
|
||||
else:
|
||||
send_mail(subject, plain_message, from_email, recipients, html_message=message, connection=connection, fail_silently=False)
|
||||
return Response({'message': 'Email envoyé avec succès.'}, status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
def envoieReinitMotDePasse(recipients, code):
|
||||
errorMessage = ''
|
||||
try:
|
||||
EMAIL_REINIT_SUBJECT = 'Réinitialisation du mot de passe'
|
||||
context = {
|
||||
'BASE_URL': settings.BASE_URL,
|
||||
'code': str(code)
|
||||
}
|
||||
subject = EMAIL_REINIT_SUBJECT
|
||||
html_message = render_to_string('emails/resetPassword.html', context)
|
||||
sendMail(recipients, subject, html_message)
|
||||
|
||||
except Exception as e:
|
||||
errorMessage = str(e)
|
||||
|
||||
return errorMessage
|
||||
|
||||
|
||||
def sendRegisterForm(recipients, establishment_id):
|
||||
errorMessage = ''
|
||||
try:
|
||||
# Préparation du contexte pour le template
|
||||
EMAIL_INSCRIPTION_SUBJECT = '[N3WT-SCHOOL] Dossier Inscription'
|
||||
context = {
|
||||
'BASE_URL': settings.BASE_URL,
|
||||
'email': recipients,
|
||||
'establishment': establishment_id
|
||||
}
|
||||
|
||||
subject = EMAIL_INSCRIPTION_SUBJECT
|
||||
html_message = render_to_string('emails/inscription.html', context)
|
||||
sendMail(recipients, subject, html_message)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
errorMessage = str(e)
|
||||
|
||||
return errorMessage
|
||||
|
||||
def sendMandatSEPA(recipients, establishment_id):
|
||||
errorMessage = ''
|
||||
try:
|
||||
# Préparation du contexte pour le template
|
||||
EMAIL_INSCRIPTION_SUBJECT = '[N3WT-SCHOOL] Mandat de prélèvement SEPA'
|
||||
context = {
|
||||
'BASE_URL': settings.BASE_URL,
|
||||
'email': recipients,
|
||||
'establishment': establishment_id
|
||||
}
|
||||
|
||||
subject = EMAIL_INSCRIPTION_SUBJECT
|
||||
html_message = render_to_string('emails/sepa.html', context)
|
||||
sendMail(recipients, subject, html_message)
|
||||
|
||||
except Exception as e:
|
||||
errorMessage = str(e)
|
||||
|
||||
return errorMessage
|
||||
|
||||
def envoieRelanceDossierInscription(recipients, code):
|
||||
EMAIL_RELANCE_SUBJECT = '[N3WT-SCHOOL] Relance - Dossier Inscription'
|
||||
EMAIL_RELANCE_CORPUS = 'Bonjour,\nN\'ayant pas eu de retour de votre part, nous vous renvoyons le lien vers le formulaire d\'inscription : ' + BASE_URL + '/users/login\nCordialement'
|
||||
errorMessage = ''
|
||||
try:
|
||||
sendMail(recipients, EMAIL_RELANCE_SUBJECT, EMAIL_RELANCE_CORPUS%str(code))
|
||||
|
||||
except Exception as e:
|
||||
errorMessage = str(e)
|
||||
|
||||
return errorMessage
|
||||
|
||||
def isValid(message, fiche_inscription):
|
||||
# Est-ce que la référence du dossier est VALIDATED
|
||||
subject = message.subject
|
||||
print ("++++ " + subject)
|
||||
responsableMail = message.from_header
|
||||
result = re.search('<(.*)>', responsableMail)
|
||||
|
||||
if result:
|
||||
responsableMail = result.group(1)
|
||||
|
||||
result = re.search(r'.*\[Ref(.*)\].*', subject)
|
||||
idMail = -1
|
||||
if result:
|
||||
idMail = result.group(1).strip()
|
||||
|
||||
eleve = fiche_inscription.eleve
|
||||
responsable = eleve.getMainGuardian()
|
||||
mailReponsableAVerifier = responsable.mail
|
||||
|
||||
return responsableMail == mailReponsableAVerifier and str(idMail) == str(fiche_inscription.eleve.id)
|
||||
@ -14,6 +14,10 @@ from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
# Configuration du logger
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
@ -219,23 +223,29 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
#################### Application Settings ##############################
|
||||
########################################################################
|
||||
|
||||
with open('Subscriptions/Configuration/application.json', 'r') as f:
|
||||
jsonObject = json.load(f)
|
||||
|
||||
|
||||
DJANGO_SUPERUSER_PASSWORD='admin'
|
||||
DJANGO_SUPERUSER_USERNAME='admin'
|
||||
DJANGO_SUPERUSER_EMAIL='admin@n3wtschool.com'
|
||||
# Configuration de l'email de l'application
|
||||
smtp_config_file = 'N3wtSchool/Configuration/application.json'
|
||||
|
||||
EMAIL_HOST='smtp.gmail.com'
|
||||
EMAIL_PORT=587
|
||||
EMAIL_HOST_USER=jsonObject['mailFrom']
|
||||
EMAIL_HOST_PASSWORD=jsonObject['password']
|
||||
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
|
||||
EMAIL_USE_TLS = True
|
||||
EMAIL_USE_SSL = False
|
||||
|
||||
|
||||
|
||||
if os.path.exists(smtp_config_file):
|
||||
try:
|
||||
with open(smtp_config_file, 'r') as f:
|
||||
smtpSettings = json.load(f)
|
||||
EMAIL_HOST = smtpSettings.get('hostSMTP', '')
|
||||
EMAIL_PORT = smtpSettings.get('portSMTP', 587)
|
||||
EMAIL_HOST_USER = smtpSettings.get('username', '')
|
||||
EMAIL_HOST_PASSWORD = smtpSettings.get('password', '')
|
||||
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
|
||||
EMAIL_USE_TLS = smtpSettings.get('useTLS', True)
|
||||
EMAIL_USE_SSL = smtpSettings.get('useSSL', False)
|
||||
except Exception as e:
|
||||
logger.error(f"Erreur lors de la lecture du fichier de configuration SMTP : {e}")
|
||||
else:
|
||||
logger.error(f"Fichier de configuration SMTP introuvable : {smtp_config_file}")
|
||||
|
||||
DOCUMENT_DIR = 'documents'
|
||||
|
||||
|
||||
Reference in New Issue
Block a user