|
3 | 3 | from myapp import app, mail |
4 | 4 | from flask_mail import Message |
5 | 5 | from werkzeug.utils import secure_filename |
| 6 | +from datetime import datetime |
6 | 7 | import io |
| 8 | +import os |
7 | 9 |
|
8 | 10 | APP_NAME=app.config['APP_NAME'] |
9 | 11 | APP_URL=app.config['APP_URL'] |
10 | 12 | APP_TITLE=app.config['APP_TITLE'] |
11 | 13 |
|
| 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}") |
12 | 44 |
|
13 | 45 | def send_async_email(app, msg): |
14 | 46 | 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) |
16 | 52 |
|
17 | 53 | def send_email(subject, sender, recipients, text_body, html_body, reply_to, attachment=None, attachment_path=None, attachment_type=None, open_type="rb"): |
18 | 54 | msg = Message(subject, sender=sender, recipients=recipients, reply_to = reply_to) |
|
0 commit comments