send_email.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. # 10 seconds = 10/3600 hours = 1/360 hour.
  25. # So, the conversion factor for watts to kilowatt-hours for a 10-second interval is:
  26. # (1/1000) * (1/360) = 1/360000 = 0.000002777777777
  27. client = InfluxDBClient(host='127.0.0.1', port=8086, database='solar')
  28. result = client.query("SELECT sum(\"eingespeiste_leistung\") *0.000002777777777 FROM \"Tannenstrasse\" WHERE time >= {}ms and time <= {}ms".format(beginning, end))
  29. if 'series' in result.raw:
  30. return round(result.raw['series'][0]['values'][0][1], 1)
  31. else:
  32. return "0 - Keine Werte"
  33. def create_email(kwh):
  34. msgRoot = MIMEMultipart('related')
  35. msgRoot['Subject'] = f'{datetime.today().strftime("%Y-%m-%d")} - {kwh}kWh - Solaranlage'
  36. msgRoot['From'] = strFrom
  37. msgRoot['To'] = ",".join(strTo)
  38. msgRoot.preamble = 'This is a multi-part message in MIME format.'
  39. msgAlternative = MIMEMultipart('alternative')
  40. msgRoot.attach(msgAlternative)
  41. msgText = MIMEText('This is the alternative plain text message.')
  42. msgAlternative.attach(msgText)
  43. bt = get_boot_time()
  44. bt_str = bt.strftime("%d.%m.%Y, %H.%M")
  45. msgText = MIMEText(f'<img src="cid:image1"><br><p>Letzter Start: {bt_str} Uhr</p>', 'html')
  46. msgAlternative.attach(msgText)
  47. with open(tmpdir.name + '/leistung.png', 'rb') as fp:
  48. msgImage = MIMEImage(fp.read())
  49. msgImage.add_header('Content-ID', '<image1>')
  50. msgRoot.attach(msgImage)
  51. return msgRoot
  52. def send_email(msgRoot):
  53. context = ssl.create_default_context()
  54. with smtplib.SMTP('smtp.web.de', 587) as server:
  55. server.ehlo()
  56. server.starttls(context=context)
  57. server.ehlo()
  58. server.login(strFrom, 'PV-Tannenstr1')
  59. server.sendmail(strFrom, strTo, msgRoot.as_string())
  60. def send_telegram(bot_token, chat_id, kwh):
  61. bot_url = f'https://api.telegram.org/bot{bot_token}/sendPhoto'
  62. bt = get_boot_time()
  63. bt_str = bt.strftime("%d.%m.%Y, %H.%M")
  64. caption = f'{datetime.today().strftime("%Y-%m-%d")} - {kwh}kWh - Solaranlage\nLetzter Start: {bt_str} Uhr'
  65. with open(tmpdir.name + '/leistung.png', 'rb') as img:
  66. response = requests.post(
  67. bot_url,
  68. data={'chat_id': chat_id, 'caption': caption},
  69. files={'photo': img}
  70. )
  71. return response
  72. if __name__ == "__main__":
  73. tmpdir = tempfile.TemporaryDirectory()
  74. beginning = str((1000 * int(time.time())) - (17 * 3600000))
  75. end = str(1000 * int(time.time()))
  76. 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")
  77. kwh = get_kwh(beginning, end)
  78. email_msg = create_email(kwh)
  79. send_email(email_msg)
  80. send_telegram(bot_token, chat_id, kwh)
  81. tmpdir.cleanup()