mail_alert.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. mailbox3 = MailBox(host=config['email']['host'], ssl_context=context)
  24. mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='Inbox')
  25. mailbox2.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events')
  26. mailbox3.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='API')
  27. def pretty_exc():
  28. exc_type, _exc_obj, exc_tb = sys.exc_info()
  29. # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
  30. for tb in list(traceback.format_exception(exc_type, _exc_obj, exc_tb)):
  31. print(tb)
  32. def mask(msg, to_):
  33. return any([to_ == msg.from_,
  34. to_ in msg.to,
  35. to_ in msg.cc,
  36. to_ in msg.bcc])
  37. def mask2(msg, to_):
  38. return any([to_ == msg.from_,
  39. to_ in msg.to,
  40. to_ in msg.cc,
  41. to_ in msg.bcc,
  42. to_ in msg.subject])
  43. def mail_alert(event=None):
  44. '''mail alert Inbox'''
  45. container = deque(maxlen=500)
  46. # mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='Inbox')
  47. while not event.is_set():
  48. try:
  49. sleep(15)
  50. msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=False)]
  51. for msg in msgs:
  52. chk = mask(msg, 'levente.marton@mzk.ro')
  53. if chk:
  54. msg_text = msg.text
  55. if 'end of day extras/intraday' in msg.subject:
  56. msg_text = msg.text.replace('<br>', '\n')
  57. if msg.uid not in container:
  58. try:
  59. if len(msg.text) != 0:
  60. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text}')
  61. else:
  62. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html}')
  63. container.appendleft(msg.uid)
  64. print('message appended', len(container))
  65. except BadRequest:
  66. try:
  67. if len(msg.text) != 0:
  68. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text[:len(msg_text) // 5]}')
  69. else:
  70. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html[:len(msg.html) // 5]}')
  71. container.appendleft(msg.uid)
  72. print('message appended', len(container))
  73. except BadRequest:
  74. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\nMessage is too long')
  75. container.appendleft(msg.uid)
  76. print('message appended', len(container), '!! last message was to long !!')
  77. except Exception:
  78. mailbox.logout()
  79. pretty_exc()
  80. # break
  81. except Exception:
  82. mailbox.logout()
  83. # break
  84. # finally:
  85. # mailbox.logout()
  86. def mail_alert2(event=None):
  87. container = deque(maxlen=500)
  88. # mailbox2.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events')
  89. while not event.is_set():
  90. try:
  91. sleep(15)
  92. msgs = [msgs for msgs in mailbox2.fetch(AND(seen=False), mark_seen=True)]
  93. for msg in msgs:
  94. chk = mask2(msg, 'account')
  95. if chk:
  96. if msg.uid not in container:
  97. soup = BeautifulSoup(msg.html, 'html.parser')
  98. msg_text = soup.prettify().replace('<br/>', '').replace('<html>', '').replace('<head>', '').replace('</head>', '').replace('<body>', '').replace('<div>', '').replace('</div>', '').replace('</body>', '').replace('</html>', '')
  99. try:
  100. if len(msg.text) != 0:
  101. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
  102. else:
  103. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
  104. container.appendleft(msg.uid)
  105. print('message appended', len(container))
  106. except BadRequest:
  107. try:
  108. if len(msg.text) != 0:
  109. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
  110. else:
  111. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
  112. container.appendleft(msg.uid)
  113. print('message appended', len(container))
  114. except BadRequest:
  115. bot2.send_message(chat_id=config['AUTH']['chatid'], text=f'Message is too long')
  116. container.appendleft(msg.uid)
  117. print('message appended', len(container), '!! last message was to long !!')
  118. except Exception:
  119. mailbox2.logout()
  120. pretty_exc()
  121. # break
  122. except Exception:
  123. # pretty_exc()
  124. mailbox2.logout()
  125. # break
  126. # finally:
  127. # mailbox2.logout()
  128. def mail_alert3(event=None):
  129. '''mail alert Inbox'''
  130. container = deque(maxlen=500)
  131. # mailbox3.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='API')
  132. while not event.is_set():
  133. try:
  134. sleep(15)
  135. msgs = [msgs for msgs in mailbox3.fetch(AND(seen=False), mark_seen=True)]
  136. for msg in msgs:
  137. chk = mask(msg, 'Ciel_notifier@mzk.ro')
  138. if chk:
  139. msg_text = msg.text
  140. # if 'end of day extras/intraday' in msg.subject:
  141. # msg_text = msg.text.replace('<br>', '\n')
  142. if msg.uid not in container:
  143. try:
  144. if len(msg.text) != 0:
  145. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text}')
  146. else:
  147. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html}')
  148. container.appendleft(msg.uid)
  149. print('message appended', len(container))
  150. except BadRequest:
  151. try:
  152. if len(msg.text) != 0:
  153. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text[:len(msg_text) // 5]}')
  154. else:
  155. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html[:len(msg.html) // 5]}')
  156. container.appendleft(msg.uid)
  157. print('message appended', len(container))
  158. except BadRequest:
  159. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\nMessage is too long')
  160. container.appendleft(msg.uid)
  161. print('message appended', len(container), '!! last message was to long !!')
  162. except Exception:
  163. mailbox3.logout()
  164. pretty_exc()
  165. # break
  166. except Exception:
  167. mailbox3.logout()
  168. # break
  169. # finally:
  170. # mailbox3.logout()
  171. if __name__ == '__main__':
  172. try:
  173. event = Event()
  174. mail_alert2(event=event)
  175. except KeyboardInterrupt:
  176. event.set()