mail_alert.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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
  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. while not event.is_set():
  48. try:
  49. mailbox = MailBox(host=config['email']['host'], ssl_context=context)
  50. mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='Inbox')
  51. sleep(15)
  52. msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=False)]
  53. for msg in msgs:
  54. chk = mask(msg, 'levente.marton@mzk.ro')
  55. if chk:
  56. msg_text = msg.text
  57. if 'end of day extras/intraday' in msg.subject:
  58. msg_text = msg.text.replace('<br>', '\n')
  59. if msg.uid not in container:
  60. try:
  61. if len(msg.text) != 0:
  62. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text}')
  63. else:
  64. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html}')
  65. container.appendleft(msg.uid)
  66. print('message appended', len(container))
  67. except BadRequest:
  68. try:
  69. if len(msg.text) != 0:
  70. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text[:len(msg_text) // 5]}')
  71. else:
  72. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html[:len(msg.html) // 5]}')
  73. container.appendleft(msg.uid)
  74. print('message appended', len(container))
  75. except BadRequest:
  76. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\nMessage is too long')
  77. container.appendleft(msg.uid)
  78. print('message appended', len(container), '!! last message was to long !!')
  79. except Exception:
  80. try:
  81. mailbox.logout()
  82. pretty_exc()
  83. except IMAP4.abort:
  84. pass
  85. # break
  86. mailbox.logout()
  87. except Exception:
  88. try:
  89. mailbox.logout()
  90. except IMAP4.abort:
  91. pass
  92. # break
  93. # finally:
  94. # mailbox.logout()
  95. def mail_alert2(event=None):
  96. container = deque(maxlen=500)
  97. while not event.is_set():
  98. try:
  99. mailbox2 = MailBox(host=config['email']['host'], ssl_context=context)
  100. mailbox2.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events')
  101. sleep(15)
  102. msgs = [msgs for msgs in mailbox2.fetch(AND(seen=False), mark_seen=True)]
  103. for msg in msgs:
  104. chk = mask2(msg, 'account')
  105. if chk:
  106. if msg.uid not in container:
  107. soup = BeautifulSoup(msg.html, 'html.parser')
  108. msg_text = soup.prettify().replace('<br/>', '').replace('<html>', '').replace('<head>', '').replace('</head>', '').replace('<body>', '').replace('<div>', '').replace('</div>', '').replace('</body>', '').replace('</html>', '')
  109. try:
  110. if len(msg.text) != 0:
  111. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
  112. else:
  113. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
  114. container.appendleft(msg.uid)
  115. print('message appended', len(container))
  116. except BadRequest:
  117. try:
  118. if len(msg.text) != 0:
  119. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
  120. else:
  121. bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
  122. container.appendleft(msg.uid)
  123. print('message appended', len(container))
  124. except BadRequest:
  125. bot2.send_message(chat_id=config['AUTH']['chatid'], text=f'Message is too long')
  126. container.appendleft(msg.uid)
  127. print('message appended', len(container), '!! last message was to long !!')
  128. except Exception:
  129. try:
  130. mailbox2.logout()
  131. pretty_exc()
  132. except IMAP4.abort:
  133. pass
  134. # break
  135. mailbox2.logout()
  136. except Exception:
  137. # pretty_exc()
  138. try:
  139. mailbox2.logout()
  140. except IMAP4.abort:
  141. pass
  142. # break
  143. # finally:
  144. # mailbox2.logout()
  145. def mail_alert3(event=None):
  146. '''mail alert Inbox'''
  147. container = deque(maxlen=500)
  148. while not event.is_set():
  149. try:
  150. mailbox3 = MailBox(host=config['email']['host'], ssl_context=context)
  151. mailbox3.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='API')
  152. sleep(15)
  153. msgs = [msgs for msgs in mailbox3.fetch(AND(seen=False), mark_seen=True)]
  154. for msg in msgs:
  155. chk = mask(msg, 'Ciel_notifier@mzk.ro')
  156. if chk:
  157. msg_text = msg.text
  158. # if 'end of day extras/intraday' in msg.subject:
  159. # msg_text = msg.text.replace('<br>', '\n')
  160. if msg.uid not in container:
  161. try:
  162. if len(msg.text) != 0:
  163. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text}')
  164. else:
  165. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html}')
  166. container.appendleft(msg.uid)
  167. print('message appended', len(container))
  168. except BadRequest:
  169. try:
  170. if len(msg.text) != 0:
  171. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text[:len(msg_text) // 5]}')
  172. else:
  173. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html[:len(msg.html) // 5]}')
  174. container.appendleft(msg.uid)
  175. print('message appended', len(container))
  176. except BadRequest:
  177. bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\nMessage is too long')
  178. container.appendleft(msg.uid)
  179. print('message appended', len(container), '!! last message was to long !!')
  180. except Exception:
  181. try:
  182. mailbox3.logout()
  183. pretty_exc()
  184. except IMAP4.abort:
  185. pass
  186. # break
  187. mailbox3.logout()
  188. except Exception:
  189. try:
  190. mailbox3.logout()
  191. except IMAP4.abort:
  192. pass
  193. # break
  194. # finally:
  195. # mailbox3.logout()
  196. if __name__ == '__main__':
  197. try:
  198. event = Event()
  199. mail_alert2(event=event)
  200. except KeyboardInterrupt:
  201. event.set()