Skip to content

Commit 19f841c

Browse files
committed
email log check
1 parent caa84b4 commit 19f841c

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

myapp/email.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,52 @@
33
from myapp import app, mail
44
from flask_mail import Message
55
from werkzeug.utils import secure_filename
6+
from datetime import datetime
67
import io
8+
import os
79

810
APP_NAME=app.config['APP_NAME']
911
APP_URL=app.config['APP_URL']
1012
APP_TITLE=app.config['APP_TITLE']
1113

14+
EMAIL_LOG_DIR=os.path.join(app.config["USERS_DATA"], 'email_logs')
15+
SEND_FAILED_FILE=os.path.join(EMAIL_LOG_DIR, 'failed.log')
16+
SEND_SUCCESS_FILE=os.path.join(EMAIL_LOG_DIR, 'success.log')
17+
18+
def write_email_log(file_path, msg, e = None):
19+
try:
20+
os.makedirs(EMAIL_LOG_DIR, exist_ok=True)
21+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
22+
with open(file_path, "a") as file:
23+
file.write(f"Time:" + str(current_time) + "\n")
24+
file.write("Subject: " + str(msg.subject) + "\n")
25+
file.write("Sender: " + str(msg.sender) + "\n")
26+
file.write("Recipients: " + str(msg.recipients) + "\n")
27+
file.write("Body: " + str(msg.body) + "\n")
28+
file.write("HTML Body: " + str(msg.html) + "\n")
29+
file.write("Reply-To: " + str(msg.reply_to) + "\n")
30+
if e is not None:
31+
file.write(f"Exception: {e} \n")
32+
file.write("-" * 50 + "\n")
33+
34+
# keep the log file size in check, max 500kb
35+
if os.path.exists(file_path) and os.path.getsize(file_path) > 512000:
36+
with open(file_path, "r+") as file:
37+
lines = file.readlines()
38+
if len(lines) > 500:
39+
file.seek(0)
40+
file.writelines(lines[500:])
41+
file.truncate()
42+
except Exception as e:
43+
print(f"Failed to write email log to file: {e}")
1244

1345
def send_async_email(app, msg):
1446
with app.app_context():
15-
mail.send(msg)
47+
try:
48+
mail.send(msg)
49+
write_email_log(SEND_SUCCESS_FILE, msg)
50+
except Exception as e:
51+
write_email_log(SEND_FAILED_FILE, msg, e)
1652

1753
def send_email(subject, sender, recipients, text_body, html_body, reply_to, attachment=None, attachment_path=None, attachment_type=None, open_type="rb"):
1854
msg = Message(subject, sender=sender, recipients=recipients, reply_to = reply_to)

0 commit comments

Comments
 (0)