mail_alert.py 9.7 KB

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