send_email.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import requests
  2. import smtplib
  3. import ssl
  4. import tempfile
  5. import time
  6. import urllib.request
  7. import json
  8. import logging
  9. from datetime import datetime, timedelta
  10. from email.mime.image import MIMEImage
  11. from email.mime.multipart import MIMEMultipart
  12. from email.mime.text import MIMEText
  13. # Logging configuration
  14. log_file = "/var/log/scripts/script_log.log"
  15. logging.basicConfig(filename=log_file, level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
  16. def send_to_telegram(bot_token, chat_id, caption, *image_paths):
  17. url = f"https://api.telegram.org/bot{bot_token}/sendMediaGroup"
  18. media_group = []
  19. for i, image_path in enumerate(image_paths):
  20. media_group.append({
  21. 'type': 'photo',
  22. 'media': 'attach://image' + str(i),
  23. 'caption': caption if i == 0 else "",
  24. 'parse_mode': 'HTML',
  25. })
  26. data = {
  27. 'chat_id': chat_id,
  28. 'media': json.dumps(media_group),
  29. }
  30. files = {
  31. f'image{i}': (f'image{i}.jpg', open(image_path, 'rb')) for i, image_path in enumerate(image_paths)
  32. }
  33. response = requests.post(url, data=data, files=files)
  34. if response.status_code != 200:
  35. raise ValueError(f"Request to Telegram API returned an error: {response.status_code}, {response.text}")
  36. def create_email(sender_email, recipient_emails, subject, boot_time_str, image_path1, image_path2, image_path3):
  37. msg = MIMEMultipart("related")
  38. msg["From"] = sender_email
  39. msg["To"] = ",".join(recipient_emails)
  40. msg["Subject"] = subject
  41. msg_alternative = MIMEMultipart("alternative")
  42. msg.attach(msg_alternative)
  43. msg_text = MIMEText("This is the alternative plain text message.")
  44. msg_alternative.attach(msg_text)
  45. html_text = f'<img src="cid:image1"><br><img src="cid:image2"><br><br><p>Letzter Start: {boot_time_str} Uhr</p>'
  46. msg_html = MIMEText(html_text, "html")
  47. msg_alternative.attach(msg_html)
  48. with open(image_path1, "rb") as file:
  49. msg_image1 = MIMEImage(file.read())
  50. msg_image1.add_header("Content-ID", "<image1>")
  51. msg.attach(msg_image1)
  52. with open(image_path2, "rb") as file:
  53. msg_image2 = MIMEImage(file.read())
  54. msg_image2.add_header("Content-ID", "<image2>")
  55. msg.attach(msg_image2)
  56. return msg
  57. def send_email(sender_email, recipient_emails, msg):
  58. try:
  59. context = ssl.create_default_context()
  60. with smtplib.SMTP("smtp.web.de", 587) as server:
  61. server.ehlo()
  62. server.starttls(context=context)
  63. server.ehlo()
  64. server.login(sender_email, "PV-Tannenstr1")
  65. server.sendmail(sender_email, recipient_emails, msg.as_string())
  66. logging.info("Email sent successfully.")
  67. except Exception as e:
  68. logging.error(f"Failed to send email: {e}")
  69. def get_boot_time():
  70. with open("/proc/uptime", "r") as f:
  71. uptime_seconds = int(float(f.readline().split()[0]))
  72. boot_time = datetime.now() - timedelta(seconds=uptime_seconds) + timedelta(hours=1)
  73. return boot_time
  74. tmpdir = tempfile.TemporaryDirectory()
  75. beginning = str(1000 * (int(time.time())) - (24 * 3600000))[:-3]
  76. end = str(1000 * int(time.time()))[:-3]
  77. urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=109&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=350&graph_height=100", tmpdir.name + "/ping.png")
  78. urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=103&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=700&graph_height=198", tmpdir.name + "/traffic.png")
  79. urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=120&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=350&graph_height=80", tmpdir.name + "/ping_google.png")
  80. # Bot token and chat ID for Telegram
  81. bot_token = "949332240:AAHNsQEmCW4it86Esa7F5o07XxwrotSM7s8"
  82. chat_id = "-914111351"
  83. boot_time = get_boot_time()
  84. boot_time_str = boot_time.strftime("%d.%m.%Y, %H.%M")
  85. subject = datetime.today().strftime('%Y-%m-%d') + ' Darmstadt'
  86. sender_email = 'pv-tannenstr@web.de'
  87. recipient_emails = ["tobias.siegel@outlook.com", "wsiegel@web.de"]
  88. email_msg = create_email(sender_email, recipient_emails, subject, boot_time_str, tmpdir.name + "/traffic.png", tmpdir.name + "/ping.png", tmpdir.name + "/ping_google.png")
  89. send_email(sender_email, recipient_emails, email_msg)
  90. try:
  91. 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", tmpdir.name + "/ping_google.png")
  92. logging.info("Telegram message sent successfully.")
  93. except ValueError as e:
  94. logging.error(f"Failed to send images to Telegram: {e}")
  95. tmpdir.cleanup()