send_email.py 4.0 KB

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