send_email.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import os
  2. import ssl
  3. import smtplib
  4. import tempfile
  5. import time
  6. import urllib.request
  7. from datetime import datetime, timedelta
  8. from email.mime.image import MIMEImage
  9. from email.mime.multipart import MIMEMultipart
  10. from email.mime.text import MIMEText
  11. from influxdb import InfluxDBClient
  12. import requests
  13. # Configurations
  14. strFrom = 'pv-tannenstr@web.de'
  15. strTo = ["tobias.siegel@outlook.com", "wsiegel@web.de"]
  16. bot_token = '949332240:AAHNsQEmCW4it86Esa7F5o07XxwrotSM7s8'
  17. chat_id = '-914111351'
  18. def get_boot_time():
  19. with open('/proc/uptime', 'r') as f:
  20. uptime_seconds = int(float(f.readline().split()[0]))
  21. boot_time = datetime.now() - timedelta(seconds=uptime_seconds) + timedelta(hours=1)
  22. return boot_time
  23. def get_kwh(beginning, end):
  24. client = InfluxDBClient(host='127.0.0.1', port=8086, database='solar')
  25. result = client.query("SELECT sum(\"eingespeiste_leistung\") *0.000002777777777 FROM \"Tannenstrasse\" WHERE time >= {}ms and time <= {}ms".format(beginning, end))
  26. if 'series' in result.raw:
  27. return round(result.raw['series'][0]['values'][0][1], 1)
  28. else:
  29. return "0 - Keine Werte"
  30. def create_email(kwh):
  31. msgRoot = MIMEMultipart('related')
  32. msgRoot['Subject'] = f'{datetime.today().strftime("%Y-%m-%d")} - {kwh}kWh - Solaranlage'
  33. msgRoot['From'] = strFrom
  34. msgRoot['To'] = ",".join(strTo)
  35. msgRoot.preamble = 'This is a multi-part message in MIME format.'
  36. msgAlternative = MIMEMultipart('alternative')
  37. msgRoot.attach(msgAlternative)
  38. msgText = MIMEText('This is the alternative plain text message.')
  39. msgAlternative.attach(msgText)
  40. bt = get_boot_time()
  41. bt_str = bt.strftime("%d.%m.%Y, %H.%M")
  42. msgText = MIMEText(f'<img src="cid:image1"><br><p>Letzter Start: {bt_str} Uhr</p>', 'html')
  43. msgAlternative.attach(msgText)
  44. with open(tmpdir.name + '/leistung.png', 'rb') as fp:
  45. msgImage = MIMEImage(fp.read())
  46. msgImage.add_header('Content-ID', '<image1>')
  47. msgRoot.attach(msgImage)
  48. return msgRoot
  49. def send_email(msgRoot):
  50. context = ssl.create_default_context()
  51. with smtplib.SMTP('smtp.web.de', 587) as server:
  52. server.ehlo()
  53. server.starttls(context=context)
  54. server.ehlo()
  55. server.login(strFrom, 'PV-Tannenstr1')
  56. server.sendmail(strFrom, strTo, msgRoot.as_string())
  57. def send_telegram(bot_token, chat_id, kwh):
  58. bot_url = f'https://api.telegram.org/bot{bot_token}/sendPhoto'
  59. bt = get_boot_time()
  60. bt_str = bt.strftime("%d.%m.%Y, %H.%M")
  61. caption = f'{datetime.today().strftime("%Y-%m-%d")} - {kwh}kWh - Solaranlage\nLetzter Start: {bt_str} Uhr'
  62. with open(tmpdir.name + '/leistung.png', 'rb') as img:
  63. response = requests.post(
  64. bot_url,
  65. data={'chat_id': chat_id, 'caption': caption},
  66. files={'photo': img}
  67. )
  68. return response
  69. if __name__ == "__main__":
  70. tmpdir = tempfile.TemporaryDirectory()
  71. beginning = str((1000 * int(time.time())) - (17 * 3600000))
  72. end = str(1000 * int(time.time()))
  73. urllib.request.urlretrieve(f"http://localhost:3000/render/d-solo/-wCxs6mgk/solaranlage?orgId=1&refresh=10s&panelId=2&from={beginning}&to={end}&width=600&height=300&tz=Europe%2FBerlin", f"{tmpdir.name}/leistung.png")
  74. kwh = get_kwh(beginning, end)
  75. email_msg = create_email(kwh)
  76. send_email(email_msg)
  77. send_telegram(bot_token, chat_id, kwh)
  78. tmpdir.cleanup()