66from datetime import datetime
77import io
88import os
9+ import requests
910
1011APP_NAME = app .config ['APP_NAME' ]
1112APP_URL = app .config ['APP_URL' ]
1213APP_TITLE = app .config ['APP_TITLE' ]
1314
15+ SLACK_HOOK = app .config ['SLACK_HOOK' ]
1416EMAIL_LOG_DIR = os .path .join (app .config ["USERS_DATA" ], 'email_logs' )
1517SEND_FAILED_FILE = os .path .join (EMAIL_LOG_DIR , 'failed.log' )
1618SEND_SUCCESS_FILE = os .path .join (EMAIL_LOG_DIR , 'success.log' )
1719
18- def write_email_log (file_path , msg , e = None ):
20+ def write_email_log (file_path , msg , e = None ):
1921 try :
2022 os .makedirs (EMAIL_LOG_DIR , exist_ok = True )
2123 current_time = datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
@@ -24,11 +26,10 @@ def write_email_log(file_path, msg, e = None):
2426 file .write ("Subject: " + str (msg .subject ) + "\n " )
2527 file .write ("Sender: " + str (msg .sender ) + "\n " )
2628 file .write ("Recipients: " + str (msg .recipients ) + "\n " )
27- file .write ("Body: " + str (msg .body ) + "\n " )
28- file .write ("HTML Body: " + str (msg .html ) + "\n " )
2929 file .write ("Reply-To: " + str (msg .reply_to ) + "\n " )
30+ file .write ("Body: " + str (msg .body ) + "\n " )
3031 if e is not None :
31- file .write (f"Exception: { e } \n " )
32+ file .write (f"Exception: { str ( e ) } \n " )
3233 file .write ("-" * 50 + "\n " )
3334
3435 # keep the log file size in check, max 500kb
@@ -42,13 +43,38 @@ def write_email_log(file_path, msg, e = None):
4243 except Exception as e :
4344 print (f"Failed to write email log to file: { e } " )
4445
46+ def send_slack_notification (slack_hook , msg , e = None ):
47+ try :
48+ current_time = datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
49+ message = (
50+ f"*Flaski Email Sending Failed!*\n \n "
51+ f"*Time:* { current_time } \n "
52+ f"*Subject:* { str (msg .subject )} \n "
53+ f"*Sender:* { str (msg .sender )} \n "
54+ f"*Recipients:* { str (msg .recipients )} \n "
55+ f"*Reply-To:* { str (msg .reply_to )} \n "
56+ f"*Body:* { str (msg .body )} \n "
57+ )
58+ if e is not None :
59+ message += f"*Exception:* { str (e )} \n "
60+
61+ payload = {
62+ "text" : message
63+ }
64+ headers = {"Content-Type" : "application/json" }
65+ requests .post (slack_hook , json = payload , headers = headers )
66+ except :
67+ pass
68+
4569def send_async_email (app , msg ):
4670 with app .app_context ():
4771 try :
4872 mail .send (msg )
4973 write_email_log (SEND_SUCCESS_FILE , msg )
5074 except Exception as e :
5175 write_email_log (SEND_FAILED_FILE , msg , e )
76+ if SLACK_HOOK is not None :
77+ send_slack_notification (SLACK_HOOK , msg , e )
5278
5379def send_email (subject , sender , recipients , text_body , html_body , reply_to , attachment = None , attachment_path = None , attachment_type = None , open_type = "rb" ):
5480 msg = Message (subject , sender = sender , recipients = recipients , reply_to = reply_to )
0 commit comments