Elyos_FI_Back_Office/email_mgt.py

2164 lines
85 KiB
Python

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 locale
import datetime
import inspect
import sys, os
from bson import ObjectId
from xhtml2pdf import pisa
import prj_common as mycommon
import GlobalVariable as MYSY_GV
from dateutil import tz
import pytz
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
import jinja2
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.iexercice.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.iexercice.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.iexercice.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.iexercice.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.iexercice.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.iexercice.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 = '''
<!DOCTYPE html>
<html>
<body>
<div style="background-color:#eee;padding:0px;text-align:center;width:100%">
<h2 style="font-family:Georgia, 'Times New Roman', Times, serif;color#454349;">
<img src="http://88.170.110.220/img/MYSY-LOGO-BLUE.png" alt="Mysy Training Logo" width="110px" height="70px"/> </h2>
</div>
<div style="padding:20px 0px;text-align:center;font-family:Georgia, 'Times New Roman', Times, serif;color#454349;font-size:2rem;">
<div style="width:100%">
<div style="text-align:center;">
Bonjour
<div style="padding:20px 0px;text-align:center;font-family:Georgia, 'Times New Roman', Times, serif;color#454349;font-size:1.2rem;">
Message de <font color="green">MySy-Training Technology </font>.<br/>
{mymessage}
</div>
</body>
</html> '''.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 liste ")
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 liste ")
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 = '''
<!DOCTYPE html>
<html>
<body>
<div style="background-color:#eee;padding:0px;text-align:center;width:100%">
<h2 style="font-family:Georgia, 'Times New Roman', Times, serif;color#454349;">
<img src="http://88.170.110.220/img/MYSY-LOGO-BLUE.png" alt="Mysy Training Logo" width="110px" height="70px"/> </h2>
</div>
<div style="padding:20px 0px;text-align:center;font-family:Georgia, 'Times New Roman', Times, serif;color#454349;font-size:2rem;">
<div style="width:100%">
<div style="text-align:center;">
Bonjour
<div style="padding:20px 0px;text-align:center;font-family:Georgia, 'Times New Roman', Times, serif;color#454349;font-size:1.2rem;">
Message de <font color="green">MySy-Training Technology </font>.<br/>
ici le message de cherif <br/>
{mymessage}
</div>
</body>
</html> '''.format(mymessage=mail_message)
"""
msg.set_content('''
<!DOCTYPE html>
<html>
<body
style="
width: 50%;
margin-left: auto;
margin-right: auto;
text-align: center;
background-color: #EFF2F7;
"
>
<div style="background-color: #FFFFFF; padding: 10px 20px">
<div style="background-color: #EEEEEE; margin-top: 1rem; margin-bottom: 1rem;">
<img
src="https://img.mysy-training.com/MYSY-LOGO-BLUE.png" alt="Mysy Training Logo" style="max-width: 15%;"
/>
</div>
<div>
<div style="margin-left: auto;
margin-right: auto;">
<img
src="https://dummyimage.com/500x300/000/fff&text=Dummy+image"
style="height: 300px"
/>
<div style="text-align: center">
<h3>Article 1</h3>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. A
ducimus deleniti nemo quibusdam iste sint!
</p>
<a href="#">Read more</a>
</div>
</div>
</div>
</div>
</body>
</html>
''', 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:
'''
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 liste ")
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"
# 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
# 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,
},
}
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.iexercice.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.iexercice.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.iexercice.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.iexercice.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
'''
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)
"""
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_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)}
}
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))
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.iexercice.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.iexercice.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)
"""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)
# This data can come from database query
body = {
"params":{"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']),
},
}
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] : Demande d'information sur une formation"
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', ]
for val in field_list_obligatoire:
if val not in diction:
mycommon.myprint(str(inspect.stack()[0][3]) + " - La valeur '" + val + "' n'est pas presente dans liste ")
return False, " Impossible d'envoyer 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
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_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,
}
}
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 liste ")
return False, " Impossible d'envoyer les emails d'emargement"
my_token = ""
if ("token" in diction.keys()):
if diction['token']:
my_token = diction['token']
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)})
print("val_emarge = "+str(val_emarge))
print("ID = " + str(val_emarge['_id']))
print("email = " + str(val_emarge['email']))
# recuperation du titre de la formation
local_class_title = MYSY_GV.dbname['myclass'].find_one({'internal_url':str(val_emarge['class_internal_url']) })
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.iexercice.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.iexercice.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": "Matinée",
"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 Matinée du "+str(val_emarge['date'])
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()
print(" Email matinée envoyé " + str(my_emarge_id))
# envoie de l'emargement de l'apres midi
myurl = "http://127.0.0.1:5001/myclass/api/UserEmargementValidation/" + str(val_emarge['_id']) + "/2"
if (MYSY_GV.MYSY_ENV == "PROD"):
myurl = "https://apimysy.iexercice.com/myclass/api/UserEmargementValidation/" + str(
val_emarge['_id']) + "/2"
elif (MYSY_GV.MYSY_ENV == "DEV"):
myurl = "http://127.0.0.1:5001/myclass/api/UserEmargementValidation/" + str(val_emarge['_id']) + "/2"
elif (MYSY_GV.MYSY_ENV == "REC"):
myurl = "https://devapimysy.iexercice.com/myclass/api/UserEmargementValidation/" + str(
val_emarge['_id']) + "/2"
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": "Après-midi",
"mysyurl": str(myurl),
},
}
sourceHtml = template.render(params=body["params"])
msg_2 = EmailMessage()
msg_2.set_content(sourceHtml, subtype='html')
msg_2['From'] = MYSY_GV.O365_SMTP_COUNT_From_User
msg_2['Cc'] = 'contact@mysy-training.com'
msg_2['Subject'] = "[MySy Training Technology] : Emargement Après-midi du "+str(val_emarge['date'])
msg_2['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_2)
smtpserver.close()
print(" Email Apres midi envoyé " + str(my_emarge_id))
return True, "Email envoyé "
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, " Impossible d'envoyer l'email de notification "
"""
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": "005G",
"date_order": ": 07/03/2023",
"total_ht": "150",
"tva": "0",
"total_ttc": "150",
"client_name": "HIFMI-INSTITUTE",
"client_address": "50 AV PIERRE ET MARIE CURIE",
"client_zip_ville": "93700 DRANCY",
"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": "3",
"unit_price": "50",
"montant": "150",
"invoice_id": "FACT_230300027",
"invoice_date": "07/03/2023",
"due_date": "07/03/2022",
"orign_order": "Contrat 005G",
}
}
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_230200020.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 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 liste ")
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 "