28/10/22 - 20h30

master
cherif 2022-10-28 20:29:39 +02:00
parent 4d2822a376
commit a3a5758098
2 changed files with 531 additions and 1 deletions

View File

@ -4,6 +4,8 @@ from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.mime.base import MIMEBase from email.mime.base import MIMEBase
from email import encoders from email import encoders
from email.message import EmailMessage
import locale import locale
import datetime import datetime
import inspect import inspect
@ -14,6 +16,8 @@ from dateutil import tz
import pytz import pytz
import sib_api_v3_sdk import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException from sib_api_v3_sdk.rest import ApiException
import jinja2
configuration = sib_api_v3_sdk.Configuration() configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = MYSY_GV.SENDINBLUE_API_KEY configuration.api_key['api-key'] = MYSY_GV.SENDINBLUE_API_KEY
@ -364,7 +368,7 @@ def Pro_Account_Token_Pass(account_mail, my_token):
''' '''
Cette fonction envoie l'email de confirmation de la commande de vente Cette fonction envoie l'email de confirmation de la commande de vente
''' '''
def SalesOrderConfirmationEmail(account_mail, diction): def SalesOrderConfirmationEmail_old(account_mail, diction):
try: try:
''' '''
Verification des données obligatoires Verification des données obligatoires
@ -646,3 +650,505 @@ def SendInvoiceEmail(account_mail, diction):
exc_type, exc_obj, exc_tb = sys.exc_info() 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)) print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False 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 "
password = 'GomboyaVince1234+'
smtpsrv = "smtp.office365.com"
smtpserver = smtplib.SMTP(smtpsrv, 587)
user = "cbalde@mysy-training.com"
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(user, 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 "
password = 'GomboyaVince1234+'
smtpsrv = "smtp.office365.com"
smtpserver = smtplib.SMTP(smtpsrv, 587)
user = "cbalde@mysy-training.com"
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(user, 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 "
password = 'GomboyaVince1234+'
smtpsrv = "smtp.office365.com"
smtpserver = smtplib.SMTP(smtpsrv, 587)
user = "cbalde@mysy-training.com"
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(user, 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
'''
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['Cc'] = '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)
"""
#----------
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 "
password = 'GomboyaVince1234+'
smtpsrv = "smtp.office365.com"
smtpserver = smtplib.SMTP(smtpsrv, 587)
user = "cbalde@mysy-training.com"
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'] = "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(user, password)
smtpserver.send_message(msg)
smtpserver.close()
#--------
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

24
main.py
View File

@ -1871,6 +1871,30 @@ def SendPre_InscriptionEmail():
"""
API pour tester les nice emails de cherif (alternative à sendinblu)
"""
@app.route('/myclass/api/MysyGenericEmail_tpl/', methods=['POST','GET'])
@crossdomain(origin='*')
def MysyGenericEmail_tpl():
# On recupere le corps (payload) de la requete
payload = request.form.to_dict()
print(" ### MysyGenericEmail : payload = ",str(payload))
localStatus, message= emails.MysyGenericEmail_tpl()
return jsonify(status=localStatus, message=message )
@app.route('/myclass/api/MysyOrderEmail_tpl/', methods=['POST','GET'])
@crossdomain(origin='*')
def MysyOrderEmail_tpl():
# On recupere le corps (payload) de la requete
payload = request.form.to_dict()
print(" ### MysyOrderEmail_tpl : payload = ",str(payload))
localStatus, message= emails.MysyOrderEmail_tpl()
return jsonify(status=localStatus, message=message )
if __name__ == '__main__': if __name__ == '__main__':