from __future__ import print_function import smtplib from email.message import EmailMessage from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email import encoders import Inscription_mgt as inscription import partner_client import locale import datetime import inspect import sys, os 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 import strype_payement as strype_payement import ressources_humaines as ressources_humaines configuration = sib_api_v3_sdk.Configuration() configuration.api_key['api-key'] = MYSY_GV.SENDINBLUE_API_KEY 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 = 'contact@mysy-training.com' receiver = ["cbalde3@mysy-training.com","billardman1@gmail.com"] user = 'contact@mysy-training.com' password = 'yGmzqBfrjb3YCvQN' def send_user_account_mail_old(message, account_mail): 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 : Activez votre compte ' msg['From'] = 'contact@mysy-training.com' msg['To'] = str(account_mail) to = [{"email":str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://apimysy.mysy-training.com/myclass/api/valide_user_account/"+str(message) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:"+str(MYSY_GV.MYSY_PORT_DEV)+"/myclass/api/valide_user_account/"+str(message) elif (MYSY_GV.MYSY_ENV == "REC"): my_url = "https://devapimysy.mysy-training.com/myclass/api/valide_user_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEM"): my_url = "https://demoapi.mysy-training.com/myclass/api/valide_user_account/" + str(message) send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=15, params={"mysyurl": my_url, "user_name": str(account_mail), "id": "122CSR_id"}, to=to, bcc=bcc ) api_response = api_instance.send_transac_email(send_smtp_email) print(api_response) return True 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 envoie un mail de remerciement apres l'activation du compte d'un utilisateur ''' def send_user_thks_mail_old(message, account_mail): 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 : Votre compte est actif ' msg['From'] = 'contact@mysy-training.com' msg['To'] = str(account_mail) to = [{"email": str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://apimysy.mysy-training.com/myclass/api/valide_user_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:"+str(MYSY_GV.MYSY_PORT_DEV)+"/myclass/api/valide_user_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "REC"): my_url = "https://devapimysy.mysy-training.com/myclass/api/valide_user_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEM"): my_url = "https://demoapi.mysy-training.com/myclass/api/valide_user_account/" + str(message) send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=16, params={ "user_name": str(account_mail),}, to=to, bcc=bcc ) api_response = api_instance.send_transac_email(send_smtp_email) print(api_response) return True 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 " def send_partner_account_mail_old(message, account_mail): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") receiver = [str(account_mail)] toaddrs = ",".join(receiver) my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://apimysy.mysy-training.com/myclass/api/valide_partnair_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:"+str(MYSY_GV.MYSY_PORT_DEV)+"/myclass/api/valide_partnair_account/"+str(message) elif (MYSY_GV.MYSY_ENV == "REC"): my_url = "https://devapimysy.mysy-training.com/myclass/api/valide_partnair_account/"+str(message) elif (MYSY_GV.MYSY_ENV == "DEM"): my_url = "https://demoapi.mysy-training.com/myclass/api/valide_partnair_account/"+str(message) print(" mail enoye à toaddrs : "+toaddrs) print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur msg = MIMEMultipart("alternative") msg['Subject'] = '[MySy Training]: activation de votre compte PRO' msg['From'] = 'contact@mysy-training.com' msg['To'] = str(toaddrs) msg['Bcc'] = 'contact@mysy-training.com' to = [{"email": str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=17, params={"mysyurl": my_url, "user_name": str(account_mail), }, to=to, bcc=bcc ) api_response = api_instance.send_transac_email(send_smtp_email) print(api_response) return True 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 de reinitialisation du mot de passe du user ''' def send_user_init_pwd_mail_pwd(token, account_mail, type_account): 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] : Reinitialisez votre mot de passe' msg['From'] = 'contact@mysy-training.com' msg['To'] = str(account_mail) my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://www.mysy-training.com/ResetUserPwd/" + str(token)+"/"+str(type_account) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:3009/ResetUserPwd/" + str(token)+"/"+str(type_account) to = [{"email": str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=19, params={"mysyurl": my_url, "user_name": str(account_mail), }, to=to, bcc=bcc ) api_response = api_instance.send_transac_email(send_smtp_email) print(api_response) return True 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 de suppression du compte utilisateur ''' def send_user_delete_account(token, account_mail): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") msg = MIMEMultipart("alternative") msg['Subject'] = '[MySy Training Technology] : Suppression de votre' msg['From'] = 'contact@mysy-training.com' msg['To'] = str(account_mail) my_url = "" if( MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://www.mysy-training.com/DeleteUserAccount/" + str(token) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:3009/DeleteUserAccount/" + str(token) to = [{"email": str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=20, params={"mysyurl": my_url, "user_name": str(account_mail), }, to=to, bcc=bcc ) api_response = api_instance.send_transac_email(send_smtp_email) print(api_response) return True 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 envoir n'import quel email avec les varibable : - recever_email - objet_mail - message_mail ''' def SendGenericEmail(mail_recever=None, mail_object=None, mail_message=None): 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] : '+str(mail_object) msg['From'] = MYSY_GV.INTERNAL_MAIL_SENDER msg['To'] = str(mail_recever) html = '''

Mysy Training Logo

Bonjour
Message de MySy-Training Technology .
{mymessage}
'''.format(mymessage=mail_message) html_mime = MIMEText(html, 'html') # msg.attach(texte_mime) msg.attach(html_mime) print("html_mime =" + str(html)) toaddr = str(mail_recever) cc = ['cbalde@mysy-training.com'] toaddrs = [toaddr] + cc # msg.attach(MIMEText(open(filename).read())) with smtplib.SMTP(smtp_address, port) as server: server.starttls() # Secure the connection server.login(user, password) server.sendmail(sender, toaddrs, msg.as_string()) mycommon.myprint("mail successfully sent to " + str(toaddrs)) return True except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False ''' Apres l'activation du compte pro, cet email envoie le token et mot de passe temporaire à l'utilisateur ''' def Pro_Account_Token_Pass_old(account_mail, my_token): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") receiver = [str(account_mail)] toaddrs = ",".join(receiver) print(" mail enoye à toaddrs : " + toaddrs) print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur msg = MIMEMultipart("alternative") msg['Subject'] = '[MySy Training]: votre compte PRO est pret' msg['From'] = 'contact@mysy-training.com' msg['To'] = str(toaddrs) msg['Bcc'] = 'contact@mysy-training.com' cle = my_token print(" mail enoye à toaddrs : " + str(msg['To'])) to = [{"email": str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=18, params={"user_name": str(account_mail), "secrete":str(my_token) }, to=to, bcc=bcc) api_response = api_instance.send_transac_email(send_smtp_email) print(api_response) return True except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False ''' Cette fonction envoie l'email de confirmation de la commande de vente ''' def SalesOrderConfirmationEmail_old(account_mail, diction): try: ''' Verification des données obligatoires ''' ''' Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, On controle que les champs obligatoires sont presents dans la liste ''' field_list_obligatoire = ['invoice_nom', 'invoice_adr_city', 'invoice_adr_country', 'invoice_adr_street', 'invoice_adr_zip', 'periodicite', 'total_ht', 'total_tva', 'total_ttc', 'order_id', 'date_update', 'nb_product', 'order_date'] 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 la liste des arguments ") return False, " Impossible d'envoyer l'email de confirmation" total_ht = diction['total_ht'] tva = diction['total_tva'] total_ttc = diction['total_ttc'] client_name = diction['invoice_nom'] client_address = diction['invoice_adr_street'] client_zip_ville = diction['invoice_adr_zip']+" "+diction['invoice_adr_city'] client_pays = diction['invoice_adr_country'] order_id = diction['order_id'] date_order = diction['order_date'] my_end_date = "" if ("end_date" in diction.keys()): if diction.keys(): my_end_date = "*Offre valable jusqu'au "+str(diction['end_date']) nb_line = mycommon.tryInt(diction['nb_product']) if( nb_line == 0 ): mycommon.myprint(str(inspect.stack()[0][3]) + " - nb_line = '" + nb_line + "' : Aucun produit à facturer") return False, " Impossible d'envoyer l'email de confirmation" #print("client_name = "+str(client_name)) #print("client_address = " + str(client_address)) #print("client_zip_ville = " + str(client_zip_ville)) #print("client_pays = " + str(client_pays)) #print("order_id = " + str(order_id)) #print("date_order = " + str(date_order)) #print("nb_line = " + str(nb_line)) #print("End Date = " + str(my_end_date)) # Recuperation des produits (max 3 produits) # produit 1 if ("item_0" in diction.keys()): if( diction["item_0"] ): packs = diction["item_0"]['code'] qty = diction["item_0"]['qty'] unit_price = diction["item_0"]['prix'] montant = diction["item_0"]['amount'] detail_packs = diction["item_0"]['pack_products'] #print("diction['item_0']['pack_products'] = "+str(diction["item_0"]['pack_products'])) # produit 2 if ("item_1" in diction.keys()): if (diction["item_1"]): packs1 = diction["item_1"]['code'] qty1 = diction["item_0"]['qty'] unit_price1 = diction["item_1"]['prix'] montant1 = diction["item_1"]['amount'] detail_packs1 = diction["item_1"]['pack_products'] # produit 3 if ("item_2" in diction.keys()): if (diction["item_2"]): packs2 = diction["item_2"]['code'] qty2 = diction["item_0"]['qty'] unit_price2 = diction["item_2"]['prix'] montant2 = diction["item_2"]['amount'] detail_packs2 = diction["item_1"]['pack_products'] i = 0 while (i < nb_line): row = "item_" + str(i) #print(" product = "+ str(diction[str(row)])) i = i + 1 receiver = [str(account_mail)] toaddrs = ",".join(receiver) #print(" mail enoye à toaddrs : " + toaddrs) #print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur msg = MIMEMultipart("alternative") msg['Subject'] = '[MySy Training]: votre compte PRO est pret' msg['From'] = 'contact@mysy-training.com' msg['To'] = str(toaddrs) msg['Bcc'] = 'contact@mysy-training.com' to = [{"email": str(account_mail)}] #print(" ############# to = "+str(to)) bcc = [{"email": "contact@mysy-training.com"}] send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=22, params={"order_id": order_id, "date_order": date_order, "total_ht": total_ht, "tva": tva, "total_ttc": total_ttc, "client_name": client_name, "client_address": client_address, "client_zip_ville": client_zip_ville, "client_pays": client_pays, "packs": packs, "detail_packs": detail_packs, "qty": qty, "unit_price": unit_price, "montant":montant, "end_date": my_end_date, }, to=to, bcc=bcc) api_response = api_instance.send_transac_email(send_smtp_email) print(api_response) return True except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False """ Cette fonction envoi les factures OLD """ def SendInvoiceEmail_Old(account_mail, diction): try: ''' Verification des données obligatoires ''' ''' Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, On controle que les champs obligatoires sont presents dans la liste ''' field_list_obligatoire = ['invoice_nom', 'invoice_adr_street', 'invoice_adr_zip', 'invoice_adr_city', 'invoice_adr_country', 'invoice_id', 'invoice_date', 'due_date', 'order_id', 'item_0', 'total_ht', 'total_tva', 'total_ttc', ] 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 la liste des arguments ") return False, " Impossible d'envoyer la facture par email" order_id = diction['order_id'] date_order = diction['order_date'] client_name = str(diction['invoice_nom']) client_address= str(diction['invoice_adr_street']) client_zip_ville = str(diction['invoice_adr_zip']) + " " + str(diction['invoice_adr_city']) client_pays = str(diction['invoice_adr_country']) invoice_id = str(diction['invoice_id']) invoice_date = str(diction['invoice_date']) due_date = str(diction['due_date']) orign_order = str(diction['order_id']) packs = str(diction['item_0']['code']) qty = str(diction['item_0']['qty']) unit_price = str(diction['item_0']['prix']) montant = str(diction['item_0']['amount']) total_ht = str(diction['total_ht']) tva = str(diction['total_tva']) total_ttc = str(diction['total_ttc']) my_end_date = "" if ("end_date" in diction.keys()): if diction.keys(): my_end_date = "*Offre valable jusqu'au "+str(diction['end_date']) nb_line = mycommon.tryInt(diction['nb_product']) if( nb_line == 0 ): mycommon.myprint(str(inspect.stack()[0][3]) + " - nb_line = '" + nb_line + "' : Aucun produit à facturer") return False, " Impossible d'envoyer l'email de confirmation" #print("Facture client_name = "+str(client_name)) #print("Facture client_address = " + str(client_address)) #print("Facture client_zip_ville = " + str(client_zip_ville)) #print("Facture client_pays = " + str(client_pays)) #print("Facture order_id = " + str(order_id)) #print("Facture date_order = " + str(date_order)) #print("Facture nb_line = " + str(nb_line)) #print("Facture End Date = " + str(my_end_date)) # Recuperation des produits (max 3 produits) # produit 1 if ("item_0" in diction.keys()): if( diction["item_0"] ): packs = diction["item_0"]['code'] qty = diction["item_0"]['qty'] unit_price = diction["item_0"]['prix'] montant = diction["item_0"]['amount'] detail_packs = diction["item_0"]['pack_products'] #print("diction['item_0']['pack_products'] = "+str(diction["item_0"]['pack_products'])) # produit 2 if ("item_1" in diction.keys()): if (diction["item_1"]): packs1 = diction["item_1"]['code'] qty1 = diction["item_0"]['qty'] unit_price1 = diction["item_1"]['prix'] montant1 = diction["item_1"]['amount'] detail_packs1 = diction["item_1"]['pack_products'] # produit 3 if ("item_2" in diction.keys()): if (diction["item_2"]): packs2 = diction["item_2"]['code'] qty2 = diction["item_0"]['qty'] unit_price2 = diction["item_2"]['prix'] montant2 = diction["item_2"]['amount'] detail_packs2 = diction["item_1"]['pack_products'] i = 0 while (i < nb_line): row = "item_" + str(i) #print(" product = "+ str(diction[str(row)])) i = i + 1 receiver = [str(account_mail)] toaddrs = ",".join(receiver) #print("Facture mail enoye à toaddrs : " + toaddrs) #print("Facture debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur msg = MIMEMultipart("alternative") msg['Subject'] = '[MySy Training]: votre compte PRO est pret' msg['From'] = 'contact@mysy-training.com' msg['To'] = str(toaddrs) msg['Bcc'] = 'contact@mysy-training.com' to = [{"email": str(account_mail)}] #print(" Facture ############# to = "+str(to)) bcc = [{"email": "contact@mysy-training.com"}] send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=23, params={"order_id": order_id, "date_order": date_order, "total_ht": total_ht, "tva": tva, "total_ttc": total_ttc, "client_name": client_name, "client_address": client_address, "client_zip_ville": client_zip_ville, "client_pays": client_pays, "packs": packs, "detail_packs": detail_packs, "qty": qty, "unit_price": unit_price, "montant":montant, "invoice_id":invoice_id, "invoice_date":invoice_date, "due_date":due_date, "orign_order":orign_order, }, to=to, bcc=bcc) api_response = api_instance.send_transac_email(send_smtp_email) #print("Facture "+str(api_response)) return True except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False """ Email generic pour se subsituer sendinblu """ def MysyGenericEmail( ): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") mail_recever = "billardman01@hotmail.com" mail_object = " new mysy email" mail_message = " le message : corps du mail " smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur #msg = MIMEMultipart("alternative") msg = EmailMessage() msg['Subject'] = '[MySy Training Technology] : ' + str(mail_object) msg['From'] = "cbalde@mysy-training.com" msg['To'] = str(mail_recever) """ html = '''

Mysy Training Logo

Bonjour
Message de MySy-Training Technology .
ici le message de cherif
{mymessage}
'''.format(mymessage=mail_message) """ msg.set_content('''
Mysy Training Logo

Article 1

Lorem ipsum dolor sit amet consectetur, adipisicing elit. A ducimus deleniti nemo quibusdam iste sint!

Read more
''', subtype='html') #html_mime = MIMEText(html, 'html') # msg.attach(texte_mime) #msg.attach(html_mime) 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("html_mime =" + str(html)) toaddr = str(mail_recever) cc = ['cbalde@mysy-training.com'] toaddrs = [toaddr] + cc # msg.attach(MIMEText(open(filename).read())) with smtplib.SMTP(smtp_address, port) as server: server.starttls() # Secure the connection server.login(user, password) server.sendmail(sender, toaddrs, msg.as_string()) mycommon.myprint("mail successfully sent to " + str(toaddrs)) """ return True, "mail envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer le mail" """ envoie email avec template """ def MysyGenericEmail_tpl(): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") mail_recever = "billardman01@hotmail.com,cherif.balde@yahoo.fr,cbalde@mysy-training.com" mail_object = " new mysy email" mail_message = " le message : corps du mail " smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur # msg = MIMEMultipart("alternative") msg = EmailMessage() msg['Subject'] = '[MySy Training Technology] : ' + str(mail_object) msg['From'] = "cbalde@mysy-training.com" msg['To'] = str(mail_recever) # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/tpl_mail_test.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "user": {"nom":"BALDE", "prenom":"sekou"}, "session": {"title":"le titre", "date_du": "01/01/01", "date_fin": "02/02/02"} } sourceHtml = template.render(user=body["user"], session=body["session"]) print('### sourceHtml = '+str(sourceHtml)) # END JINJA msg.set_content(sourceHtml, subtype='html') # html_mime = MIMEText(html, 'html') # msg.attach(texte_mime) # msg.attach(html_mime) 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("html_mime =" + str(html)) toaddr = str(mail_recever) cc = ['cbalde@mysy-training.com'] toaddrs = [toaddr] + cc # msg.attach(MIMEText(open(filename).read())) with smtplib.SMTP(smtp_address, port) as server: server.starttls() # Secure the connection server.login(user, password) server.sendmail(sender, toaddrs, msg.as_string()) mycommon.myprint("mail successfully sent to " + str(toaddrs)) """ return True, "mail envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer le mail" """ Envoie de l'email de commande avec un template local """ def MysyOrderEmail_tpl(): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") mail_recever = "billardman01@hotmail.com,cherif.balde@yahoo.fr,cbalde@mysy-training.com" mail_object = " new mysy email" mail_message = " le message : corps du mail " smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) print("debut envoi mail de test ") # 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_Sales_Order_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params": {"client_name":"BALDE", "client_address":"sekou", "client_zip_ville": "sekou", "client_pays": "sekou", "order_id": "sekou", "date_order": "sekou", "packs": "sekou", "qty": "sekou", "unit_price": "sekou", "montant": "sekou", "detail_packs": "sekou", "total_ht": "sekou", "tva": "sekou", "montant": "sekou", }, "user":{"nom":"balde", "prenom":"sekou"}, } sourceHtml = template.render(params=body["params"], user=body["user"]) msg.set_content(sourceHtml, subtype='html') msg['Subject'] = "[MySy Training] : Confirmation commande N°1222" msg['From'] = "cbalde@mysy-training.com" msg['To'] = str(mail_recever) # html_mime = MIMEText(html, 'html') # msg.attach(texte_mime) # msg.attach(html_mime) 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("html_mime =" + str(html)) toaddr = str(mail_recever) cc = ['cbalde@mysy-training.com'] toaddrs = [toaddr] + cc # msg.attach(MIMEText(open(filename).read())) with smtplib.SMTP(smtp_address, port) as server: server.starttls() # Secure the connection server.login(user, password) server.sendmail(sender, toaddrs, msg.as_string()) mycommon.myprint("mail successfully sent to " + str(toaddrs)) """ return True, "mail envoyé" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer le mail" ''' Cette fonction envoie l'email de confirmation de la commande de vente ''' def SalesOrderConfirmationEmail(account_mail, diction): try: """ Liste des champs autorisés """ field_list= ['invoice_nom', 'periodicite', 'total_ht', 'total_tva', 'total_ttc', 'order_id', 'date_update', 'nb_product', 'order_date', 'discount_code', 'discount_type', 'discount_valeur', 'discount_montant_remise'] ''' Verification des données obligatoires ''' ''' Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, On controle que les champs obligatoires sont presents dans la liste ''' if(len(str(account_mail).strip()) == 0 ): mycommon.myprint(str(inspect.stack()[0][3]) + " - La valeur '" + str(account_mail) + "' est vide ") return False, " Impossible d'envoyer l'email de confirmation. l'adresse email est vide" field_list_obligatoire = ['invoice_nom', 'periodicite', 'total_ht', 'total_tva', 'total_ttc', 'order_id', 'date_update', 'nb_product', 'order_date'] 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 la liste des arguments ") return False, " Impossible d'envoyer l'email de confirmation" total_ht = diction['total_ht'] tva = diction['total_tva'] total_ttc = diction['total_ttc'] client_name = diction['invoice_nom'] client_address = diction['invoice_adr_street'] client_zip_ville = diction['invoice_adr_zip']+" "+diction['invoice_adr_city'] client_pays = diction['invoice_adr_country'] order_id = diction['order_id'] date_order = diction['order_date'] discount_code = "" if ("discount_code" in diction.keys()): if diction['discount_code']: discount_code = diction['discount_code'] discount_type = "" if ("discount_type" in diction.keys()): if diction['discount_type']: discount_type = diction['discount_type'] discount_valeur = "" if ("discount_valeur" in diction.keys()): if diction['discount_valeur']: discount_valeur = diction['discount_valeur'] discount_montant_remise = "" if ("discount_montant_remise" in diction.keys()): if diction['discount_montant_remise']: discount_montant_remise = diction['discount_montant_remise'] my_end_date = "" if ("end_date" in diction.keys()): if diction.keys(): my_end_date = "*Offre valable jusqu'au "+str(diction['end_date']) nb_line = mycommon.tryInt(diction['nb_product']) if( nb_line == 0 ): mycommon.myprint(str(inspect.stack()[0][3]) + " - nb_line = '" + nb_line + "' : Aucun produit à facturer") return False, " Impossible d'envoyer l'email de confirmation" # Recuperation des produits (max 3 produits) # produit 1 if ("item_0" in diction.keys()): if( diction["item_0"] ): packs = diction["item_0"]['code'] qty = diction["item_0"]['qty'] unit_price = diction["item_0"]['prix'] montant = diction["item_0"]['amount'] detail_packs = diction["item_0"]['pack_products'] #print("diction['item_0']['pack_products'] = "+str(diction["item_0"]['pack_products'])) # produit 2 if ("item_1" in diction.keys()): if (diction["item_1"]): packs1 = diction["item_1"]['code'] qty1 = diction["item_0"]['qty'] unit_price1 = diction["item_1"]['prix'] montant1 = diction["item_1"]['amount'] detail_packs1 = diction["item_1"]['pack_products'] # produit 3 if ("item_2" in diction.keys()): if (diction["item_2"]): packs2 = diction["item_2"]['code'] qty2 = diction["item_0"]['qty'] unit_price2 = diction["item_2"]['prix'] montant2 = diction["item_2"]['amount'] detail_packs2 = diction["item_1"]['pack_products'] i = 0 while (i < nb_line): row = "item_" + str(i) #print(" product = "+ str(diction[str(row)])) i = i + 1 receiver = [str(account_mail)] toaddrs = ",".join(receiver) # on rentre les renseignements pris sur le site du fournisseur #---------- mail_recever = str(toaddrs) smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur discount_display_text = "" if( discount_type == "fix"): discount_display_text = " -"+str(discount_valeur)+" €" elif( discount_type == "percent"): discount_display_text = " -"+str(discount_valeur)+" %" # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Sales_Order_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params": {"order_id": order_id, "date_order": date_order, "total_ht": total_ht, "tva": tva, "total_ttc": total_ttc, "client_name": client_name, "client_email":str(account_mail), "client_address": client_address, "client_zip_ville": client_zip_ville, "client_pays": client_pays, "packs": packs, "detail_packs": detail_packs, "qty": qty, "unit_price": unit_price, "montant": montant, "end_date": my_end_date, "discount_montant_remise": discount_montant_remise, "discount_code": discount_code, "discount_type": discount_type, "discount_valeur": discount_valeur, "discount_display_text": discount_display_text, }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['Subject'] = "[MySy Training] : Confirmation commande N°"+str(order_id) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(mail_recever) msg['Bcc'] = 'contact@mysy-training.com' msg.add_attachment('./Template/MySy_CGV.pdf') with open('./Template/MySy_CGV.pdf', 'rb') as content_file: content = content_file.read() msg.add_attachment(content, maintype='application', subtype='pdf', filename='MySy_CGV.pdf') # html_mime = MIMEText(html, 'html') # msg.attach(texte_mime) # msg.attach(html_mime) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) smtpserver.send_message(msg) smtpserver.close() return True, " Creation commande OK" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " Impossible de créer la commande " """ Envoi du nouvel email de creation de compte avec mes propres template """ def send_user_account_mail(message, account_mail): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://apimysy.mysy-training.com/myclass/api/valide_user_account/"+str(message) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:"+str(MYSY_GV.MYSY_PORT_DEV)+"/myclass/api/valide_user_account/"+str(message) elif (MYSY_GV.MYSY_ENV == "REC"): my_url = "https://devapimysy.mysy-training.com/myclass/api/valide_user_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEM"): my_url = "https://demoapi.mysy-training.com/myclass/api/valide_user_account/" + str(message) smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) print("debut envoi mail de test ") # 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_Create_User_account_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params": {"mysyurl": my_url, "user_name": str(account_mail), "id": "122CSR_id"}, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['Subject'] = '[MySy Training] : Activez votre compte ' msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(account_mail) to = [{"email": str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] 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 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 " """ Creation du compte PRO avec mes template """ def send_partner_account_mail(message, account_mail): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") receiver = [str(account_mail)] toaddrs = ",".join(receiver) my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://apimysy.mysy-training.com/myclass/api/valide_partnair_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:"+str(MYSY_GV.MYSY_PORT_DEV)+"/myclass/api/valide_partnair_account/"+str(message) elif (MYSY_GV.MYSY_ENV == "REC"): my_url = "https://devapimysy.mysy-training.com/myclass/api/valide_partnair_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEM"): my_url = "https://demoapi.mysy-training.com/myclass/api/valide_partnair_account/" + str(message) smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) print("debut envoi mail de test ") # 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_Create_PRO_account_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params": {"mysyurl": my_url, "user_name": str(account_mail), } } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['Subject'] = '[MySy Training]: activation de votre compte PRO' msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(toaddrs) msg['Bcc'] = 'contact@mysy-training.com' to = [{"email": str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] 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 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" ''' Apres l'activation du compte pro, cet email envoie le token et mot de passe temporaire à l'utilisateur /!\ : update du 27/09/2023 : Apres l'activation du compte, il faut créer l'employé rattaché à cet utilisateur ''' def Pro_Account_Token_Pass(account_mail, my_token): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") receiver = [str(account_mail)] toaddrs = ",".join(receiver) print(" mail enoye à toaddrs : " + toaddrs) print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur """send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=18, params={"user_name": str(account_mail), "secrete":str(my_token) }, to=to, bcc=bcc) """ smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() url_environnement = MYSY_GV.CLIENT_URL_BASE # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_account_pro_enabled_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"user_name": str(account_mail), "secrete": str(my_token), "url_connexion":str(url_environnement)} } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['Subject'] = '[MySy Training]: votre compte PRO est pret' cle = my_token msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['To'] = str(toaddrs) msg['Bcc'] = 'contact@mysy-training.com' to = [{"email": str(account_mail)}] bcc = [{"email": "contact@mysy-training.com"}] 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)) """ Update du 27/09/2023 : Apres activation du compte pro, on va créer l'employé rattaché à ce compte """ # Recuperation des données du partner my_partner = MYSY_GV.dbname['partnair_account'].find_one({'email':str(account_mail)}) if( my_partner is None): mycommon.myprint(" WARNING : Impossible de recuperer les données du partner. Impossible de créer le compte employé de l'administrateur") return True data_employe_admin = {} data_employe_admin['partner_recid'] = str(my_partner['recid']) data_employe_admin['nom'] = str(my_partner['nom']) data_employe_admin['email'] = str(account_mail) data_employe_admin['comment'] = "Compte Administrateur" data_employe_admin['is_partner_admin_account'] = "1" data_employe_admin['account_partner_id'] = str(my_partner['_id']) print(" #### data_employe_admin = ", str(data_employe_admin)) local_status, local_retval_inserted_id = ressources_humaines.Add_Partner_Admin_Ressource_Humaine_No_Toke(data_employe_admin) if( local_status is False): mycommon.myprint(str(local_retval_inserted_id)) return True return True except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False """ Email d'info apres activation du compte utilisateur """ def send_user_thks_mail(message, account_mail): 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 my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://apimysy.mysy-training.com/myclass/api/valide_user_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:"+str(MYSY_GV.MYSY_PORT_DEV)+"/myclass/api/valide_user_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "REC"): my_url = "https://devapimysy.mysy-training.com/myclass/api/valide_user_account/" + str(message) elif (MYSY_GV.MYSY_ENV == "DEM"): my_url = "https://demoapi.mysy-training.com/myclass/api/valide_user_account/" + str(message) """ send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=16, params={ "user_name": str(account_mail),}, to=to, bcc=bcc ) """ smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_User_account_enabled_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"user_name": str(account_mail), } } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = '[MySy Training]: Votre compte est actif ' msg['To'] = str(account_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 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 " """ Mail de reinitialisation de mot de passe """ def send_user_init_pwd_mail(token, account_mail, type_account): 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 my_url = "" if (MYSY_GV.MYSY_ENV == "PROD"): my_url = "https://www.mysy-training.com/ResetUserPwd/" + str(token)+"/"+str(type_account) elif (MYSY_GV.MYSY_ENV == "DEV"): my_url = "http://localhost:3009/ResetUserPwd/" + str(token)+"/"+str(type_account) elif (MYSY_GV.MYSY_ENV == "REC"): my_url = "https://dev.mysy-training.com/ResetUserPwd/" + str(token) + "/" + str(type_account) elif (MYSY_GV.MYSY_ENV == "DEM"): my_url = "https://demo.mysy-training.com/ResetUserPwd/" + str(token) + "/" + str(type_account) """send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(template_id=19, params={"mysyurl": my_url, "user_name": str(account_mail), }, to=to, bcc=bcc ) """ smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_User_account_change_pwd_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"mysyurl": my_url, "user_name": str(account_mail), }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = '[MySy Training Technology] : Reinitialisez votre mot de passe' msg['To'] = str(account_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 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 la demande d'information sur une formation """ def EmailDemandeInfoClass( diction): 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 smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Demande_Info_Class_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) local_status, my_partner = mycommon.Get_Connected_User_Partner_Data_From_RecID(str(diction['partner_owner_recid'])) if (local_status is not True): return local_status, my_partner # Creation du dictionnaire d'information à utiliser pour la creation du doc convention_dictionnary_data = {} new_diction = {} new_diction['token'] = my_partner['token'] new_diction['list_stagiaire_id'] = [] new_diction['list_session_id'] = [] new_diction['list_class_id'] = [] new_diction['list_client_id'] = [] local_status, local_retval = mycommon.Get_Dictionnary_data_For_Template(new_diction) if (local_status is False): return local_status, local_retval convention_dictionnary_data = local_retval new_node = {"nom": str(diction['nom']), "prenom": str(diction['prenom']), "email": str(diction['email']), "email_partnair": str(diction['email_partnair']), "class_title": str(diction['class_title']), "telephone": str(diction['telephone']), "employeur": str(diction['employeur']), "message": str(diction['message']), "class_internal_url": str(diction['class_internal_url']), } convention_dictionnary_data['data_from_site'] = new_node body_company_data = { "params": convention_dictionnary_data, } """ Recuperer le modèle de courrier """ courrier_template_data = None is_courrier_template_id_valide = MYSY_GV.dbname['courrier_template'].count_documents( {'ref_interne': 'CLASS_INFO_REQUEST', 'valide': '1', 'type_doc': 'email', 'locked': '0', 'partner_owner_recid': str(diction['partner_owner_recid'])} ) if( is_courrier_template_id_valide == 1): courrier_template_data = MYSY_GV.dbname['courrier_template'].find_one( {'ref_interne': 'CLASS_INFO_REQUEST', 'valide': '1', 'type_doc': 'email', 'locked': '0', 'partner_owner_recid': str(diction['partner_owner_recid'])} ) else: is_courrier_template_id_valide = MYSY_GV.dbname['courrier_template'].count_documents( {'ref_interne': 'CLASS_INFO_REQUEST', 'valide': '1', 'type_doc': 'email', 'locked': '0', 'partner_owner_recid': 'default'} ) if( is_courrier_template_id_valide != 1 ): mycommon.myprint(str(inspect.stack()[0][3]) + " Impossible de récupérer le modèle de courrier 'CLASS_INFO_REQUEST' ") return False, " Impossible de récupérer le modèle de courrier 'CLASS_INFO_REQUEST' " else: courrier_template_data = MYSY_GV.dbname['courrier_template'].find_one( {'ref_interne': 'CLASS_INFO_REQUEST', 'valide': '1', 'type_doc': 'email', 'locked': '0', 'partner_owner_recid': 'default'} ) if( courrier_template_data is None ): mycommon.myprint( str(inspect.stack()[0][3]) + " Impossible de récupérer le modèle de courrier 'CLASS_INFO_REQUEST' (2) ") return False, " Impossible de récupérer le modèle de courrier 'CLASS_INFO_REQUEST' (2) " sujet_doc_Template = jinja2.Template(str(courrier_template_data['sujet'])) sujetHtml = sujet_doc_Template.render(params=body_company_data["params"]) contenu_doc_Template = jinja2.Template(str(courrier_template_data['contenu_doc'])) sourceHtml = contenu_doc_Template.render(params=body_company_data['params']) html_mime = MIMEText(sourceHtml, 'html') # Creation de l'email à enoyer msg = MIMEMultipart("alternative") msg.attach(html_mime) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = sujetHtml msg['To'] = str(diction['email_partnair']) 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 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 la demande d'information sur une formation avec bouton de creation de devis Ceci n'est valide que pour les entreprises (voir champ : 'is_company') """ def EmailDemandeInfoClass_For_Cpny_With_Quotation_Option( diction): try: field_list_obligatoire = ['is_company', 'raison_sociale', 'siret', 'email_requester', 'telephone_requester', 'nom_requester', 'prenom_requester', 'nb_person_info', 'lead_website_id', '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 la liste des arguments ") return False, " : La valeur '" + val + "' n'est pas presente dans la liste des arguments " 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 smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) local_status, my_partner = mycommon.Get_Connected_User_Partner_Data_From_RecID(str(diction['partner_owner_recid'])) if (local_status is not True): return local_status, my_partner # Creation du dictionnaire d'information à utiliser pour la creation du doc convention_dictionnary_data = {} new_diction = {} new_diction['token'] = my_partner['token'] new_diction['list_stagiaire_id'] = [] new_diction['list_session_id'] = [] new_diction['list_class_id'] = [] new_diction['list_client_id'] = [] local_status, local_retval = mycommon.Get_Dictionnary_data_For_Template(new_diction) if (local_status is False): return local_status, local_retval convention_dictionnary_data = local_retval new_node = {"raison_sociale": str(diction['raison_sociale']), "siret": str(diction['siret']), "email_requester": str(diction['email_requester']), "email_partnair": str(diction['email_partnair']), "telephone_requester": str(diction['telephone_requester']), "nom_requester": str(diction['nom_requester']), "prenom_requester": str(diction['prenom_requester']), "nb_person_info": str(diction['nb_person_info']), "message": str(diction['message']), "class_internal_url": str(diction['class_internal_url']), 'mysyurl':MYSY_GV.CLIENT_URL_BASE+"automatic-quotation/"+str(diction['partner_owner_recid'])+"/"+ str(diction['lead_website_id'])+"/" } convention_dictionnary_data['data_from_site'] = new_node body_company_data = { "params": convention_dictionnary_data, } """ Recuperer le modèle de courrier """ courrier_template_data = None is_courrier_template_id_valide = MYSY_GV.dbname['courrier_template'].count_documents( {'ref_interne': 'CLASS_INFO_REQUEST', 'valide': '1', 'type_doc': 'email', 'locked': '0', 'partner_owner_recid': str(diction['partner_owner_recid'])} ) if( is_courrier_template_id_valide == 1): courrier_template_data = MYSY_GV.dbname['courrier_template'].find_one( {'ref_interne': 'CLASS_INFO_REQUEST_WITH_QUOTATION', 'valide': '1', 'type_doc': 'email', 'locked': '0', 'partner_owner_recid': str(diction['partner_owner_recid'])} ) else: is_courrier_template_id_valide = MYSY_GV.dbname['courrier_template'].count_documents( {'ref_interne': 'CLASS_INFO_REQUEST_WITH_QUOTATION', 'valide': '1', 'type_doc': 'email', 'locked': '0', 'partner_owner_recid': 'default'} ) if( is_courrier_template_id_valide != 1 ): mycommon.myprint(str(inspect.stack()[0][3]) + " Impossible de récupérer le modèle de courrier 'CLASS_INFO_REQUEST_WITH_QUOTATION' ") return False, " Impossible de récupérer le modèle de courrier 'CLASS_INFO_REQUEST_WITH_QUOTATION' " else: courrier_template_data = MYSY_GV.dbname['courrier_template'].find_one( {'ref_interne': 'CLASS_INFO_REQUEST_WITH_QUOTATION', 'valide': '1', 'type_doc': 'email', 'locked': '0', 'partner_owner_recid': 'default'} ) if( courrier_template_data is None ): mycommon.myprint( str(inspect.stack()[0][3]) + " Impossible de récupérer le modèle de courrier 'CLASS_INFO_REQUEST_WITH_QUOTATION' (2) ") return False, " Impossible de récupérer le modèle de courrier 'CLASS_INFO_REQUEST_WITH_QUOTATION' (2) " sujet_doc_Template = jinja2.Template(str(courrier_template_data['sujet'])) sujetHtml = sujet_doc_Template.render(params=body_company_data["params"]) contenu_doc_Template = jinja2.Template(str(courrier_template_data['contenu_doc'])) sourceHtml = contenu_doc_Template.render(params=body_company_data["params"]) html_mime = MIMEText(sourceHtml, 'html') # Creation de l'email à enoyer msg = MIMEMultipart("alternative") msg.attach(html_mime) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = sujetHtml msg['To'] = str(diction['email_partnair']) 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 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 envoi les factures """ def SendInvoiceEmail(account_mail, diction): try: ''' Verification des données obligatoires ''' ''' Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, On controle que les champs obligatoires sont presents dans la liste ''' field_list_obligatoire = ['invoice_nom', 'invoice_adr_street', 'invoice_adr_zip', 'invoice_adr_city', 'invoice_adr_country', 'invoice_id', 'invoice_date', 'due_date', 'order_id', 'item_0', 'total_ht', 'total_tva', 'total_ttc', 'client_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 la liste des arguments ") return False, " Impossible d'envoyer la facture par email" order_id = diction['order_id'] date_order = diction['order_date'] client_name = str(diction['invoice_nom']) client_address= str(diction['invoice_adr_street']) client_zip_ville = str(diction['invoice_adr_zip']) + " " + str(diction['invoice_adr_city']) client_pays = str(diction['invoice_adr_country']) invoice_id = str(diction['invoice_id']) invoice_date = str(diction['invoice_date']) due_date = str(diction['due_date']) orign_order = str(diction['order_id']) packs = str(diction['item_0']['code']) qty = str(diction['item_0']['qty']) unit_price = str(diction['item_0']['prix']) montant = str(diction['item_0']['amount']) total_ht = str(diction['total_ht']) tva = str(diction['total_tva']) total_ttc = str(diction['total_ttc']) my_end_date = "" if ("end_date" in diction.keys()): if diction.keys(): my_end_date = "*Offre valable jusqu'au "+str(diction['end_date']) discount_code = "" if ("discount_code" in diction.keys()): if diction['discount_code']: discount_code = diction['discount_code'] discount_type = "" if ("discount_type" in diction.keys()): if diction['discount_type']: discount_type = diction['discount_type'] discount_valeur = "" if ("discount_valeur" in diction.keys()): if diction['discount_valeur']: discount_valeur = diction['discount_valeur'] discount_montant_remise = "" if ("discount_montant_remise" in diction.keys()): if diction['discount_montant_remise']: discount_montant_remise = diction['discount_montant_remise'] nb_line = mycommon.tryInt(diction['nb_product']) if( nb_line == 0 ): mycommon.myprint(str(inspect.stack()[0][3]) + " - nb_line = '" + nb_line + "' : Aucun produit à facturer") return False, " Impossible d'envoyer l'email de confirmation" #print("Facture client_name = "+str(client_name)) #print("Facture client_address = " + str(client_address)) #print("Facture client_zip_ville = " + str(client_zip_ville)) #print("Facture client_pays = " + str(client_pays)) #print("Facture order_id = " + str(order_id)) #print("Facture date_order = " + str(date_order)) #print("Facture nb_line = " + str(nb_line)) #print("Facture End Date = " + str(my_end_date)) # Recuperation des produits (max 3 produits) # produit 1 if ("item_0" in diction.keys()): if( diction["item_0"] ): packs = diction["item_0"]['code'] qty = diction["item_0"]['qty'] unit_price = diction["item_0"]['prix'] montant = diction["item_0"]['amount'] detail_packs = diction["item_0"]['pack_products'] #print("diction['item_0']['pack_products'] = "+str(diction["item_0"]['pack_products'])) # produit 2 if ("item_1" in diction.keys()): if (diction["item_1"]): packs1 = diction["item_1"]['code'] qty1 = diction["item_0"]['qty'] unit_price1 = diction["item_1"]['prix'] montant1 = diction["item_1"]['amount'] detail_packs1 = diction["item_1"]['pack_products'] # produit 3 if ("item_2" in diction.keys()): if (diction["item_2"]): packs2 = diction["item_2"]['code'] qty2 = diction["item_0"]['qty'] unit_price2 = diction["item_2"]['prix'] montant2 = diction["item_2"]['amount'] detail_packs2 = diction["item_1"]['pack_products'] i = 0 while (i < nb_line): row = "item_" + str(i) #print(" product = "+ str(diction[str(row)])) i = i + 1 receiver = [str(account_mail)] toaddrs = ",".join(receiver) #print("Facture mail enoye à toaddrs : " + toaddrs) #print("Facture debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur 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 smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() discount_display_text = "" if( discount_type == "fix"): discount_display_text = " -"+str(discount_valeur)+" €" elif( discount_type == "percent"): discount_display_text = " -"+str(discount_valeur)+" %" # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Invoice_tpl.html" print(" ############ TEMPLATE_FILE = "+str(TEMPLATE_FILE)) template = templateEnv.get_template(TEMPLATE_FILE) body = { "params": {"order_id": order_id, "date_order": date_order, "total_ht": total_ht, "tva": tva, "total_ttc": total_ttc, "client_name": client_name, "client_address": client_address, "client_zip_ville": client_zip_ville, "client_pays": client_pays, "packs": packs, "detail_packs": detail_packs, "qty": qty, "unit_price": unit_price, "montant": montant, "invoice_id": invoice_id, "invoice_date": invoice_date, "due_date": due_date, "orign_order": orign_order, "discount_montant_remise": discount_montant_remise, "discount_code": discount_code, "discount_type": discount_type, "discount_valeur": discount_valeur, "discount_display_text": discount_display_text, } } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Votre facture N° "+str(invoice_id) msg['To'] = str(toaddrs) 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 except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False """ Cette fonction envoi une demande de validation de presence à une formation. C'est l'emargement electronique """ def SendEmargementMail( diction): try: field_list_obligatoire = ['token', 'tab_ids'] 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 la liste des arguments ") return False, " Impossible d'envoyer les emails d'emargement" my_token = "" if ("token" in diction.keys()): if diction['token']: my_token = diction['token'] local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction) if (local_status is not True): return local_status, my_partner # Verifier la validité du token retval = mycommon.check_partner_token_validity("", my_token) if retval is False: return "Err_Connexion", " La session de connexion n'est pas valide" my_emarge_ids = "" if ("tab_ids" in diction.keys()): if diction['tab_ids']: my_emarge_ids = diction['tab_ids'] partner_recid = mycommon.get_parnter_recid_from_token(my_token) if (partner_recid is False): mycommon.myprint(str(inspect.stack()[0][3]) + " - partner_recid est KO ") return False, "Impossible d'envoyer les emails d'emargement " tab_my_emarge_ids = str(my_emarge_ids).split(",") for my_emarge_id in tab_my_emarge_ids : # Recuperation des infos de l'emargement #print("my_emarge_id = " + str(my_emarge_id)) val_emarge = MYSY_GV.dbname['emargement'].find_one({'_id':ObjectId(my_emarge_id), 'partner_owner_recid':str(partner_recid)}) # recuperation du titre de la formation local_class_title = MYSY_GV.dbname['myclass'].find_one({'internal_url':str(val_emarge['class_internal_url']), 'partner_owner_recid':str(partner_recid), 'valide':'1', 'locked':'0'}) if( local_class_title is None): mycommon.myprint(str(inspect.stack()[0][3]) + " - Aucune formation valide ") return False, " La formation n'est pas valide" # recuperation du titre de la session local_session_data = MYSY_GV.dbname['session_formation'].find_one( {'_id': ObjectId(str(val_emarge['session_id'])), 'partner_owner_recid': str(partner_recid), 'valide': '1',}) if (local_session_data is None): mycommon.myprint(str(inspect.stack()[0][3]) + " - Aucune session valide ") return False, " La session de formation n'est pas valide" print("debut envoi mail de test ") # on rentre les renseignements pris sur le site du fournisseur smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Emargement.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query # envoie de l'emargement du matin #myurl = "http://127.0.0.1:5001/myclass/api/UserEmargementValidation/"+str(val_emarge['_id'])+"/1" if (MYSY_GV.MYSY_ENV == "PROD"): myurl = "https://apimysy.mysy-training.com/myclass/api/UserEmargementValidation/" + str(val_emarge['_id']) + "/1" elif (MYSY_GV.MYSY_ENV == "DEV"): myurl = "http://127.0.0.1:5001/myclass/api/UserEmargementValidation/"+str(val_emarge['_id'])+"/1" elif (MYSY_GV.MYSY_ENV == "REC"): myurl = "https://devapimysy.mysy-training.com/myclass/api/UserEmargementValidation/" + str(val_emarge['_id']) + "/1" elif (MYSY_GV.MYSY_ENV == "DEM"): myurl = "https://demoapi.mysy-training.com/myclass/api/UserEmargementValidation/" + str(val_emarge['_id']) + "/1" body = { "params":{"nom": str(val_emarge['nom']), "prenom": str(val_emarge['prenom']), "email": str(val_emarge['email']), "class_title": str(local_class_title['title']), "date": str(val_emarge['date']), "session": str(val_emarge['sequence_start'])+" - "+str(val_emarge['sequence_end']), "code_session":str(local_session_data['code_session']), "mysyurl": str(myurl), }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Emargement "+str(val_emarge['sequence_start'])+" - "+str(val_emarge['sequence_end']) msg['To'] = str(val_emarge['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() """ 25/01/2024 : Apres l'envoi de la demande d'emargement, on log une action dans la collection ==> courrier_template_tracking_history """ local_inscription_id = "" if( "inscription_id" in val_emarge.keys() ): local_inscription_id = str(val_emarge['inscription_id']) local_status, local_retval = module_editique.Editic_Log_History_Action_From_courrier_template_type_document_ref_interne( my_partner, "EMARGEMENT_FORMATION", str(val_emarge['session_id']), "inscription", local_inscription_id, "" ) """ 31/01/2024 : A présent que la demande d'émargement est envoyée, on met à jour la collection 'emargement' pour dire que la demande a été envoyé, et quel jour """ now = str(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")) updata_data = {} updata_data['date_update'] = now updata_data['update_by'] = str(my_partner['_id']) updata_data['statut'] = "1" updata_data['date_envoi'] = now MYSY_GV.dbname['emargement'].find_one_and_update({'_id':ObjectId(str(val_emarge['_id'])), 'partner_owner_recid':str(my_partner['recid'])}, {"$set": updata_data}, return_document=ReturnDocument.AFTER ) print(" Email matinée envoyé " + str(my_emarge_id)) return True, " La demande d'émargement a été correctement envoyée" 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 la demande d'émargement " """ Creation manuelle d'une facture avec RIB """ def ManualSendInvoiceEmailRIB(diction): try: ''' Verification des données obligatoires ''' ''' Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, On controle que les champs obligatoires sont presents dans la liste ''' 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 smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Invoice_RIB_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) body = { "params": {"order_id": "007G", "date_order": ": 03/04/2023", "total_ht": "171", "tva": "34,2", "total_ttc": "205,2", "client_name": "CAP SANTE", "client_address": "4 Allée des Jacquiers", "client_zip_ville": "97427 L'Etang Salé", "client_pays": "France", "packs": "PACK GOLD ", "detail_packs": "-- Support téléphonique -- " "Reporting basique -- " "Mots clés par formation -- " "Customisation de l'affichage d'une formation -- " "Préférence/ Diffusion géographique -- " "Publication d'un article -- " "Envoi de 1000 emails markéting / mois --" "Reporting Dynamique et personnalisé", "qty": "2", "unit_price": "85.5", "montant": "171", "invoice_id": "FACT_230400029", "invoice_date": "03/04/2023", "due_date": "03/04/2022", "orign_order": "Contrat 007G", } } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Votre facture N° FACT_230200020" msg['To'] = 'billardman1@gmail.com' 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)) ### CREATION DE LA FACTION PDF templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/invoice_RIB.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query """ body = { "data": { "client_name": str(diction['invoice_nom']), "client_address": str(diction['invoice_adr_street']), "client_zip_ville": str(diction['invoice_adr_zip']) + " " + str(diction['invoice_adr_city']), "client_pays": str(diction['invoice_adr_country']), "invoice_id": str(diction['invoice_id']), "invoice_date": str(diction['invoice_date']), "due_date": str(diction['due_date']), "orign_order": str(diction['order_id']), "packs": str(diction['item_0']['code']), "qty": str(diction['item_0']['qty']), "unit_price": str(diction['item_0']['prix']), "montant": str(diction['item_0']['amount']), "total_ht": str(diction['total_ht']), "tva": str(diction['total_tva']), "total_ttc": str(diction['total_ttc']), } } """ sourceHtml = template.render(json_data=body["params"]) orig_file_name = "invoice_FACT_230400029.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() return True, " facture envoyée" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " impossible d'envoyer la facure" """ Creation manuelle d'une facture avec RIB pour Port Cities - perso """ def ManualSendInvoiceEmailRIB_PortCities(diction): try: ''' Verification des données obligatoires ''' ''' Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, On controle que les champs obligatoires sont presents dans la liste ''' 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 #smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") #msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Invoice_RIB_PortCities_Perso_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) body = { "params": {"order_id": "0010G", "date_order": ": 01/06/2023", "total_ht": "3 200", "tva": "640", "total_ttc": "3 840", "client_name": "Port Cities France SAS", "client_address": "180 Av. du Prado", "client_zip_ville": "13008 Marseille", "client_pays": "France", "packs": "Chef de projet Odoo ", "detail_packs": "Avignon - Siège CAPL ", "qty": "4 jrs", "unit_price": "800 €", "montant": "3 200€", "invoice_id": "FACT_230800038", "invoice_date": "15/08/2023", "due_date": "15/08/2023", "orign_order": "Contrat N°0010G", } } #print(" ### body 1 = ", body) sourceHtml = template.render(params=body["params"]) """msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Votre facture N° FACT_230500030" msg['To'] = 'billardman1@gmail.com' 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)) ### CREATION DE LA FACTION PDF templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) #TEMPLATE_FILE = "Template/MySy_Invoice_RIB_tpl.html" TEMPLATE_FILE = "Template/invoice_RIB_PortCities_perso_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query #print(" ### body 22 = ", body) sourceHtml = template.render(json_data=body["params"]) orig_file_name = "invoice_FACT_230800038.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() return True, " facture envoyée" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, " impossible d'envoyer la facure" """ Cette fonction envoie un email pour notifier a un partenaire l'arrete d'un abonnement """ def EmailStopAbonnement( partners_email, partners_pack_service, partners_date_arret, partners_nom): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Stop_Abonnement_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"user_name": str(partners_nom), "packs": str(partners_pack_service), "end_date_abonnement": str(partners_date_arret), "email": str(partners_email), }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Arret de votre abonnement "+str(partners_pack_service) msg['To'] = str(partners_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 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 notifier à un partenaire la modification de son abonnement avec de nouvelle quantité """ def EmailChangeAbonnementQty( partners_email, partners_pack_service, partners_date_arret, partners_nom, old_qty, new_qty ): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Update_Qty_Abonnement_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"user_name": str(partners_nom), "packs": str(partners_pack_service), "end_date_abonnement": str(partners_date_arret), "email": str(partners_email), "old_qty": str(old_qty), "new_qty": str(new_qty), }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Modification de votre abonnement "+str(partners_pack_service) msg['To'] = str(partners_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 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 notifier à un partenaire la modification de son abonnement. Cas du changement de plan. par exemple : gold vers standard... """ def EmailChangeAbonnementPlan( partners_email, partners_pack_service, partners_nom, qty ): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Update_Plan_Abonnement_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"user_name": str(partners_nom), "packs": str(partners_pack_service), "email": str(partners_email), "qty": str(qty), }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Modification de votre abonnement "+str(partners_pack_service) msg['To'] = str(partners_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 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 envoie la notification d'evaluation à un institut de formation """ def EmailNotifEvaluation_Done(diction): try: tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") field_list_obligatoire = ['inscription_id', 'eval_note', 'eval_eval', 'eval_pedagogie', 'class_internal_url'] 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 la liste des arguments ") return False, " Les informations fournies sont incorrectes" note = str(diction['eval_note']).strip() if (mycommon.IsFloat(note) is False): mycommon.myprint( str(inspect.stack()[0][ 3]) + " La note d'evaluation est incorrecte ") return False, " La note d'evaluation est incorrecte " note_peda = str(diction['eval_pedagogie']).strip() if (mycommon.IsFloat(note_peda) is False): mycommon.myprint( str(inspect.stack()[0][ 3]) + " La note pédagogique est incorrecte ") return False, " La note d'pédagogique est incorrecte " # Recuperation du titre de la formation local_class = MYSY_GV.dbname['myclass'].find_one({"internal_url":diction['class_internal_url'], 'valide':'1', 'locked': '0'}) if( local_class is None ): mycommon.myprint( str(inspect.stack()[0][ 3]) + " Impossible d'envoyer la notification. La formation est introuvable ") return False, " Impossible d'envoyer la notification. La formation est introuvable " if ("title" not in local_class.keys()): mycommon.myprint( str(inspect.stack()[0][ 3]) + " Impossible d'envoyer la notification. La formation est introuvable (2) ") return False, " Impossible d'envoyer la notification. La formation est introuvable (2) " # Recuperation des données du partenaire local_partner = MYSY_GV.dbname['partnair_account'].find_one({'recid': str(local_class['partner_owner_recid'])}) if (local_partner is None): mycommon.myprint( str(inspect.stack()[0][ 3]) + " Impossible d'envoyer la notification. Le compte partenaire est introuvable ") return False, " Impossible d'envoyer la notification. Le compte partenaire est introuvable " if ("nom" not in local_partner.keys() or "email" not in local_partner.keys()): mycommon.myprint( str(inspect.stack()[0][ 3]) + " Impossible d'envoyer la notification. Le compte partenaire est introuvable (2) ") return False, " Impossible d'envoyer la notification. Le compte partenaire est introuvable (2) " # Recuperation des donnée d'inscription local_inscription = MYSY_GV.dbname['inscription'].find_one({'_id': ObjectId(str(str(diction['inscription_id']).strip())),}) if (local_inscription is None): mycommon.myprint( str(inspect.stack()[0][ 3]) + " Impossible d'envoyer la notification. L'inscription est introuvable ") return False, " Impossible d'envoyer la notification. L'inscription est introuvable " insc_nom = "" if ("nom" in local_inscription.keys()): insc_nom = local_inscription['nom'] insc_prenom = "" if ("prenom" in local_inscription.keys()): insc_prenom = local_inscription['prenom'] date_du = "" if ("date_du" in local_inscription.keys()): date_du = local_inscription['date_du'] date_au = "" if ("date_au" in local_inscription.keys()): date_au = local_inscription['nom'] partenaire_name = "" if ("nom" in local_partner.keys()): partenaire_name = local_partner['nom'] partenaire_email = "" if ("email" in local_partner.keys()): partenaire_email = local_partner['email'] eval_note = "" if ("eval_note" in local_inscription.keys()): eval_note = local_inscription['eval_note'] eval_pedagogie = "" if ("eval_pedagogie" in local_inscription.keys()): eval_pedagogie = local_inscription['eval_pedagogie'] eval_date = "" if ("eval_date" in local_inscription.keys()): eval_date = str(local_inscription['eval_date'])[0:10] eval_eval = "" if ("eval_eval" in local_inscription.keys()): eval_eval = mycommon.cleanhtml(str(local_inscription['eval_eval'])) title = "" if ("title" in local_class.keys()): title = mycommon.cleanhtml(str(local_class['title'])) smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Evaluation_Class_done_Notif_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"partenaire_name": partenaire_name, "prenom": insc_prenom, "nom": insc_nom, "date_du": date_du, "date_fin": date_au, "eval_note":eval_note, "eval_pedagogie": eval_pedagogie, "eval_eval": eval_eval, "eval_date": eval_date, "title":title }, } #print(" ### body = ", body) sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Votre formation a été évaluée " msg['To'] = partenaire_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, "ok" 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 envoie un email à partenaire avec ses identfiants de connexion à son espace hebergement de formation """ def Email_Part_Espace_Hosting( diction): try: field_list_obligatoire = ['token', ] 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 la liste des arguments ") return False, " Impossible d'envoyer les emails avec les information d'hébergement" my_token = "" if ("token" in diction.keys()): if diction['token']: my_token = diction['token'] partner_recid = mycommon.get_parnter_recid_from_token(my_token) if (partner_recid is False): mycommon.myprint(str(inspect.stack()[0][3]) + " - partner_recid est KO ") return False, "Impossible d'envoyer les emails avec les information d'hébergement " # Recuperation des données du partenaire local_status, my_partner = mycommon.get_partner_data_from_recid(partner_recid) if (local_status is False): mycommon.myprint(str(inspect.stack()[0][3]) + " - impossible de récupérer les données du partenaire") return False, str(inspect.stack()[0][3]) + " - impossible de récupérer les données du partenaire" print(" ### in Email_Part_Espace_Hosting my_partner data = ", my_partner) nom = "" if ("nom" in my_partner.keys()): nom = my_partner['nom'] mysy_pack = "" if ("pack_service" in my_partner.keys()): mysy_pack = my_partner['pack_service'] nb_formation = "" if ("nb_formation" in my_partner.keys()): nb_formation = my_partner['nb_formation'] mysy_url = MYSY_GV.CLIENT_URL_BASE lms_url = "" if ("lms_virtualhost_url" in my_partner.keys()): lms_url = my_partner['lms_virtualhost_url'] login = "" if ("lms_username" in my_partner.keys()): login = my_partner['lms_username'] print(" ### in Email_Part_Espace_Hosting login = ", login) if( login == ""): mycommon.myprint(str(inspect.stack()[0][3]) + " - Le login du partenaire est incorrecte") return False, str(inspect.stack()[0][3]) + " - Le login du partenaire est incorrecte" tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow_day = tomorrow.strftime("%A") smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Acces_Espace_Hebergement_Partner_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params":{"nom": str(nom), "mysy_pack": str(mysy_pack), "nb_formation": str(nb_formation), "lms_url": str(lms_url), "mysy_url": str(mysy_url), "login": str(login), }, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Vos identifiants de connexion à la plateforme d'hébergement. " msg['To'] = str(my_partner['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, " Les identifiants de connexion à la plateforme d'hébergement a été correctement 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 les identifiants de connexion à la plateforme d'hébergement par email " """ Cette fonction envoie un email avec les informations sur la prochaine facturation du client. Cette fonction est utilisée : 1 - En cas de changement d'abonnement 2 - eventuellement connaitre le montant de la prochaine facture du client """ import json def Strip_Get_Customer_Upcoming_Invoice(diction): try: diction = mycommon.strip_dictionary(diction) """ Verification des input acceptés """ field_list = ['recid', ] incom_keys = diction.keys() for val in incom_keys: if val not in field_list and val.startswith('my_') is False: mycommon.myprint(str( inspect.stack()[0][3]) + " Le champ '" + val + "' n'existe pas") return False, " Les informations fournies sont incorrectes", """ Verification des champs obligatoires """ field_list_obligatoire = ['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 la liste des arguments ") return False, " Les informations fournies sont incorrectes", """ Verification de l'identité et autorisation de l'entité qui appelle cette API """ recid = "" if ("recid" in diction.keys()): if diction['recid']: recid = diction['recid'] # Recuperation des données du partenaire local_status, my_partner = mycommon.get_partner_data_from_recid(recid) if (local_status is False): mycommon.myprint( str(inspect.stack()[0][3]) + " - impossible de récupérer les données de l'utilisateur ") return False, str(inspect.stack()[0][3]) + " - impossible de récupérer les données de l'utilisateur. " data = {} data['recid'] = my_partner['recid'] local_status, local_retval = strype_payement.Strip_Get_Customer_Abonnement_Data(data) if (local_status is False): mycommon.myprint( str(inspect.stack()[0][3]) + " - impossible de récupérer les données de facturation ") return False, str(inspect.stack()[0][3]) + " - impossible de récupérer les données de facturation. " print(" ### local_retval[0] = ", local_retval[0]) local_retval_JSON = json.loads(str(local_retval[0])) local_retval_JSON['user_name'] = my_partner['nom'] # On verifie que les informations retournées contiennent tous les champs local_champs_obligatoire = ['recid', 'period_start', 'period_end', 'total', 'main_description', 'lines', 'user_name'] for val in local_champs_obligatoire: if val not in local_retval_JSON.keys(): mycommon.myprint( str(inspect.stack()[0][3]) + " - La valeur '" + val + "' n'est pas presente dans la liste des arguments (2)") return False, " Les informations fournies sont incorrectes (2)", local_retval_JSON['tva'] = round(mycommon.tryFloat(str(local_retval_JSON["total"])) * 0.2, 2) local_retval_JSON['total_ttc'] = round(mycommon.tryFloat(str(local_retval_JSON["total"])) * 1.2, 2) smtpserver = smtplib.SMTP(MYSY_GV.O365_SMTP_COUNT_smtpsrv, MYSY_GV.O365_SMTP_COUNT_port) # msg = MIMEMultipart("alternative") msg = EmailMessage() # JINJA2 templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = "Template/MySy_Next_Invoice_Info_tpl.html" template = templateEnv.get_template(TEMPLATE_FILE) # This data can come from database query body = { "params": local_retval_JSON, } sourceHtml = template.render(params=body["params"]) msg.set_content(sourceHtml, subtype='html') msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Bcc'] = 'contact@mysy-training.com' msg['Subject'] = "[MySy Training Technology] : Information Facture à venir. " msg['To'] = str(my_partner['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 envoyé ok" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer les informations de la prochaines factures " """ Cette fonction permet d'envoyer les emails générés par le module font "module_email_management" Pour ce faire, la fonction prend en argument : - list_email_dest - list_email_cc - list_email_bcc - email_corps - related_collection - pièce jointes algo : le corps du mail peut porter des tag de replacement comme le nom, prenom. On va aller chercher dans la collection "related_collection" les donnée des personnes qui sont dans le "list_email_dest" En gros, si list_email_dest[x] = related_collection.email, alors ok. Si on ne trouve pas la personne, on n'envoie par l'email. /!\ Ceci est une sécurité pour eviter d'envoyer des email des personnes non connus de mysy/ """ def Prepare_and_Send_Email_From_Front(tab_files, Folder, diction): try: diction = mycommon.strip_dictionary(diction) field_list = ['token', 'list_email_dest', 'list_email_cc', 'list_email_bcc', 'email_corps', 'related_collection', 'email_sujet', 'include_client', 'include_tuteur', 'list_inscription_id'] incom_keys = diction.keys() for val in incom_keys: if val not in field_list and val.startswith('my_') is False: mycommon.myprint(str(inspect.stack()[0][ 3]) + " - Le champ '" + val + "' n'est pas autorisé") return False, "Impossible de créer le stagiaire. Toutes les informations fournies ne sont pas valables" field_list_obligatoire = ['token', 'list_email_dest', 'related_collection', 'email_sujet', 'email_corps'] 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 la liste des arguments ") return False, " La valeur '" + val + "' n'est pas presente dans la liste des arguments" my_token = "" if ("token" in diction.keys()): if diction['token']: my_token = diction['token'] local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction) if (local_status is not True): return local_status, my_partner list_inscription_id = str(diction['list_inscription_id']).split(",") list_inscription_id_Objectid = [] for tmp in list_inscription_id: if( tmp ): list_inscription_id_Objectid.append((ObjectId(str(tmp)))) #print(" #### list_inscription_id = ", list_inscription_id) """ Verifier la validité "related_collection" """ related_collection = str(diction['related_collection']).strip().lower() if(related_collection not in MYSY_GV.EMAIL_DEST_RELATED_COLLECTION ): mycommon.myprint( str(inspect.stack()[0][ 3]) + " Le champ 'related_collection' est invalide ") return False, " Le champ 'related_collection' est invalide " local_partner_owner_recid = "partner_owner_recid" if (related_collection == "contact"): local_partner_owner_recid = "partner_recid" """ Gestion du sujet : On le tronc à 200 caractère max """ email_sujet = "" if(len(str(diction['email_sujet'])) > 200 ): email_sujet = str(diction['email_sujet'])[0:200] else: email_sujet = str(diction['email_sujet']) """ Verifier que le format list_email_cc est valide """ tab_email_cc = "" if ("list_email_cc" in diction.keys()): if diction['list_email_cc']: tab_email_cc = diction['list_email_cc'] tab_email_cc = str(tab_email_cc).split(",") for email_cc in tab_email_cc: if (email_cc): if (mycommon.isEmailValide(str(email_cc)) is False): mycommon.myprint( str(inspect.stack()[0][3]) + " L'adresse email en CC '" + str(email_cc) + "' est invalide ") return False, "L'adresse email en CC '" + str(email_cc) + "' est invalide" if (len(tab_email_cc) > MYSY_GV.EMAIL_MAX_CC): mycommon.myprint("Vous ne pouvez pas envoyer plus de " + str(MYSY_GV.EMAIL_MAX_BCC) + " emails en copie.") return False, "Vous ne pouvez pas envoyer plus de " + str(MYSY_GV.EMAIL_MAX_BCC) + " emails en copie." """ Verifier que le format list_email_bcc est valide """ tab_email_bcc = "" if ("list_email_bcc" in diction.keys()): if diction['list_email_bcc']: tab_email_bcc = diction['list_email_bcc'] tab_email_bcc = str(tab_email_bcc).split(",") for email_bcc in tab_email_bcc: if (email_bcc): if (mycommon.isEmailValide(str(email_bcc)) is False): mycommon.myprint( str(inspect.stack()[0][3]) + " L'adresse email en BCC '" + str(email_bcc) + "' est invalide ") return False, "L'adresse email en BCC '" + str(email_bcc) + "' est invalide" if (len(tab_email_bcc) > MYSY_GV.EMAIL_MAX_BCC): mycommon.myprint( "Vous ne pouvez pas envoyer plus de " + str(MYSY_GV.EMAIL_MAX_BCC) + " emails en copie-cachée.") return False, "Vous ne pouvez pas envoyer plus de " + str( MYSY_GV.EMAIL_MAX_BCC) + " emails en copie-cachée." """ Verifier la validité des emails de destinataire. Si et SEULEMENT SI "related_collection" != "no_contact" """ tab_related_collection_id = [] tab_email_dest = "" if ("list_email_dest" in diction.keys()): if diction['list_email_dest']: tab_email_dest = diction['list_email_dest'] tab_email_dest = str(tab_email_dest).split(",") for email_dest in tab_email_dest: if( email_dest ): if (mycommon.isEmailValide(str(email_dest)) is False): mycommon.myprint( str(inspect.stack()[0][3]) + " L'adresse email '" + str(email_dest) + "' est invalide ") return False, "L'adresse email '" + str(email_dest) + "' est invalide" is_valide_email_in_related_collection = MYSY_GV.dbname[str(related_collection)].count_documents({"email":str(email_dest), 'valide':'1', local_partner_owner_recid:str(my_partner['recid']), '_id': { '$in': list_inscription_id_Objectid}, }) if( is_valide_email_in_related_collection != 1 ): mycommon.myprint( str(inspect.stack()[0][ 3]) + " L'adresse email '" + str(email_dest) + "' existe pas dans le système ") return False, " L'adresse email '" + str(email_dest) + "'existe pas dans le système " is_valide_email_in_related_collection_data = MYSY_GV.dbname[str(related_collection)].find_one( {"email": str(email_dest), 'valide': '1', local_partner_owner_recid: str(my_partner['recid']), '_id': { '$in': list_inscription_id_Objectid}, }, {'_id':1}) tab_related_collection_id.append(str(is_valide_email_in_related_collection_data['_id'])) #print(" ### la liste _id des destinataire est ", str(tab_related_collection_id)) if (len(tab_email_dest) > MYSY_GV.EMAIL_MAX_DESTINAIRE): mycommon.myprint( "Vous ne pouvez pas envoyer plus de " + str(MYSY_GV.EMAIL_MAX_DESTINAIRE) + " emails à la fois.") return False, "Vous ne pouvez pas envoyer plus de " + str( MYSY_GV.EMAIL_MAX_DESTINAIRE) + " emails à la fois." # Sauvegarde des fichiers joints depuis le front if (len(tab_files) > MYSY_GV.EMAIL_MAX_PJ): mycommon.myprint("Vous ne pouvez pas envoyer plus de " + str(MYSY_GV.EMAIL_MAX_PJ) + " pièces jointes.") return False, "Vous ne pouvez pas envoyer plus de " + str(MYSY_GV.EMAIL_MAX_PJ) + " pièces jointes. " tab_saved_file_full_path = [] for file in tab_files: status, saved_file_full_path = mycommon.Upload_Save_PDF_IMG_File(file, Folder) if (status is False): mycommon.myprint("Impossible de récupérer correctement le fichier à importer") return False, "Impossible de récupérer correctement le fichier à importer" tab_saved_file_full_path.append(saved_file_full_path) # Traitement de l'eventuel fichier joint tab_files_to_attache_to_mail = [] for saved_file in tab_saved_file_full_path: file_to_attache_to_mail = MIMEBase('application', "octet-stream") file_to_attache_to_mail.set_payload(open(saved_file, "rb").read()) encoders.encode_base64(file_to_attache_to_mail) file_to_attache_to_mail.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(saved_file))) new_node = {"attached_file": file_to_attache_to_mail} tab_files_to_attache_to_mail.append(new_node) # Recuperation des donnes SMTP local_stpm_status, partner_SMTP_COUNT_smtpsrv, partner_own_smtp_value, partner_SMTP_COUNT_password, partner_SMTP_COUNT_user, partner_SMTP_COUNT_From_User, partner_SMTP_COUNT_port = mycommon.Get_Partner_SMTP_Param( my_partner['recid']) if (local_stpm_status is False): return local_stpm_status, partner_own_smtp_value smtpserver = None 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) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) cpt_email_envoye = 0 """ Envoie proprement-dit des emails """ for user_id in tab_related_collection_id: user_related_collection_data = MYSY_GV.dbname[str(related_collection)].find_one( {"_id": ObjectId(str(user_id)), 'valide': '1', local_partner_owner_recid: str(my_partner['recid']) }, {'_id': 1, 'email':1, 'nom':1, 'prenom':1}) nom="" prenom = "" email = "" if( "nom" in user_related_collection_data.keys() ): nom = user_related_collection_data['nom'] if ("prenom" in user_related_collection_data.keys()): prenom = user_related_collection_data['prenom'] if ("email" in user_related_collection_data.keys()): email = user_related_collection_data['email'] # Creation du dictionnaire d'information à utiliser pour la creation du doc convention_dictionnary_data = {} new_diction = {} new_diction['token'] = my_partner['token'] new_diction['list_stagiaire_id'] = [] new_diction['list_session_id'] = [] new_diction['list_class_id'] = [] new_diction['list_client_id'] = [] local_status, local_retval = mycommon.Get_Dictionnary_data_For_Template(new_diction) if (local_status is False): return local_status, local_retval convention_dictionnary_data = local_retval node = {} convention_dictionnary_data['nom'] = nom convention_dictionnary_data['prenom'] = prenom body = { "params": convention_dictionnary_data, } # Creation de l'email à enoyer zzzz msg = MIMEMultipart("alternative") contenu_doc_Template = jinja2.Template(str(diction['email_corps'])) sourceHtml = contenu_doc_Template.render(params=body["params"]) html_mime = MIMEText(sourceHtml, 'html') tab_email_bcc.append(str(my_partner['email'])) local_diction = {} local_diction['token'] = diction['token'] local_diction['partner_own_smtp_value'] = partner_own_smtp_value local_diction['partner_SMTP_COUNT_smtpsrv'] = partner_SMTP_COUNT_smtpsrv local_diction['partner_SMTP_COUNT_port'] = partner_SMTP_COUNT_port local_diction['user_id'] = user_id local_diction['related_collection'] = related_collection local_diction['partner_SMTP_COUNT_From_User'] = partner_SMTP_COUNT_From_User local_diction['tab_email_cc'] = tab_email_cc local_diction['tab_email_bcc'] = tab_email_bcc local_diction['tab_files_to_attache_to_mail'] = tab_files_to_attache_to_mail local_diction['email_sujet'] = email_sujet local_diction['html_mime'] = html_mime local_diction['email'] = email local_diction['partner_owner_recid'] = str(my_partner['recid']) if( "include_client" in diction.keys() ): local_diction['include_client'] = diction['include_client'] else: local_diction['include_client'] = "0" if ("include_tuteur" in diction.keys()): local_diction['include_tuteur'] = diction['include_tuteur'] else: local_diction['include_tuteur'] = "0" #print(" ### local_diction = ", local_diction) local_status, local_retval = send_invidual_email (local_diction) if( local_status is False ): return local_status, local_retval cpt_email_envoye = cpt_email_envoye + 1 print(" NB_email envoyé = ", cpt_email_envoye) return True, " Les emails ont été correctement envoyés" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer les emails " """ Cette fonction envoie des email pour des destinataires qui ne sont pas connus de mysy. donc impossible d'utiliser les tag comme les nom et prenom etc """ def Prepare_and_Send_Email_From_Front_For_Unknown_Contact(tab_files, Folder, diction): try: diction = mycommon.strip_dictionary(diction) field_list = ['token', 'list_email_dest', 'list_email_cc', 'list_email_bcc', 'email_corps', 'related_collection', 'email_sujet'] incom_keys = diction.keys() for val in incom_keys: if val not in field_list and val.startswith('my_') is False: mycommon.myprint(str(inspect.stack()[0][ 3]) + " - Le champ '" + val + "' n'est pas autorisé") return False, "Impossible de créer le stagiaire. Toutes les informations fournies ne sont pas valables" field_list_obligatoire = ['token', 'list_email_dest', 'related_collection', 'email_sujet', 'email_corps'] 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 la liste des arguments ") return False, " La valeur '" + val + "' n'est pas presente dans la liste des arguments" my_token = "" if ("token" in diction.keys()): if diction['token']: my_token = diction['token'] local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction) if (local_status is not True): return local_status, my_partner """ Verifier la validité "related_collection" """ related_collection = str(diction['related_collection']).strip().lower() if(related_collection not in MYSY_GV.EMAIL_DEST_RELATED_COLLECTION ): mycommon.myprint( str(inspect.stack()[0][ 3]) + " Le champ 'related_collection' est invalide ") return False, " Le champ 'related_collection' est invalide " local_partner_owner_recid = "partner_owner_recid" if (related_collection == "contact"): local_partner_owner_recid = "partner_recid" """ Gestion du sujet : On le tronc à 200 caractère max """ email_sujet = "" if(len(str(diction['email_sujet'])) > 200 ): email_sujet = str(diction['email_sujet'])[0:200] else: email_sujet = str(diction['email_sujet']) """ Verifier que le format list_email_cc est valide """ tab_email_cc = "" if ("list_email_cc" in diction.keys()): if diction['list_email_cc']: tab_email_cc = diction['list_email_cc'] tab_email_cc = str(tab_email_cc).split(",") for email_cc in tab_email_cc: if (email_cc): if (mycommon.isEmailValide(str(email_cc)) is False): mycommon.myprint( str(inspect.stack()[0][3]) + " L'adresse email en CC '" + str(email_cc) + "' est invalide ") return False, "L'adresse email en CC '" + str(email_cc) + "' est invalide" if (len(tab_email_cc) > MYSY_GV.EMAIL_MAX_CC): mycommon.myprint("Vous ne pouvez pas envoyer plus de "+str(MYSY_GV.EMAIL_MAX_BCC)+" emails en copie.") return False, "Vous ne pouvez pas envoyer plus de "+str(MYSY_GV.EMAIL_MAX_BCC)+" emails en copie." """ Verifier que le format list_email_bcc est valide """ tab_email_bcc = "" if ("list_email_bcc" in diction.keys()): if diction['list_email_bcc']: tab_email_bcc = diction['list_email_bcc'] tab_email_bcc = str(tab_email_bcc).split(",") for email_bcc in tab_email_bcc: if (email_bcc): if (mycommon.isEmailValide(str(email_bcc)) is False): mycommon.myprint( str(inspect.stack()[0][3]) + " L'adresse email en BCC '" + str(email_bcc) + "' est invalide ") return False, "L'adresse email en BCC '" + str(email_bcc) + "' est invalide" if (len(tab_email_bcc) > MYSY_GV.EMAIL_MAX_BCC): mycommon.myprint("Vous ne pouvez pas envoyer plus de "+str(MYSY_GV.EMAIL_MAX_BCC)+" emails en copie-cachée.") return False, "Vous ne pouvez pas envoyer plus de "+str(MYSY_GV.EMAIL_MAX_BCC)+" emails en copie-cachée." """ Verifier la validité des emails de destinataire. Si et SEULEMENT SI "related_collection" != "no_contact" """ tab_related_collection_id = [] tab_email_dest = "" if ("list_email_dest" in diction.keys()): if diction['list_email_dest']: tab_email_dest = diction['list_email_dest'] tab_email_dest = str(tab_email_dest).split(",") for email_dest in tab_email_dest: if( email_dest ): if (mycommon.isEmailValide(str(email_dest)) is False): mycommon.myprint( str(inspect.stack()[0][3]) + " L'adresse email '" + str(email_dest) + "' est invalide ") return False, "L'adresse email '" + str(email_dest) + "' est invalide" #print(" ### la liste _id des destinataire est ", str(tab_related_collection_id)) if(len(tab_email_dest) > MYSY_GV.EMAIL_MAX_DESTINAIRE ): mycommon.myprint("Vous ne pouvez pas envoyer plus de "+str(MYSY_GV.EMAIL_MAX_DESTINAIRE)+" emails à la fois.") return False, "Vous ne pouvez pas envoyer plus de "+str(MYSY_GV.EMAIL_MAX_DESTINAIRE)+" emails à la fois." # Sauvegarde des fichiers joints depuis le front if (len(tab_files) > MYSY_GV.EMAIL_MAX_PJ ): mycommon.myprint("Vous ne pouvez pas envoyer plus de "+str(MYSY_GV.EMAIL_MAX_PJ)+" pièces jointes.") return False, "Vous ne pouvez pas envoyer plus de "+str(MYSY_GV.EMAIL_MAX_PJ)+" pièces jointes. " tab_saved_file_full_path = [] for file in tab_files: status, saved_file_full_path = mycommon.Upload_Save_PDF_IMG_File(file, Folder) if (status is False): mycommon.myprint("Impossible de récupérer correctement le fichier à importer") return False, "Impossible de récupérer correctement le fichier à importer" tab_saved_file_full_path.append(saved_file_full_path) # Traitement de l'eventuel fichier joint tab_files_to_attache_to_mail = [] for saved_file in tab_saved_file_full_path: file_to_attache_to_mail = MIMEBase('application', "octet-stream") file_to_attache_to_mail.set_payload(open(saved_file, "rb").read()) encoders.encode_base64(file_to_attache_to_mail) file_to_attache_to_mail.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(saved_file))) new_node = {"attached_file": file_to_attache_to_mail} tab_files_to_attache_to_mail.append(new_node) # Recuperation des donnes SMTP local_stpm_status, partner_SMTP_COUNT_smtpsrv, partner_own_smtp_value, partner_SMTP_COUNT_password, partner_SMTP_COUNT_user, partner_SMTP_COUNT_From_User, partner_SMTP_COUNT_port = mycommon.Get_Partner_SMTP_Param( my_partner['recid']) if (local_stpm_status is False): return local_stpm_status, partner_own_smtp_value smtpserver = None 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) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) cpt_email_envoye = 0 """ Envoie proprement-dit des emails """ for local_email_dest in tab_email_dest: # Creation de l'email à enoyer msg = MIMEMultipart("alternative") node = {} node['nom'] = "" node['prenom'] = "" body = { "params": node, } # Creation de l'email à enoyer msg = MIMEMultipart("alternative") contenu_doc_Template = jinja2.Template(str(diction['email_corps'])) sourceHtml = contenu_doc_Template.render(params=body["params"]) html_mime = MIMEText(sourceHtml, 'html') tab_email_bcc.append(str(my_partner['email'])) local_diction = {} local_diction['token'] = diction['token'] local_diction['partner_own_smtp_value'] = partner_own_smtp_value local_diction['partner_SMTP_COUNT_smtpsrv'] = partner_SMTP_COUNT_smtpsrv local_diction['partner_SMTP_COUNT_port'] = partner_SMTP_COUNT_port local_diction['user_id'] = "" local_diction['related_collection'] = related_collection local_diction['partner_SMTP_COUNT_From_User'] = partner_SMTP_COUNT_From_User local_diction['tab_email_cc'] = tab_email_cc local_diction['tab_email_bcc'] = tab_email_bcc local_diction['tab_files_to_attache_to_mail'] = tab_files_to_attache_to_mail local_diction['email_sujet'] = email_sujet local_diction['html_mime'] = html_mime local_diction['email'] = str(local_email_dest) local_status, local_retval = send_invidual_email (local_diction) if( local_status is False ): return local_status, local_retval cpt_email_envoye = cpt_email_envoye + 1 print(" NB_email envoyé = ", cpt_email_envoye) return True, " Les emails ont été correctement envoyés" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer les emails " """ Envoi d'un email email individuel """ def send_invidual_email(diction): try: diction = mycommon.strip_dictionary(diction) my_token = "" if ("token" in diction.keys()): if diction['token']: my_token = diction['token'] local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction) if (local_status is not True): return local_status, my_partner smtpserver = None partner_own_smtp_value = diction['partner_own_smtp_value'] partner_SMTP_COUNT_smtpsrv = diction['partner_SMTP_COUNT_smtpsrv'] partner_SMTP_COUNT_port = diction['partner_SMTP_COUNT_port'] partner_SMTP_COUNT_From_User = diction['partner_SMTP_COUNT_From_User'] tab_email_cc = diction['tab_email_cc'] tab_email_bcc = diction['tab_email_bcc'] tab_files_to_attache_to_mail = diction['tab_files_to_attache_to_mail'] email_sujet = diction['email_sujet'] html_mime = diction['html_mime'] email = diction['email'] user_id = diction['user_id'] related_collection = diction['related_collection'] include_client = diction['include_client'] include_tuteur = diction['include_tuteur'] include_client = diction['include_client'] partner_owner_recid = diction['partner_owner_recid'] # Recuperer les données tuteurs if(related_collection == "inscription" ): inscription_data = MYSY_GV.dbname['inscription'].find_one({'_id':ObjectId(str(user_id)), 'partner_owner_recid':str(partner_owner_recid)}, ) if( include_client == "1" and inscription_data and "client_rattachement_id" in inscription_data.keys() ): # Recuperation des contacts de communication du client new_diction = {} new_diction['related_collection'] = "partner_client" new_diction['related_collection_recid'] = inscription_data['client_rattachement_id'] new_diction['partner_recid'] = partner_owner_recid new_diction['valide'] = "1" new_diction['locked'] = "0" new_diction['include_com'] = "1" for retval in MYSY_GV.dbname['contact'].find(new_diction): if( "email" in retval ): tab_email_cc.append(retval['email']) if( include_tuteur == "1"): if( "tuteur1_include_com" in inscription_data and inscription_data['tuteur1_include_com'] == "1"): tab_email_cc.append(inscription_data['tuteur1_email']) if ("tuteur2_include_com" in inscription_data and inscription_data['tuteur2_include_com'] == "1"): tab_email_cc.append(inscription_data['tuteur2_email']) 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) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(MYSY_GV.O365_SMTP_COUNT_user, MYSY_GV.O365_SMTP_COUNT_password) cpt_email_envoye = 0 """ Envoie proprement-dit des emails """ # Creation de l'email à enoyer msg = MIMEMultipart("alternative") tab_email_bcc.append(str(my_partner['email'])) if (str(partner_own_smtp_value) == "1"): msg.attach(html_mime) msg['From'] = partner_SMTP_COUNT_From_User msg['Cc'] = ",".join(tab_email_cc) msg['Bcc'] = ",".join(tab_email_bcc) msg['Subject'] = email_sujet msg['to'] = str(email) # Attacher l'eventuelle pièces jointes for myfile in tab_files_to_attache_to_mail: msg.attach(myfile['attached_file']) val = smtpserver.send_message(msg) print(" Email a envoyé " + str(email)) cpt_email_envoye = cpt_email_envoye + 1 else: msg.attach(html_mime) msg['From'] = MYSY_GV.O365_SMTP_COUNT_From_User msg['Cc'] = ",".join(tab_email_cc) msg['Bcc'] = ",".join(tab_email_bcc) msg['Subject'] = email_sujet msg['to'] = str(email) # Attacher l'eventuelle pièces jointes for myfile in tab_files_to_attache_to_mail: msg.attach(myfile['attached_file']) val = smtpserver.send_message(msg) print(" Email a envoyé " + str(email)) cpt_email_envoye = cpt_email_envoye + 1 smtpserver.close() return True, " Les emails ont été correctement envoyés" except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) return False, " Impossible d'envoyer les emails "