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 module_editique
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')

        """
                Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

        if (str(partner_own_smtp_value) == "1"):
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
        else:
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)


        if (str(partner_own_smtp_value) == "1"):
            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
        else:
            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')

        """
               Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
               """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

        if (str(partner_own_smtp_value) == "1"):
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)

            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email confirmation envoyé " + str(val))

        else:

            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 confirmation 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





        # JINJA2
        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)

        # This data can come from database query
        body = {}


        if ("comment" in diction.keys() and 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'])},
                }

        # Recuperation du modele de courrier d'annulation d'une inscription
        partner_document_ANNULE_INSCRIPTION_data_qry = {'partner_owner_recid': str(diction['partner_owner_recid']),
                                                     'valide': '1', 'locked': '0',
                                                     'ref_interne': 'ANNULE_INSCRIPTION'}

        print(" ### partner_document_PRE_INSCRIPTION_data_qry = ", partner_document_ANNULE_INSCRIPTION_data_qry)
        partner_document_ANNULE_INSCRIPTION_data = MYSY_GV.dbname['courrier_template'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'valide': '1', 'locked': '0', 'ref_interne': 'ANNULE_INSCRIPTION'})

        if (partner_document_ANNULE_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_ANNULE_INSCRIPTION_data = MYSY_GV.dbname['courrier_template'].find_one(
                {'partner_owner_recid': 'default',
                 'valide': '1', 'locked': '0', 'ref_interne': 'ANNULE_INSCRIPTION'})

        if (partner_document_ANNULE_INSCRIPTION_data is None):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + "-Impossible d'envoyer l'email d'annulation de l'inscription. Aucun document parametré ")
            return False, " Impossible d'envoyer l'email d'annulation de l'inscription. Aucun document parametré "

        if ("contenu_doc" not in partner_document_ANNULE_INSCRIPTION_data or len(
                str(partner_document_ANNULE_INSCRIPTION_data['contenu_doc'])) <= 0):
            mycommon.myprint(str(inspect.stack()[0][
                                     3]) + " -Impossible d'envoyer l'email d'annulation de l'inscription. Le parametrage du document  est invalide")
            return False, " Impossible d'envoyer l'email d'annulation de l'inscription. Le parametrage du document  est invalide "

        ANNULE_INSCRIPTION_contenu_doc_Template = jinja2.Template(
            str(partner_document_ANNULE_INSCRIPTION_data['contenu_doc']))
        sourceHtml = ANNULE_INSCRIPTION_contenu_doc_Template.render(params=body["params"])



        print(" #### body = ", body)


        # msg = MIMEMultipart("alternative")

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])




        if (str(partner_own_smtp_value) == "1"):
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
            msg = EmailMessage()
            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email confirlation envoyé " + str(val))

        else:
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            msg = EmailMessage()

            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')

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])


        if (str(partner_own_smtp_value) == "1"):
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)

            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email envoyé " + str(val))

        else:

            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")


        # 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"])

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

        if (str(partner_own_smtp_value) == "1"):
            msg = EmailMessage()
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
            msg.set_content(sourceHtml, subtype='html')
            msg['From'] = partner_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.loginlogin(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email envoyé " + str(val))

        else:
            msg = EmailMessage()
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            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', 'token', 'session_id', 'inscription_id']
        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"


        local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
        if (local_status is not True):
            return local_status, my_partner

        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'])

        elif (MYSY_GV.MYSY_ENV == "DEM"):
            my_url = "https://demo.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")



        # 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"])

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

        if (str(partner_own_smtp_value) == "1"):
            msg = EmailMessage()
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
            msg.set_content(sourceHtml, subtype='html')
            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email envoyé " + str(val))

        else:
            msg = EmailMessage()
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            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"))
        new_data = {}
        new_data['eval_status'] = "0"
        new_data['date_demande_eval'] = str(now)
        new_data['date_update'] = str(now)
        new_data['update_by'] = str(my_partner['_id'])


        #MYSY_GV.dbname['inscription'].find_one_and_update()
        ret_val2 = MYSY_GV.dbname['inscription'].find_one_and_update(
            {'_id': ObjectId(str(diction['inscription_id'])), 'valide': '1', },
            {"$set": new_data},
            return_document=ReturnDocument.AFTER,
            upsert=False,
        )

        if( ret_val2 is None ):
            mycommon.myprint(
                " WARNING : Impossible mettre à jour la date de demande d'évaluation: ")

        """
               update du 30/01/2024 :
              Apres l'envoi de la demande d'evaluation
               loger une action dans la collection  ==> courrier_template_tracking_history
               """

        local_status, local_retval = module_editique.Editic_Log_History_Action_From_courrier_template_type_document_ref_interne(
            my_partner, "EVALUATIONS",
            str(diction['session_id']), 'inscription', str(diction['inscription_id']), "")

        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 "





        ## 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('<p>', '').replace('</p>', '').replace("\r\n", '<br/>')

            print(" ### contenu_ftion = ", contenu_ftion)



        ct = datetime.datetime.now()
        ts = ct.timestamp()
        date_jour = ct.strftime("%d/%m/%Y")

        # msg = MIMEMultipart("alternative")

        # 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"
                       }}




        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()




        html = '''
                          <!DOCTYPE html>
                          <html>
                              <body>

                              <h3> Attestation de {nom} {prenom} </h3>
                              Bonjour, <br/>
                              Merci de trouver votre attestation de la  formation {maformation} en pièce jointe
                               <br/>

                              </body>
                              </html>'''.format(nom=nom, prenom = prenom, maformation=str(diction['class_title']))

        html_mime = MIMEText(html, 'html')

        #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)))

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])


        if (str(partner_own_smtp_value) == "1"):
            msg = MIMEMultipart("alternative")
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
            msg.attach(html_mime)
            msg.attach(part)
            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email envoyé " + str(val))

        else:

            msg = MIMEMultipart("alternative")
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            msg.attach(html_mime)
            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")

        # 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 &eacute;tats d&rsquo;esprit Kaizen<br>Pratique du PDCA et de la R&eacute;solution de probl&egrave;me<br>MODULE 3 P&eacute;rennisation:<br>Les rituels manag&eacute;riaux<br>Piloter un syst&egrave;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 = '''
                          <!DOCTYPE html>
                          <html>
                              <body>

                              <h1> {mymessage} </h1>

                              </body>
                              </html>'''.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)))

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

        if (str(partner_own_smtp_value) == "1"):
            msg = MIMEMultipart("alternative")
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)

            msg.attach(part)
            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email envoyé " + str(val))

        else:
            msg = MIMEMultipart("alternative")
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)

            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 = '''
                  <!DOCTYPE html>
                  <html>
                      <body>

                      <h1> {mymessage} </h1>

                      </body>
                      </html>'''.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")

        # 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"])

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

        if (str(partner_own_smtp_value) == "1"):
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
            msg = EmailMessage()
            msg.set_content(sourceHtml, subtype='html')
            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email confirlation envoyé " + str(val))

        else:
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            msg = EmailMessage()
            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")


        # 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))

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

        if (str(partner_own_smtp_value) == "1"):
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
            msg = EmailMessage()
            msg.set_content(sourceHtml, subtype='html')
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            msg['From'] = partner_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(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email EMPLOYEE_CREDENTIALS envoyé " + str(val))

        else:
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            msg = EmailMessage()
            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]: 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 "


"""
Cette fonction un mail à un EMPLOYE pour lui notifier
de l'ouverture de ses acces à la plateforme E-Learning
"""
def Employee_Acces_LMS_Sending_mail(diction):
    try:

        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['nom', 'prenom', 'email',  'mysy_url', '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")


        # JINJA2
        # This data can come from database query
        body = {}

        body = {

            "params": {"nom": str(diction['nom']),
                       "prenom": str(diction['prenom']),
                       "email": str(diction['email']),
                        "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_FOR_LMS'}

        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_FOR_LMS'})

        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))

        """
                       Recuperation des parametre SMTP du partner si le client a decidé d'utiliser son propre smpt
                       """
        partner_own_smtp_value = "0"
        partner_own_smtp = MYSY_GV.dbname['base_partner_setup'].find_one(
            {'partner_owner_recid': str(diction['partner_owner_recid']),
             'config_name': 'partner_smtp',
             'valide': '1',
             'locked': '0'})

        if (partner_own_smtp and "config_value" in partner_own_smtp.keys()):
            partner_own_smtp_value = partner_own_smtp['config_value']

            if (str(partner_own_smtp_value) == "1"):
                partner_SMTP_COUNT_password = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user_pwd',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_smtpsrv = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_server',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_user = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_user',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_From_User = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_from_name',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

                partner_SMTP_COUNT_port = str(MYSY_GV.dbname['base_partner_setup'].find_one(
                    {'partner_owner_recid': str(diction['partner_owner_recid']),
                     'config_name': 'smtp_count_port',
                     'valide': '1',
                     'locked': '0'}, {'config_value': 1})['config_value'])

        if (str(partner_own_smtp_value) == "1"):
            smtpserver = smtplib.SMTP(partner_SMTP_COUNT_smtpsrv, partner_SMTP_COUNT_port)
            msg = EmailMessage()
            msg.set_content(sourceHtml, subtype='html')
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            msg['From'] = partner_SMTP_COUNT_From_User
            # msg['Bcc'] = 'contact@mysy-training.com'
            msg['Subject'] = partner_document_EMPLOYEE_CREDENTIALS_data['sujet']
            msg['To'] = str(diction['email'])


            # -----------------

            smtpserver.ehlo()
            smtpserver.starttls()
            smtpserver.login(partner_SMTP_COUNT_user, partner_SMTP_COUNT_password)
            val = smtpserver.send_message(msg)
            smtpserver.close()
            print(" Email EMPLOYEE_CREDENTIALS_FOR_LMS envoyé " + str(val))

        else:
            smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port)
            msg = EmailMessage()
            msg.set_content(sourceHtml, subtype='html')
            msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
            #msg['Bcc'] = 'contact@mysy-training.com'
            msg['Subject'] = partner_document_EMPLOYEE_CREDENTIALS_data['sujet']
            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 EMPLOYEE_CREDENTIALS_FOR_LMS envoyé " + str(val))


        return True, " Email d'identification de connexion au E-Learnning 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 de connexion au E-Learning "
