tsi il y a 2 ans
Parent
commit
3886b15e17
1 fichiers modifiés avec 19 ajouts et 9 suppressions
  1. 19 9
      send_email.py

+ 19 - 9
send_email.py

@@ -1,4 +1,3 @@
-import os
 import requests
 import requests
 import smtplib
 import smtplib
 import ssl
 import ssl
@@ -6,11 +5,17 @@ import tempfile
 import time
 import time
 import urllib.request
 import urllib.request
 import json
 import json
+import logging
 from datetime import datetime, timedelta
 from datetime import datetime, timedelta
 from email.mime.image import MIMEImage
 from email.mime.image import MIMEImage
 from email.mime.multipart import MIMEMultipart
 from email.mime.multipart import MIMEMultipart
 from email.mime.text import MIMEText
 from email.mime.text import MIMEText
 
 
+# Logging configuration
+log_file = "/var/log/script_log.log"
+logging.basicConfig(filename=log_file, level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
+
+
 def send_to_telegram(bot_token, chat_id, caption, *image_paths):
 def send_to_telegram(bot_token, chat_id, caption, *image_paths):
     url = f"https://api.telegram.org/bot{bot_token}/sendMediaGroup"
     url = f"https://api.telegram.org/bot{bot_token}/sendMediaGroup"
 
 
@@ -68,13 +73,17 @@ def create_email(sender_email, recipient_emails, subject, boot_time_str, image_p
 
 
 
 
 def send_email(sender_email, recipient_emails, msg):
 def send_email(sender_email, recipient_emails, msg):
-    context = ssl.create_default_context()
-    with smtplib.SMTP("smtp.web.de", 587) as server:
-        server.ehlo()
-        server.starttls(context=context)
-        server.ehlo()
-        server.login(sender_email, "PV-Tannenstr1")
-        server.sendmail(sender_email, recipient_emails, msg.as_string())
+    try:
+        context = ssl.create_default_context()
+        with smtplib.SMTP("smtp.web.de", 587) as server:
+            server.ehlo()
+            server.starttls(context=context)
+            server.ehlo()
+            server.login(sender_email, "PV-Tannenstr1")
+            server.sendmail(sender_email, recipient_emails, msg.as_string())
+        logging.info("Email sent successfully.")
+    except Exception as e:
+        logging.error(f"Failed to send email: {e}")
 
 
 
 
 def get_boot_time():
 def get_boot_time():
@@ -108,7 +117,8 @@ send_email(sender_email, recipient_emails, email_msg)
 
 
 try:
 try:
     send_to_telegram(bot_token, chat_id, f"<b>{subject}</b>\nLetzter Start: {boot_time_str} Uhr", tmpdir.name + "/traffic.png", tmpdir.name + "/ping.png")
     send_to_telegram(bot_token, chat_id, f"<b>{subject}</b>\nLetzter Start: {boot_time_str} Uhr", tmpdir.name + "/traffic.png", tmpdir.name + "/ping.png")
+    logging.info("Telegram message sent successfully.")
 except ValueError as e:
 except ValueError as e:
-    print(f"Failed to send images to Telegram: {e}")
+    logging.error(f"Failed to send images to Telegram: {e}")
 
 
 tmpdir.cleanup()
 tmpdir.cleanup()