'''Created Sep 28, 2021 Levi''' import configparser import sys import traceback import ssl from time import sleep from collections import deque import telegram import keyring from bs4 import BeautifulSoup from telegram.error import BadRequest from imap_tools import MailBox, AND #-> for python 3.10, the dh key too small problem context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context.set_ciphers('DEFAULT@SECLEVEL=1') config = configparser.ConfigParser() config.read('bot') bot = telegram.Bot(token=config['AUTH']['bank']) mailbox = MailBox(host=config['email']['host'], ssl_context=context) def pretty_exc(): exc_type, _exc_obj, exc_tb = sys.exc_info() # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] for tb in list(traceback.format_exception(exc_type, _exc_obj, exc_tb)): print(tb) def mask(msg, to_): return any([to_ == msg.from_, to_ in msg.to, to_ in msg.cc, to_ in msg.bcc, to_ in msg.subject]) def mail_alert(): container = deque(maxlen=500) mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events') while True: try: sleep(15) msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=True)] for msg in msgs: chk = mask(msg, 'account') if chk: if msg.uid not in container: soup = BeautifulSoup(msg.html, 'html.parser') msg_text = soup.prettify().replace('
', '').replace('', '').replace('', '').replace('', '').replace('', '').replace('
', '').replace('
', '').replace('', '').replace('', '') try: if len(msg.text) != 0: bot.send_message(chat_id=config['AUTH']['chatid'], text=msg_text) else: bot.send_message(chat_id=config['AUTH']['chatid'], text=msg_text) container.appendleft(msg.uid) print('message appended', len(container)) except BadRequest: try: if len(msg.text) != 0: bot.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5) else: bot.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5) container.appendleft(msg.uid) print('message appended', len(container)) except BadRequest: bot.send_message(chat_id=config['AUTH']['chatid'], text=f'Message is too long') container.appendleft(msg.uid) print('message appended', len(container), '!! last message was to long !!') except Exception: mailbox.logout() pretty_exc() break except Exception: # pretty_exc() mailbox.logout() break if __name__ == '__main__': mail_alert() # mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events') # msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=True, reverse=True)] # for msg in msgs: # chk = mask(msg, 'account') # if chk: # print(msg.uid, msg.subject) # msg = msgs[0] # soup = BeautifulSoup(msg.html, 'html.parser') # print(soup.prettify().replace('
', ''))