mail_alert.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. '''Created Sep 28, 2021 Levi'''
  2. import configparser
  3. import sys
  4. import traceback
  5. import ssl
  6. from time import sleep
  7. from collections import deque
  8. from threading import Event
  9. import telegram
  10. import keyring
  11. from bs4 import BeautifulSoup
  12. from telegram.error import BadRequest
  13. from imap_tools import MailBox, AND, OR
  14. #-> for python 3.10, the dh key too small problem
  15. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
  16. context.set_ciphers('DEFAULT@SECLEVEL=1')
  17. config = configparser.ConfigParser()
  18. config.read('bot')
  19. bot = telegram.Bot(token=config['AUTH']['token'])
  20. bot2 = telegram.Bot(token=config['AUTH']['bank'])
  21. mailbox = MailBox(host=config['email']['host'], ssl_context=context)
  22. mailbox2 = MailBox(host=config['email']['host'], ssl_context=context)
  23. def pretty_exc():
  24. exc_type, _exc_obj, exc_tb = sys.exc_info()
  25. # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
  26. for tb in list(traceback.format_exception(exc_type, _exc_obj, exc_tb)):
  27. print(tb)
  28. def mask(msg, to_):
  29. return any([to_ == msg.from_,
  30. to_ in msg.to,
  31. to_ in msg.cc,
  32. to_ in msg.bcc])
  33. def mask2(msg, to_):
  34. return any([to_ == msg.from_,
  35. to_ in msg.to,
  36. to_ in msg.cc,
  37. to_ in msg.bcc,
  38. to_ in msg.subject])
  39. def mail_alert(event):
  40. '''mail alert Inbox'''
  41. container = deque(maxlen=500)
  42. bot = telegram.Bot(token=config['AUTH']['token'])
  43. mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='Inbox')
  44. while not event.is_set():
  45. try:
  46. sleep(15)
  47. msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=False)]
  48. for msg in msgs:
  49. chk = mask(msg, 'levente.marton@mzk.ro')
  50. if chk:
  51. msg_text = msg.text
  52. if 'end of day extras/intraday' in msg.subject:
  53. msg_text = msg.text.replace('<br>', '\n')
  54. if msg.uid not in container:
  55. try:
  56. if len(msg.text) != 0:
  57. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text}')
  58. else:
  59. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html}')
  60. container.appendleft(msg.uid)
  61. print('message appended', len(container))
  62. except BadRequest:
  63. try:
  64. if len(msg.text) != 0:
  65. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text[:len(msg_text) // 5]}')
  66. else:
  67. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html[:len(msg.html) // 5]}')
  68. container.appendleft(msg.uid)
  69. print('message appended', len(container))
  70. except BadRequest:
  71. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\nMessage is too long')
  72. container.appendleft(msg.uid)
  73. print('message appended', len(container), '!! last message was to long !!')
  74. except Exception:
  75. mailbox.logout()
  76. pretty_exc()
  77. break
  78. except Exception:
  79. mailbox.logout()
  80. break
  81. def mail_alert2(event):
  82. container = deque(maxlen=500)
  83. mailbox2.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events')
  84. while not event.is_set():
  85. try:
  86. sleep(15)
  87. msgs = [msgs for msgs in mailbox2.fetch(AND(seen=False), mark_seen=True)]
  88. for msg in msgs:
  89. chk = mask2(msg, 'account')
  90. if chk:
  91. if msg.uid not in container:
  92. soup = BeautifulSoup(msg.html, 'html.parser')
  93. msg_text = soup.prettify().replace('<br/>', '').replace('<html>', '').replace('<head>', '').replace('</head>', '').replace('<body>', '').replace('<div>', '').replace('</div>', '').replace('</body>', '').replace('</html>', '')
  94. try:
  95. if len(msg.text) != 0:
  96. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
  97. else:
  98. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
  99. container.appendleft(msg.uid)
  100. print('message appended', len(container))
  101. except BadRequest:
  102. try:
  103. if len(msg.text) != 0:
  104. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
  105. else:
  106. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
  107. container.appendleft(msg.uid)
  108. print('message appended', len(container))
  109. except BadRequest:
  110. bot2.send_message(chat_id=config['AUTH']['chatid'], text=f'Message is too long')
  111. container.appendleft(msg.uid)
  112. print('message appended', len(container), '!! last message was to long !!')
  113. except Exception:
  114. mailbox2.logout()
  115. pretty_exc()
  116. break
  117. except Exception:
  118. # pretty_exc()
  119. mailbox2.logout()
  120. break
  121. if __name__ == '__main__':
  122. try:
  123. event = Event()
  124. mail_alert2(event=event)
  125. except KeyboardInterrupt:
  126. event.set()