from __future__ import print_function import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import locale import datetime import inspect import sys, os from email import encoders from bson import ObjectId from pymongo import ReturnDocument from xhtml2pdf import pisa import prj_common as mycommon import GlobalVariable as MYSY_GV from dateutil import tz import pytz import sib_api_v3_sdk from sib_api_v3_sdk.rest import ApiException import jinja2 from email.message import EmailMessage from email.mime.text import MIMEText from email import encoders configuration = sib_api_v3_sdk.Configuration() configuration.api_key['api-key'] = MYSY_GV.SENDINBLUE_API_KEY_SUPPORT api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration)) locale.setlocale(category=locale.LC_ALL, locale='fr_FR.utf8') smtp_address = 'smtp-relay.sendinblue.com' port = 587 sender = 'support@mysy-training.com' receiver = ["cbalde3@mysy-training.com","billardman1@gmail.com"] user = 'support@mysy-training.com' password = 'Tut29488!+' """ Envoi de l'email de confirmation d'inscription à une formation """ def incription_training_confirmation_mail(diction): try: print(" ### incription_training_confirmation_mail = "+str(diction)) """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'title'] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer l'email de confirmation de l'inscritpion" tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print("debut envoi mail de test ") """ Verification si c'est une formation en ligne. auquel cas, l'adresse est du type : enligne""" adresse = "" if ("adresse" in diction.keys()): if diction['adresse']: adresse = diction['adresse'] adresse_session = adresse session_ondemande = "" if ("session_ondemande" in diction.keys()): if diction['session_ondemande']: session_ondemande = diction['session_ondemande'] """ send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=1, params={ "nom": str(diction['nom']), "prenom":str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "adresse": str(diction['adresse']), "title":str(diction['title'])}, to=to, bcc=bcc ) """ print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur # msg = MIMEMultipart("alternative") msg = EmailMessage() local_code_postal = "" if ("code_postal" in diction.keys()): if diction['code_postal']: local_code_postal = diction['code_postal'] local_ville = "" if ("ville" in diction.keys()): if diction['ville']: local_ville = diction['ville'] local_distantiel = "" if ("distantiel" in diction.keys()): if diction['distantiel']: local_distantiel = diction['distantiel'] local_presentiel = "" if ("presentiel" in diction.keys()): if diction['presentiel']: local_presentiel = diction['presentiel'] local_formateur = "" if ("formateur" in diction.keys()): if diction['formateur']: local_formateur = diction['formateur'] prenom = "" if ("prenom" in diction.keys()): if diction['prenom']: prenom = diction['prenom'] date_du = "" if ("date_du" in diction.keys()): if diction['date_du']: date_du = diction['date_du'] date_fin = "" if ("date_fin" in diction.keys()): if diction['date_fin']: date_fin = diction['date_fin'] # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_confirmation_inscription_formation_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params" :{"nom": str(diction['nom']), "prenom": str(prenom), "date_du": str(date_du), "date_fin": str(date_fin), "adresse": str(adresse_session), "title": str(diction['title']), "code_postal": str(local_code_postal), "ville": str(local_ville), "distantiel": str(local_distantiel), "presentiel": str(local_presentiel), "formateur": str(local_formateur), "session_ondemande": str(session_ondemande), "email": str(diction['email'])}, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') """ Update du 10/09/2023 : Utiliser les documents personnalisés qui sont stockés en base de données plutot que des format de fichiers plats. Regles d'utilisation : 1 - récupérer les fichier personnalisé pour le partenaire (partner_owner_recid et ref_interne). 2 - Si aucun fichier de personnalisation pour le partenaire, alors utiliser le fichier par defaut (partner_owner_recid = "default" et ref_interne). 3 - Pour le cas de pre-inscription, la ref_interne du fichier est 'PRE_INSCRIPTION' """ partner_document_CONF_INSCRIPTION_data_qry = {'partner_owner_recid': str(diction['partner_owner_recid']), 'valide': '1', 'locked': '0', 'ref_interne': 'CONF_INSCRIPTION'} print(" ### partner_document_CONF_INSCRIPTION_data_qry = ", partner_document_CONF_INSCRIPTION_data_qry) partner_document_CONF_INSCRIPTION_data = MYSY_GV.dbname['courrier_template'].find_one( {'partner_owner_recid': str(diction['partner_owner_recid']), 'valide': '1', 'locked': '0', 'ref_interne': 'PRE_INSCRIPTION'}) if (partner_document_CONF_INSCRIPTION_data is None): # Il n'existe pas de personnalisation de la preinscription pour ce partenaire, on va aller récupérer la presinscription pa defaut partner_document_CONF_INSCRIPTION_data = MYSY_GV.dbname['courrier_template'].find_one( {'partner_owner_recid': 'default', 'valide': '1', 'locked': '0', 'ref_interne': 'CONF_INSCRIPTION'}) if (partner_document_CONF_INSCRIPTION_data is None): mycommon.myprint( str(inspect.stack()[0][ 3]) + "-Impossible d'envoyer l'email de la preinscription. Aucun document parametré ") return False, " Impossible d'envoyer l'email de la preinscription. Aucun document parametré " if ("contenu_doc" not in partner_document_CONF_INSCRIPTION_data or len( str(partner_document_CONF_INSCRIPTION_data['contenu_doc'])) <= 0): mycommon.myprint(str(inspect.stack()[0][ 3]) + " -Impossible d'envoyer l'email de la preinscription. Le parametrage du document est invalide") return False, " Impossible d'envoyer l'email de la preinscription. Le parametrage du document est invalide " CONF_INSCRIPTION_contenu_doc_Template = jinja2.Template( str(partner_document_CONF_INSCRIPTION_data['contenu_doc'])) sourceHtml = CONF_INSCRIPTION_contenu_doc_Template.render(params=body["params"]) # print(" ### PRE_INSCRIPTION_contenu_doc = ",str(sourceHtml)) msg.set_content(sourceHtml, subtype='html') smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = '[MySy Training]: Confirmation inscription formation' msg['To'] = str(diction['email']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email confirlation envoyé " + str(val)) return True, " Email confirlation inscritpion bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'email de notification " """ Envoi de l'email de refus d'une d'inscription à une formation """ def incription_training_refused_mail(diction): try: print(" ### incription_training_refused_mail = "+str(diction)) """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'title', ] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer l'email de refus de l'inscritpion" tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print("debut envoi mail de test ") """ Verification si c'est une formation en ligne. auquel cas, l'adresse est du type : enligne""" my_adress = "" if ("adresse" in diction.keys()): if diction['adresse']: my_adress = diction['adresse'] presentiel = "" if ("presentiel" in diction.keys()): if diction['presentiel']: presentiel = diction['presentiel'] distantiel = "" if ("distantiel" in diction.keys()): if diction['distantiel']: distantiel = diction['distantiel'] adresse_session = my_adress # on rentre les renseignements pris sur le site du fournisseur # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_refus_inscription_formation_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = {} if ("comment" in diction.keys()): if diction['comment']: body = { "params" :{"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "adresse": str(adresse_session), "title": str(diction['title']), "email": str(diction['email']), "distantiel": str(diction['distantiel']), "presentiel": str(diction['presentiel']), "comment": str(diction['comment'])}, } else: body = { "params": {"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "adresse": str(adresse_session), "title": str(diction['title']), "email": str(diction['email'])}, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') """ Update du 10/09/2023 : Utiliser les documents personnalisés qui sont stockés en base de données plutot que des format de fichiers plats. Regles d'utilisation : 1 - récupérer les fichier personnalisé pour le partenaire (partner_owner_recid et ref_interne). 2 - Si aucun fichier de personnalisation pour le partenaire, alors utiliser le fichier par defaut (partner_owner_recid = "default" et ref_interne). 3 - Pour le cas de pre-inscription, la ref_interne du fichier est 'PRE_INSCRIPTION' """ partner_document_REFUS_INSCRIPTION_data_qry = {'partner_owner_recid': str(diction['partner_owner_recid']), 'valide': '1', 'locked': '0', 'ref_interne': 'REFUS_INSCRIPTION'} print(" ### partner_document_REFUS_INSCRIPTION_data_qry = ", partner_document_REFUS_INSCRIPTION_data_qry) partner_document_REFUS_INSCRIPTION_data = MYSY_GV.dbname['courrier_template'].find_one( {'partner_owner_recid': str(diction['partner_owner_recid']), 'valide': '1', 'locked': '0', 'ref_interne': 'REFUS_INSCRIPTION'}) if (partner_document_REFUS_INSCRIPTION_data is None): # Il n'existe pas de personnalisation de la preinscription pour ce partenaire, on va aller récupérer la presinscription pa defaut partner_document_PRE_INSCRIPTION_data = MYSY_GV.dbname['courrier_template'].find_one( {'partner_owner_recid': 'default', 'valide': '1', 'locked': '0', 'ref_interne': 'REFUS_INSCRIPTION'}) if (partner_document_REFUS_INSCRIPTION_data is None): mycommon.myprint( str(inspect.stack()[0][ 3]) + "-Impossible d'envoyer l'email de la preinscription. Aucun document parametré ") return False, " Impossible d'envoyer l'email de la preinscription. Aucun document parametré " if ("contenu_doc" not in partner_document_REFUS_INSCRIPTION_data or len( str(partner_document_REFUS_INSCRIPTION_data['contenu_doc'])) <= 0): mycommon.myprint(str(inspect.stack()[0][ 3]) + " -Impossible d'envoyer l'email de la preinscription. Le parametrage du document est invalide") return False, " Impossible d'envoyer l'email de la preinscription. Le parametrage du document est invalide " REFUS_INSCRIPTION_contenu_doc_Template = jinja2.Template( str(partner_document_REFUS_INSCRIPTION_data['contenu_doc'])) sourceHtml = REFUS_INSCRIPTION_contenu_doc_Template.render(params=body["params"]) # print(" ### PRE_INSCRIPTION_contenu_doc = ",str(sourceHtml)) msg.set_content(sourceHtml, subtype='html') smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = '[MySy Training]: Inscription formation refusée' msg['To'] = str(diction['email']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email confirlation envoyé " + str(val)) return True, " Email confirlation inscritpion bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'email de notification " """ Envoie de l'email d'information sur l'annulation de l'inscription """ def incription_training_cancelled_mail(diction): try: print(" ### incription_training_cancelled_mail = "+str(diction)) """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'title', ] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer l'email d'annulation de l'inscritpion" tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print("debut envoi mail de test ") """ Verification si c'est une formation en ligne. auquel cas, l'adresse est du type : enligne""" my_adress = "" if ("adresse" in diction.keys()): if diction['adresse']: my_adress = diction['adresse'] presentiel = "" if ("presentiel" in diction.keys()): if diction['presentiel']: presentiel = diction['presentiel'] distantiel = "" if ("distantiel" in diction.keys()): if diction['distantiel']: distantiel = diction['distantiel'] adresse_session = my_adress # on rentre les renseignements pris sur le site du fournisseur # msg = MIMEMultipart("alternative") smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_annule_inscription_formation_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = {} if ("comment" in diction.keys()): if diction['comment']: body = { "params" :{"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "adresse": str(adresse_session), "title": str(diction['title']), "email": str(diction['email']), "distantiel": str(distantiel), "presentiel": str(presentiel), "comment": str(diction['comment'])}, } else: body = { "params": {"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "adresse": str(adresse_session), "title": str(diction['title']), "email": str(diction['email'])}, } print(" #### body = ", body) sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = '[MySy Training]: Inscription formation annulée' msg['To'] = str(diction['email']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email confirlation envoyé " + str(val)) return True, " Email d'annulation de l'inscritpion bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'email de notification " """ Email de pre-inscription """ def Pre_incription_training_confirmation_mail(diction): try: print(" ### Preincription_training_confirmation_mail = "+str(diction)) """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'code_session', 'date_au', 'title', 'distantiel', 'presentiel', 'partner_owner_recid'] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer l'email de confirmation de l'inscritpion" tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print(" Pre_incription_training_confirmation_mail : debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur msg = MIMEMultipart("alternative") msg['Subject'] = 'MySy Training : pre-inscription formation' msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(diction['email']) # msg = MIMEMultipart("alternative") msg = EmailMessage() local_adress = "" if ("adresse" in diction.keys()): if diction['adresse']: local_adress = diction['adresse'] session_ondemande = "0" if ("session_ondemande" in diction.keys()): if diction['session_ondemande']: session_ondemande = diction['session_ondemande'] # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_confirmation_Pre_inscription_formation_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "distantiel": str(diction['distantiel']), "presentiel": str(diction['presentiel']), "title": str(diction['title']), "code_postal": str(diction['code_postal']), "ville": str(diction['ville']), "adresse":str(local_adress), "email": str(diction['email']), "session_ondemande": str(session_ondemande), "code_session": str(diction['code_session']), }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') """ Update du 10/09/2023 : Utiliser les documents personnalisés qui sont stockés en base de données plutot que des format de fichiers plats. Regles d'utilisation : 1 - récupérer les fichier personnalisé pour le partenaire (partner_owner_recid et ref_interne). 2 - Si aucun fichier de personnalisation pour le partenaire, alors utiliser le fichier par defaut (partner_owner_recid = "default" et ref_interne). 3 - Pour le cas de pre-inscription, la ref_interne du fichier est 'PRE_INSCRIPTION' """ partner_document_PRE_INSCRIPTION_data_qry = {'partner_owner_recid':str(diction['partner_owner_recid']), 'valide':'1', 'locked':'0', 'ref_interne': 'CONF_PRE_INSCRIPTION'} print(" ### partner_document_PRE_INSCRIPTION_data_qry = ",partner_document_PRE_INSCRIPTION_data_qry) partner_document_PRE_INSCRIPTION_data = MYSY_GV.dbname['courrier_template'].find_one({'partner_owner_recid':str(diction['partner_owner_recid']), 'valide':'1', 'locked':'0', 'ref_interne': 'CONF_PRE_INSCRIPTION'}) if( partner_document_PRE_INSCRIPTION_data is None ): # Il n'existe pas de personnalisation de la preinscription pour ce partenaire, on va aller récupérer la presinscription pa defaut partner_document_PRE_INSCRIPTION_data = MYSY_GV.dbname['courrier_template'].find_one( {'partner_owner_recid': 'default', 'valide': '1', 'locked': '0', 'ref_interne': 'CONF_PRE_INSCRIPTION'}) if( partner_document_PRE_INSCRIPTION_data is None): mycommon.myprint( str(inspect.stack()[0][3]) + "-Impossible d'envoyer l'email de la preinscription. Aucun document parametré ") return False, " Impossible d'envoyer l'email de la preinscription. Aucun document parametré " if( "contenu_doc" not in partner_document_PRE_INSCRIPTION_data or len(str(partner_document_PRE_INSCRIPTION_data['contenu_doc'])) <= 0 ): mycommon.myprint( str(inspect.stack()[0][3]) + " -Impossible d'envoyer l'email de la preinscription. Le parametrage du document est invalide") return False, " Impossible d'envoyer l'email de la preinscription. Le parametrage du document est invalide " PRE_INSCRIPTION_contenu_doc_Template = jinja2.Template(str(partner_document_PRE_INSCRIPTION_data['contenu_doc'])) sourceHtml = PRE_INSCRIPTION_contenu_doc_Template.render(params=body["params"]) #print(" ### PRE_INSCRIPTION_contenu_doc = ",str(sourceHtml)) msg.set_content(sourceHtml, subtype='html') smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = '[MySy Training] : pre-inscription formation' msg['To'] = str(diction['email']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email envoyé " + str(val)) return True, " Email bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'email de notification " """ Cet email envoie une notfication au l'institut de formation (partenair) Pour l'informer qu'un utilisateur s'est pre-inscrit """ def Notification_partner_Pre_incription_mail(diction): try: print(" ### Notification_partner_Pre_incription_mail = "+str(diction)) """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'title', 'partner_mail', 'telephone'] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer l'email de confirmation de l'inscritpion" local_adress = "" if ("adresse" in diction.keys()): if diction['adresse']: local_adress = diction['adresse'] local_employeur = "" if ("employeur" in diction.keys()): if diction['employeur']: local_employeur = diction['employeur'] local_ville = "" if ("ville" in diction.keys()): if diction['ville']: local_ville = diction['ville'] local_code_postal = "" if ("code_postal" in diction.keys()): if diction['code_postal']: local_code_postal = diction['code_postal'] session_ondemande = "0" if ("session_ondemande" in diction.keys()): if diction['session_ondemande']: session_ondemande = diction['session_ondemande'] tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur msg = MIMEMultipart("alternative") msg['Subject'] = 'MySy Training : pre-inscription formation' msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(diction['email']) #print(" ### Adresse = "+str(diction['adresse']) ) # msg = MIMEMultipart("alternative") msg = EmailMessage() smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Notif_Partner_Pre_inscription_formation_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "adresse": str(local_adress), "employeur": str(local_employeur), "telephone": str(diction['telephone']), "distantiel": str(diction['distantiel']), "presentiel": str(diction['presentiel']), "title": str(diction['title']), "code_postal": str(local_code_postal), "ville": str(local_ville), "email": str(diction['email']), "session_ondemande": str(session_ondemande), }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Cc'] = 'contact@mysy-training.com, billardman01@hotmail.com' msg['Subject'] = '[MySy Training] : pre-inscription à la formation '+str(diction['title']) msg['To'] = str(diction['partner_mail']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email envoyé " + str(val)) return True, " Email bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'email de notification " """ Envoi de l'email d'evaluation """ def Evaluation_training_confirmation_mail(diction): try: print(" ### Evaluation_training_confirmation_mail = " + str(diction)) """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'adresse', 'title', 'token_eval', 'internal_url', 'session_ondemande'] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer l'email de demande d'evaluation" tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur msg = MIMEMultipart("alternative") msg['Subject'] = 'MySy Training : Evaluation formation' msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(diction['email']) my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://www.mysy-training.com/Display-Detail-formation/" + str(diction['internal_url'])+"/"+str(diction['token_eval']) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:3009/Display-Detail-formation/" + str(diction['internal_url'])+"/"+str(diction['token_eval']) elif (MYSY_GV.MYSY_ENV == "REC"): my_url = "https://dev.mysy-training.com/Display-Detail-formation/" + str(diction['internal_url'])+"/"+str(diction['token_eval']) print(" ### Adresse = "+str(diction['adresse']) ) print(" #### my_url = ", my_url) # msg = MIMEMultipart("alternative") msg = EmailMessage() smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Evaluation_Class_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "adresse": str(diction['adresse']), "title": str(diction['title']), "presentiel": str(diction['presentiel']), "distantiel": str(diction['distantiel']), "email": str(diction['email']), "session_ondemande": str(diction['session_ondemande']), "mysyurl": str(my_url)} } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = 'MySy Training : Evaluation formation : '+str(diction['title']) msg['To'] = str(diction['email']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email envoyé " + str(val)) """ Apres l'envoi de la demande d'evaluation on met à jour le statut 'eval_statut' à 0 (envoyé) """ now = str(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")) #MYSY_GV.dbname['inscription'].find_one_and_update() ret_val2 = MYSY_GV.dbname['inscription'].find_one_and_update( {'_id': ObjectId(str(diction['session_id'])), 'valide': '1', }, {"$set": {'eval_status': '0', 'date_demande_eval': now, 'date_update': now}}, return_document=ReturnDocument.AFTER, upsert=False, ) return True, " Email bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'email de demande d'evaluation " """ Cette fonction envoi l'attestion par email """ def SendAttestion_to_attendee_by_email(diction): try: """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['partner_recid', 'session_id', 'class_internal_url', 'class_title' , 'email_participant', 'attestation_tmpl'] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer l'attestation par email " print(' ### diction = ',str(diction)) msg = MIMEMultipart("alternative") ## Recuperation des données du partenaire local_partnair = MYSY_GV.dbname['partnair_account'].find_one({'recid':str(diction['partner_recid']), 'active':'1', 'locked':'0'}) if( local_partnair is None ): mycommon.myprint( str(inspect.stack()[0][3]) + " - Impossible de récupérer les données du partenaire") return False, " Impossible de récupérer les données du partenaire " mysy_partner_nom = "" if ("nom" in local_partnair.keys()): mysy_partner_nom = str(local_partnair['nom']) mysy_partner_num_declation = "" if ("num_nda" in local_partnair.keys()): mysy_partner_num_declation = str(local_partnair['num_nda']) mysy_partner_adr_city = "" if ("adr_city" in local_partnair.keys()): mysy_partner_adr_city = str(local_partnair['adr_city']) ## Recuperation des données de l'inscrit local_inscription = MYSY_GV.dbname['inscription'].find_one({'session_id': str(diction['session_id']), 'class_internal_url': str(diction['class_internal_url']), 'email':str(diction['email_participant'])}) if (local_inscription is None): mycommon.myprint( str(inspect.stack()[0][3]) + " - Impossible de récupérer les données du participants") return False, " Impossible de récupérer les données du participants " nom = "" if ("nom" in local_inscription.keys()): nom = str(local_inscription['nom']) prenom = "" if ("prenom" in local_inscription.keys()): prenom = str(local_inscription['prenom']) date_du = "" if ("date_du" in local_inscription.keys()): date_du = str(local_inscription['date_du'])[0:10] date_au = "" if ("date_au" in local_inscription.keys()): date_au = str(local_inscription['date_au'])[0:10] ville = "" if ("ville" in local_inscription.keys()): ville = str(local_inscription['ville']) code_postal = "" if ("code_postal" in local_inscription.keys()): code_postal = str(local_inscription['code_postal']) adresse = "" if ("adresse" in local_inscription.keys()): adresse = str(local_inscription['adresse']) ## Recuperation des données de la session local_session = MYSY_GV.dbname['session_formation'].find_one({'_id': ObjectId(str(diction['session_id'])), 'class_internal_url': str( diction['class_internal_url']), 'valide':'1'}) if (local_session is None): mycommon.myprint( str(inspect.stack()[0][3]) + " - Impossible de récupérer les données de la session") return False, " Impossible de récupérer les données de la session " formateur = "" if ("formateur" in local_session.keys()): formateur = str(local_session['formateur']) presentiel = "" if ("presentiel" in local_session.keys()): presentiel = str(local_session['presentiel']) distantiel = "" if ("distantiel" in local_session.keys()): distantiel = str(local_session['distantiel']) contenu_ftion = "" if ("contenu_ftion" in local_session.keys()): contenu_ftion = str(local_session['contenu_ftion']).replace('

', '').replace('

', '').replace("\r\n", '
') print(" ### contenu_ftion = ", contenu_ftion) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(diction['email_participant']) ct = datetime.datetime.now() ts = ct.timestamp() date_jour = ct.strftime("%d/%m/%Y") # msg = MIMEMultipart("alternative") msg = MIMEMultipart("alternative") msg22 = EmailMessage() smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/"+ str(diction['attestation_tmpl']) +".html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params": {"nom": str(nom), "prenom": str(prenom), "date_du": str(date_du), "date_au": str(date_au), "class_title": str(diction['class_title']), "email": str(diction['email_participant']), "adresse": str(adresse), "code_postal": str(code_postal), "ville": str(ville), "formateur": str(formateur), "presentiel": str(presentiel), "distantiel": str(distantiel), "partner": str(mysy_partner_nom), "contenu_ftion": str(contenu_ftion), "num_declation": str(mysy_partner_num_declation), "mysy_partner_adr_city":str(mysy_partner_adr_city), "date_jour":str(date_jour), "cachet_signature": "https://img.mysy-training.com/perso/mysy_cachet.png", "logo_url": "https://img.mysy-training.com/1000formation/LOGO-FORMATION1000.png" }} print("### body 22 ", body) sourceHtml = template.render(json_data=body["params"]) file_name = str("Attestation_" + str(ts) ).replace(".", "") orig_file_name = str(file_name)+".pdf" outputFilename = str(MYSY_GV.INVOICE_DIRECTORY) + str(orig_file_name) print(" ### orig_file_name = ", outputFilename) # open output file for writing (truncated binary) resultFile = open(outputFilename, "w+b") # convert HTML to PDF pisaStatus = pisa.CreatePDF( src=sourceHtml, # the HTML to convert dest=resultFile) # file handle to receive result # close output file resultFile.close() """ #----------- msg22.set_content(sourceHtml, subtype='html') msg22['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg22['Bcc'] = 'contact@mysy-training.com' msg22['Subject'] = 'MySy Training : Votre attestation de formation : ' + str(diction['class_title']) msg22['To'] = str(diction['email_participant']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg22) smtpserver.close() print(" Email envoyé " + str(val)) return True, " email envoyé ok" #---------- """ html = '''

Attestation de {nom} {prenom}

Bonjour,
Merci de trouver votre attestation de la formation {maformation} en pièce jointe
'''.format(nom=nom, prenom = prenom, maformation=str(diction['class_title'])) html_mime = MIMEText(html, 'html') # msg.attach(texte_mime) msg.attach(html_mime) #print("html_mime =" + str(html)) f = outputFilename part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"' .format(os.path.basename(f))) msg.attach(part) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = 'MySy Training : Votre attestation de formation : ' + str(diction['class_title']) msg['To'] = str(diction['email_participant']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email envoyé " + str(val)) mytoday = datetime.date.today().strftime("%d/%m/%Y") my_local_mydata = {'certification_send_date':str(mytoday)} #print(" ### str(diction['inscription_id']) = ",str(diction['inscription_id']) ) ## Mise à jour de la date d'envoi du certificat MYSY_GV.dbname['inscription'].find_one_and_update({'session_id': str(diction['session_id']), 'class_internal_url': str(diction['class_internal_url']), 'email':str(diction['email_participant'])}, {"$set":my_local_mydata}, return_document=ReturnDocument.AFTER,) return True, " Email bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'attestation par email " """ Cette fonction crée une attestation et converti en PDF en mode standalone (c'est un test) """ def SendAttestion_to_attendee_by_email_standalone(diction): try: """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'adresse', 'title', 'attestation_tmpl', 'inscription_id', 'partner_recid', 'formateur', 'presentiel', 'distantiel'] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer l'attestation par email " print(' ### diction = ',str(diction)) msg = MIMEMultipart("alternative") # Recuperation des données du partenaire formateur mysy_partner = MYSY_GV.dbname['partnair_account'].find_one({'recid':str(diction['partner_recid']), 'active':"1",'locked':"0" }) if( mysy_partner is None or mysy_partner['_id'] is None): mycommon.myprint( str(inspect.stack()[0][3]) + " - Impossible de récupérer les données du partenaire") return False, "Impossible de récupérer les données du partenaire " mysy_partner_nom = "" if ("nom" in mysy_partner.keys() and mysy_partner['nom']): mysy_partner_nom = mysy_partner['nom'] mysy_partner_num_declation = "" if ("num_nda" in mysy_partner.keys() and mysy_partner['num_nda']): mysy_partner_num_declation = mysy_partner['num_nda'] mysy_partner_siren = "" if ("siren" in mysy_partner.keys() and mysy_partner['siren']): mysy_partner_siren = mysy_partner['siren'] mysy_partner_adr_city = "" if ("adr_city" in mysy_partner.keys() and mysy_partner['adr_city']): mysy_partner_adr_city = mysy_partner['adr_city'] if(len(mysy_partner_num_declation.strip()) == 0 and len(mysy_partner_siren.strip()) == 0): mycommon.myprint( str(inspect.stack()[0][3]) + " - Aucun numero de déclaration ni numero SIREN enregistré") return False, "Aucun numero de déclaration ni numero SIREN enregistré" msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(diction['email']) ct = datetime.datetime.now() ts = ct.timestamp() date_jour = ct.strftime("%d/%m/%Y") # msg = MIMEMultipart("alternative") msg = MIMEMultipart("alternative") smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/"+ str(diction['attestation_tmpl']) +".html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params": {"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du'])[0:10], "date_au": str(diction['date_au'])[0:10], "adresse": str(diction['adresse']), "class_title": str(diction['title']), "email": str(diction['email']), "formateur": str(diction['formateur']), "presentiel": str(diction['presentiel']), "distantiel": str(diction['distantiel']), "partner": str(mysy_partner_nom), "contenu_ftion": "Les 10 états d’esprit Kaizen
Pratique du PDCA et de la Résolution de problème
MODULE 3 Pérennisation:
Les rituels managériaux
Piloter un système Lean", "num_declation": str(mysy_partner_num_declation), "mysy_partner_siren": str(mysy_partner_siren), "mysy_partner_adr_city":str(mysy_partner_adr_city), "date_jour":str(date_jour), "cachet_signature": "https://img.mysy-training.com/perso/mysy_cachet.png", "logo_url": "https://img.mysy-training.com/1000formation/LOGO-FORMATION1000.png" }} sourceHtml = template.render(json_data=body["params"]) orig_file_name = "Attestation_" + str(ts) + ".pdf" outputFilename = str(MYSY_GV.INVOICE_DIRECTORY) + str(orig_file_name) # open output file for writing (truncated binary) resultFile = open(outputFilename, "w+b") # convert HTML to PDF pisaStatus = pisa.CreatePDF( src=sourceHtml, # the HTML to convert dest=resultFile) # file handle to receive result # close output file resultFile.close() html = '''

{mymessage}

'''.format(mymessage="cherif bladeee") html_mime = MIMEText(html, 'html') # msg.attach(texte_mime) msg.attach(html_mime) print("html_mime =" + str(html)) toaddr = "billardman1@gmail.com" cc = ['cbalde@mysy-training.com'] toaddrs = [toaddr] + cc f = './Invoices/aaa.pdf' part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"' .format(os.path.basename(f))) msg.attach(part) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com, mysytraining@gmail.com' msg['Subject'] = 'MySy Training : Votre attestation de formation : ' + str(diction['title']) msg['To'] = str(diction['email']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) smtpserver.send_message(msg) smtpserver.close() print(" Email envoyé " + str(val)) mytoday = datetime.date.today().strftime("%d/%m/%Y") my_local_mydata = {'certification_send_date':str(mytoday)} print(" ### str(diction['inscription_id']) = ",str(diction['inscription_id']) ) ## Mise à jour de la date d'envoi du certificat MYSY_GV.dbname['inscription'].find_one_and_update({'_id':ObjectId(str(diction['inscription_id']))}, {"$set":my_local_mydata}, return_document=ReturnDocument.AFTER,) return True, " Email bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'attestation par email " def sendmailwith_attached(): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur msg = MIMEMultipart("alternative") msg['Subject'] = '[MySy Training Technology] : yesss' msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = "billardman1@gmail.com" html = '''

{mymessage}

'''.format(mymessage="cherif bladeee") html_mime = MIMEText(html, 'html') # msg.attach(texte_mime) msg.attach(html_mime) print("html_mime =" + str(html)) toaddr = "billardman1@gmail.com" cc = ['cbalde@mysy-training.com'] toaddrs = [toaddr] + cc f = './Invoices/aaa.pdf' part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"' .format(os.path.basename(f))) msg.attach(part) # msg.attach(MIMEText(open(filename).read())) with smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) as server: server.starttls() # Secure the connection server.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) server.sendmail(MYSY_GV.O365_SMTP_COUNT_From_User, toaddrs, msg.as_string()) mycommon.myprint("mail successfully sent to " + str(toaddrs)) return True, " Email bien envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'attestation par email " """ Cette fonction envoie les informations d'identification de connexion à la plateforme LMS """ def LMS_Credential_Sending_mail(diction): try: """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'date_du', 'date_au', 'title', 'login', 'pwd', 'lms_url', 'course_owner_email', 'partner_recid' ] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer les information de connexion à la plateforme LMS" """ local_status, is_account_exist = mycommon.is_LMS_user_exist(diction) if( local_status is False or is_account_exist is False): mycommon.myprint( str(inspect.stack()[0][3]) + " - Le compte LMS n'est pas valide ") return False, "Le compte LMS n'est pas valide" """ tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print("debut envoi mail de test ") """ Verification si c'est une formation en ligne. auquel cas, l'adresse est du type : enligne""" my_adress = "" if ("adresse" in diction.keys()): if diction['adresse']: my_adress = diction['adresse'] presentiel = "" if ("presentiel" in diction.keys()): if diction['presentiel']: presentiel = diction['presentiel'] distantiel = "" if ("distantiel" in diction.keys()): if diction['distantiel']: distantiel = diction['distantiel'] adresse_session = my_adress # on rentre les renseignements pris sur le site du fournisseur # msg = MIMEMultipart("alternative") smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_LMS_credential_sending_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = {} body = { "params": {"nom": str(diction['nom']), "prenom": str(diction['prenom']), "date_du": str(diction['date_du']), "date_fin": str(diction['date_au']), "adresse": str(adresse_session), "title": str(diction['title']), "email": str(diction['email']), "login": str(diction['login']), "pwd": str(diction['pwd']), "lms_url": str(diction['lms_url']), "course_owner_email": str(diction['course_owner_email'])}, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com,'+str(str(diction['course_owner_email'])) msg['Subject'] = '[MySy Training]: Vos identifications de connexion' msg['To'] = str(diction['email']) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email confirlation envoyé " + str(val)) return True, " Email d'identification de connexion envoyé " except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'email de notification " """ Fonction qui envoi les identifiant de connexion à un employé dont on vient de créer le compte utilisateur """ def Employee_Credential_Sending_mail(diction): try: """ Verification de la liste des champs obligatoires """ field_list_obligatoire = ['nom', 'prenom', 'email', 'login', 'pwd', 'mysy_url', 'email_bcc', 'partner_owner_recid' ] for val in field_list_obligatoire: if val not in diction: mycommon.myprint( str(inspect.stack()[0][3]) + " - : La valeur '" + val + "' n'est pas presente dans liste ") return False, "Impossible d'envoyer les information de connexion à la plateforme LMS" """ local_status, is_account_exist = mycommon.is_LMS_user_exist(diction) if( local_status is False or is_account_exist is False): mycommon.myprint( str(inspect.stack()[0][3]) + " - Le compte LMS n'est pas valide ") return False, "Le compte LMS n'est pas valide" """ tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur # msg = MIMEMultipart("alternative") smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) msg = EmailMessage() # JINJA2 # This data can come from database query body = {} body = { "params": {"nom": str(diction['nom']), "prenom": str(diction['prenom']), "email": str(diction['email']), "login": str(diction['login']), "pwd": str(diction['pwd']), "mysy_url": str(diction['mysy_url']), }, } #------------------ partner_document_EMPLOYEE_CREDENTIALS_data_qry = {'partner_owner_recid': str(diction['partner_owner_recid']), 'valide': '1', 'locked': '0', 'ref_interne': 'EMPLOYEE_CREDENTIALS'} print(" ### partner_document_EMPLOYEE_CREDENTIALS_data_qry = ", partner_document_EMPLOYEE_CREDENTIALS_data_qry) partner_document_EMPLOYEE_CREDENTIALS_data = MYSY_GV.dbname['courrier_template'].find_one(partner_document_EMPLOYEE_CREDENTIALS_data_qry) if (partner_document_EMPLOYEE_CREDENTIALS_data is None): # Il n'existe pas de personnalisation de la preinscription pour ce partenaire, on va aller récupérer la presinscription pa defaut partner_document_EMPLOYEE_CREDENTIALS_data = MYSY_GV.dbname['courrier_template'].find_one( {'partner_owner_recid': 'default', 'valide': '1', 'locked': '0', 'ref_interne': 'EMPLOYEE_CREDENTIALS'}) if (partner_document_EMPLOYEE_CREDENTIALS_data is None): mycommon.myprint( str(inspect.stack()[0][ 3]) + "-Impossible d'envoyer l'email de notification des accès. Aucun document parametré ") return False, " Impossible d'envoyer l'email de notification des accès. Aucun document parametré " if ("contenu_doc" not in partner_document_EMPLOYEE_CREDENTIALS_data or len( str(partner_document_EMPLOYEE_CREDENTIALS_data['contenu_doc'])) <= 0): mycommon.myprint(str(inspect.stack()[0][ 3]) + " -Impossible d'envoyer l'email de notification des accès. Le parametrage du document est invalide") return False, " Impossible d'envoyer l'email de notification des accès. Le parametrage du document est invalide " EMPLOYEE_CREDENTIALS_contenu_doc_Template = jinja2.Template( str(partner_document_EMPLOYEE_CREDENTIALS_data['contenu_doc'])) sourceHtml = EMPLOYEE_CREDENTIALS_contenu_doc_Template.render(params=body["params"]) # print(" ### PRE_INSCRIPTION_contenu_doc = ",str(sourceHtml)) msg.set_content(sourceHtml, subtype='html') smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User #msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = '[MySy Training]: Vos identifiants de connexion' msg['To'] = str(diction['email']) msg['Bcc'] = str(diction['email_bcc']) #----------------- smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) val = smtpserver.send_message(msg) smtpserver.close() print(" Email EMPLOYEE_CREDENTIALS envoyé " + str(val)) return True, " Email d'identification de connexion envoyé " except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer l'email de notification "