def handle_ranklog(root, file): filename = os.path.join(root, file) print("Handling ranklog: " + filename) openfile = open(filename, "r") lines = openfile.readlines() winner = None winner_score = None winner_email = None losers = None losers_score = None losers_email = None turns = None for line in lines: if line[:7] == "winners": winner = line[9:].split(",")[1] winner_score = line[9:].split(",")[3] winner_email = find_email_address(winner) if line[:6] == "losers": losers = line[8:].split(",")[1] losers_score = line[8:].split(",")[3] losers_email = find_email_address(losers) if losers_email != None and winner_email != None: m = MailSender() m.send_game_result_mail(winner, winner_score, winner_email, losers, losers_score, losers_email) status.ranklog_emails_sent += 1 else: print("error: game with winner without email in " + file) openfile.close() os.remove(filename)
def handle_savegame(root, file): time.sleep(1) filename = os.path.join(root, file) print("Handling savegame: " + filename) txt = None with lzma.open(filename, mode="rt") as f: txt = f.read().split("\n") status.savegames_read += 1 new_filename = "pbem_processed_" + str(random.randint(0, 10000000000)) + ".xz" f.close() shutil.move(filename, os.path.join(root, new_filename)) print("New filename will be: " + new_filename) players = list_players(txt) phase = find_phase(txt) turn = find_turn(txt) game_id = find_game_id(txt) state = find_state(txt) print("game_id=" + str(game_id)) print("phase=" + str(phase)) print("turn=" + str(turn)) print("state=" + str(state)) print("players=" + str(players)) active_player = players[phase] print("active_player=" + active_player) active_email = find_email_address(active_player) status.games[game_id] = [turn, phase, players, time.ctime(), int(time.time()), state] if active_email != None: print("active email=" + active_email) m = MailSender() m.send_email(active_player, players, active_email, new_filename.replace(".xz", ""), turn) status.emails_sent += 1
def send_mails(data): maintext = "\n".join((str(t) for t in sorted(data))) with open("emails.txt") as f: mails = [line.strip() for line in f] with open(conf.get("DEFAULT", "email_template")) as f: tmpl = f.read() # unpacks all variables from the general config and passes them as key-value pairs body = tmpl.format( list=maintext, **{k: v for d in map(dict, dict(conf).values()) for k, v in d.items()}) host, usr, pwd, sender = itemgetter("smtp_server", "smtp_username", "smtp_pwd", "sender_email")(credentials["email"]) mailsender = MailSender(host, usr, pwd, sender) print(body) print(f"\nSending {len(mails)} Emails", end="") try: with mailsender: for mail in mails: mailsender.sendmail(mail, body) except SMTPAuthenticationError: error("EmailAuthentication Failed. No emails sent.") except socket.gaierror: warning("No network connection") print("\rEmails sent ")
def handle_ranklog(root, file): filename = os.path.join(root,file) print("Handling ranklog: " + filename); openfile = open(filename, 'r') lines = openfile.readlines() winner = None; winner_score = None; winner_email = None; losers = None; losers_score = None; losers_email = None; turns = None; for line in lines: if (line[:7]=='winners'): winner = line[9:].split(",")[1]; winner_score = line[9:].split(",")[3]; winner_email = find_email_address(winner); if (line[:6]=='losers'): losers = line[8:].split(",")[1]; losers_score = line[8:].split(",")[3]; losers_email = find_email_address(losers); if (losers_email != None and winner_email != None): m = MailSender(); m.send_game_result_mail(winner, winner_score, winner_email, losers, losers_score, losers_email); status.ranklog_emails_sent += 1; else: print("error: game with winner without email in " + file); openfile.close(); os.remove(filename);
def mail_server(username, password): sender = username mail_sender = MailSender(username, password) logger.info('Mail server initialized and running sucessful') while True: try: if keyboard.is_pressed('ENTER'): # if pir.motion_detected: try: cam.saveSnapshot('image.jpg', timestamp=1) # capture() images = [{'id': 'Person', 'path': 'image.jpg'}] logger.info('Sending photo via email') mail_sender.send(sender, ['*****@*****.**'], 'Person alert!', images=images) logger.info('Photo send to [email protected]') except: logger.error('Photo send via email failed') if keyboard.is_pressed('Ctrl + c'): logger.info('Ctrl + c pressed exiting program') sys.exit(0) except: break
def handle_savegame(root, file): filename = os.path.join(root,file) print("Handling savegame: " + filename); txt = None; with lzma.open(filename, mode="rt") as f: txt = f.read().split("\n"); status.savegames_read += 1; new_filename = "pbem_processed_" + str(random.randint(0,10000000000)) + ".xz"; f.close(); shutil.move(filename, os.path.join(root,new_filename)) print("New filename will be: " + new_filename); players = list_players(txt); phase = find_phase(txt); turn = find_turn(txt); game_id = find_game_id(txt); print("game_id=" + str(game_id)); print("phase=" + str(phase)); print("turn=" + str(turn)); print("players=" + str(players)); active_player = players[phase]; print("active_player=" + active_player); active_email = find_email_address(active_player); status.games[game_id] = [turn, phase, players, time.ctime()]; if (active_email != None): print("active email=" + active_email); m = MailSender(); m.send_email(active_player, players, active_email, new_filename.replace(".xz", ""), turn); status.emails_sent += 1;
def handle_savegame(root, file): time.sleep(1); filename = os.path.join(root,file) print("Handling savegame: " + filename); txt = None; with lzma.open(filename, mode="rt") as f: txt = f.read().split("\n"); status.savegames_read += 1; new_filename = "pbem_processed_" + str(random.randint(0,10000000000)) + ".xz"; f.close(); shutil.move(filename, os.path.join(root,new_filename)) print("New filename will be: " + new_filename); players = list_players(txt); phase = find_phase(txt); turn = find_turn(txt); game_id = find_game_id(txt); state = find_state(txt); print("game_id=" + str(game_id)); print("phase=" + str(phase)); print("turn=" + str(turn)); print("state=" + str(state)); print("players=" + str(players)); active_player = players[phase]; print("active_player=" + active_player); active_email = find_email_address(active_player); status.games[game_id] = [turn, phase, players, time.ctime(), int(time.time()), state]; if (active_email != None): print("active email=" + active_email); m = MailSender(); m.send_email(active_player, players, active_email, new_filename.replace(".xz", ""), turn); status.emails_sent += 1;
def send_email_to_customer(): # Message subject success = 'Ваш отчёт готов!' # Retrieve occupation name and email address order_customer, occupation = get_email_from_mongo() # Retrieve a hyperlink to the xlsx report file message = get_href_from_mongo(occupation) mail = MailSender([mail_creds['admin'], order_customer], success, message) mail.send_email()
def update_callback(updated_webpages, credentials, email_recipients, email_enabled): msg = '' data_path = os.path.join(os.path.dirname(sys.argv[0]), 'data') for p in updated_webpages: p.toFile(data_path) msg += p.getData(strip_header=False) updated_webpages.remove(p) logger.debug('Notification:\n' + msg) if email_enabled: mailer = MailSender(credentials) mailer.send(msg, email_recipients) else: logger.info('[>] EMAIL THAT WOULD BE SENT:\n%s\n' % msg)
def get_orders_from_mongo(): # Instantiate MongoDB connection context with MongoClient(mongo) as mongodb: # Connection to 'notify' collection of 'hh_orders' database collection = mongodb.hh_orders['notify'] # Search for orders orders = list(collection.find({})) # Lists content of vacancies directory vacancies = get_reports_list('vacancies') # Lists content of resumes directory resumes = get_reports_list('resumes') if orders: for order in orders: # If it's vacancy order if order.get('occupation' ) in vacancies and 'occupation' in order.keys(): # If completes successfully, # notificates application admin and order customer order_customer = order.get('customer') mail = MailSender([mail_creds['admin'], order_customer], success, order.get('occupation')) mail.send_email() change_order_status(order) # If it's resume order if order.get( 'criteria') in resumes and 'criteria' in order.keys(): # If completes successfully, # notificates application admin and order customer order_customer = order.get('customer') mail = MailSender([mail_creds['admin'], order_customer], success, order.get('criteria')) mail.send_email() change_order_status(order)
def add_order_to_mongo(email, occupation=None, criteria=None): # Instantiate MongoDB connection context with MongoClient(mongo) as mongodb: # Connection to 'orders' collection of 'hh_reports' database collection = mongodb.hh_reports['orders'] # Put request order if occupation: # If vacancy request order = {'customer': email, 'occupation': occupation} # Add order to MongoDB collection.insert(order) # Send mail notification subject = 'Laboranalysis application gets the new order' # To admin, with above subject and 'order' body mail = MailSender( [mail_creds['admin']], subject, str(order) ) mail.send_email() else: # If resume request order = {'customer': email, 'criteria': criteria} # Add order to MongoDB collection.insert(order) # Send mail notification subject = 'Laboranalysis application gets the new order' # To admin, with above subject and 'order' body mail = MailSender( [mail_creds['admin']], subject, str(order) ) mail.send_email()
def test_constructor(self, mock_work_queue_connection): mail_sender = MailSender(config=Mock()) mock_channel = mail_sender.channel # Declare and bind email and retry exchanges/queues mock_channel.exchange_declare.assert_has_calls([ call('EmailExchange', 'direct'), call('RetryExchange', 'direct'), ]) mock_channel.queue_declare.assert_has_calls([ call(queue='EmailQueue'), call( queue='RetryQueue', arguments={'x-dead-letter-exchange': 'EmailExchange'}, ), ]) mock_channel.queue_bind.assert_has_calls([ call(exchange='EmailExchange', queue='EmailQueue', routing_key='SendEmail'), call(exchange='RetryExchange', queue='RetryQueue', routing_key='SendEmail') ]) # call email_call when a message shows up in EmailQueue mock_channel.basic_consume.assert_called_with( mail_sender.email_callback, queue='EmailQueue', no_ack=True)
def test_email_callback_with_one_retry(self, mock_bespin_api, mock_work_queue_connection): mock_bespin_api.return_value.email_message_send.side_effect = [ requests.HTTPError() ] mail_sender = MailSender( config=Mock(email_retry_count=1, retry_wait_ms=2000)) mail_sender.email_callback(None, None, None, pickle.dumps({'send_email': '5'})) mock_bespin_api.return_value.email_message_send.assert_has_calls( [call('5')]) args, kwargs = mail_sender.channel.basic_publish.call_args sent_body = pickle.loads(kwargs['body']) self.assertEqual(sent_body['send_email'], '5') self.assertEqual(sent_body['retry_count'], 0) # retry count should be decremented self.assertEqual(kwargs['properties'].expiration, 2000) self.assertEqual(kwargs['routing_key'], 'SendEmail')
def post(self): req_ip = self.request.headers.get("X-Real-IP", "missing"); self.mailchecker.invitation_emails_sent += 1; invite_to = self.get_argument("to", None, True); action=self.get_argument("action", None, True); print("request from " + req_ip + " to " + invite_to); self.ratelimit(); if (self.mailchecker.last_invitation == invite_to): self.set_status(502); print("error: invitation to same e-mail twice."); return; self.mailchecker.last_invitation = invite_to; if (action == "invite"): invite_from = self.get_argument("from", None, True) if (invite_from != None and invite_to != None and "@" in invite_to and len(invite_from) < 50 and len(invite_to) < 50): m = MailSender(); m.send_invitation(invite_from, invite_to); self.write("done!");
def price_scrapper(): URL = 'https://www.vans.com.br/sapatos/tenis/tenis-old-skool/p/1002001070011U' price_scrapper = PriceScrapper(URL) soup = price_scrapper.load_page() title = soup.find(class_='product-title lighter').get_text() price = soup.find(class_='product-cash-price').get_text() #size = soup.find(id_='variant-size-41').get('value').get_text() regular_price = 329.0 converted_price = float(price[2:5]) if (converted_price < regular_price): print(title, 'new price: R$', converted_price) if (MailSender.check_send_toggle(MailSender)): MailSender.send_mail(MailSender, URL, title, price) else: print(title, "price is still at: " + price)
def run() -> None: if args.command == "config": MailSender( sender=args.user, password=args.password, server=args.server, ) else: MailSender( sender=args.user, password=args.password, server=args.server, ).send( to=args.to, header=args.subject, content=args.content, content_type=args.content_type, )
def post(self): req_ip = self.request.headers.get("X-Real-IP", "missing") self.mailchecker.invitation_emails_sent += 1 invite_to = self.get_argument("to", None, True) action = self.get_argument("action", None, True) print("request from " + req_ip + " to " + invite_to) self.ratelimit() if (self.mailchecker.last_invitation == invite_to): self.set_status(502) print("error: invitation to same e-mail twice.") return self.mailchecker.last_invitation = invite_to if (action == "invite"): invite_from = self.get_argument("from", None, True) if (invite_from != None and invite_to != None and "@" in invite_to and len(invite_from) < 50 and len(invite_to) < 50): m = MailSender() m.send_invitation(invite_from, invite_to) self.write("done!")
def start_parse(order): # Try to make processing on geted order try: # Import our vacancy processing class from resumehandler import ResumeHandler resumes = ResumeHandler(order.get('criteria')) # Start retrievement with delay resumes._resumes_retriever(delay=30, number=None) resumes.store_resumes_to_mongo() change_order_status(order) # If run into an issue, notificates application admin except: mail = MailSender([mail_creds['admin']], problem, str(order)) mail.send_email() # If completes successfully, notificates application admin mail = MailSender([mail_creds['admin']], success, order.get('criteria')) mail.send_email()
def start_request(order): # Try to make processing on geted order try: # Import our vacancy processing class from vacancyhandler import VacancyHandler vacancies = VacancyHandler(order.get('occupation')) # Start retrievement with delay vacancies._vacancies_retriever(delay=10, number=None) vacancies.store_vacancies_to_mongo() change_order_status(order) # If run into an issue, notificates application admin except: mail = MailSender([mail_creds['admin']], problem, str(order)) mail.send_email() # If completes successfully, notificates application admin mail = MailSender([mail_creds['admin']], success, order.get('occupation')) mail.send_email()
def start_resumes_analyze(order): # Try to make processing on geted order try: # Import our vacancy processing class from resumehandler import ResumeHandler resumes = ResumeHandler(order.get('criteria')) resumes.restore_resumes_from_mongo() resumes.analyze() resumes.store_results_to_xlsx() change_order_status(order) # If run into an issue, notificates application admin except: mail = MailSender([mail_creds['admin']], problem, str(order)) mail.send_email() # If completes successfully, notificates application admin mail = MailSender([mail_creds['admin']], success, order.get('criteria')) mail.send_email()
def start_request(order): # Try to make processing on geted order try: # Import our vacancy processing class from laboranalysis.vacancyhandler import VacancyHandler vacancies = VacancyHandler(order.get('occupation')) vacancies.analyze() vacancies.store_vacancies_to_mongo() vacancies.store_results_to_xlsx() change_order_status(order) # If run into an issue, notificates application admin except: mail = MailSender([mail_creds['admin']], problem, str(order)) mail.send_email() # If completes successfully, # notificates application admin and order customer order_customer = order.get('customer') mail = MailSender([mail_creds['admin'], order_customer], success, order.get('occupation')) mail.send_email()
savedir = settings.get("Config", "savegame_directory"); rankdir = settings.get("Config", "ranklog_directory"); host = settings.get("Config", "host"); # load game status from file. loaded_games = {}; try: if (os.path.isfile('pbem-games.json')): with open('pbem-games.json') as data_file: loaded_games = json.load(data_file) except Exception as e: print(e); mail = MailSender(); status = MailStatus() status.savegames_read = 0; status.emails_sent = 0; status.reminders_sent = 0; status.ranklog_emails_sent = 0; status.invitation_emails_sent = 0; status.retired = 0; status.games = loaded_games; status.expiry = game_expire_time; # send reminder where game is about to expire def remind_old_games(): for key, value in status.games.items(): if (value['reminder_sent'] == False and (value['time_int'] + game_remind_time) < (time.time())):
def send_email_to_customer(order): # Message subject subject = 'Laboranalysis application gets the new order' # To admin, with above subject and 'order' body mail = MailSender([mail_creds['admin']], subject, str(order)) mail.send_email()
known_face_encondings = [face_encoding] known_face_names = ["Harish"] led = LED(14) led.on() sleep(1) led.off() pir = MotionSensor(4) logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO) logger = logging.getLogger(__name__) username = '******' password = '******' sender = username mail_sender = MailSender(username, password) state = 0 process_this_frame = True while True: ret, frame = video_capture.read() small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) rgb_small_frame = small_frame[:, :, ::-1] if process_this_frame: face_locations = fr.face_locations(rgb_small_frame) face_encodings = fr.face_encodings(rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: matches = fr.compare_faces(known_face_encondings, face_encoding) name = "Unknown" face_distances = fr.face_distance(known_face_encondings, face_encoding) best_match_index = np.argmin(face_distances)
#print the compnaies info debug for company in companies: if company.is_expired: status = f'EXPIRED on {company.get_exp_date_str()}' else: status = f'Expiry date: {company.get_exp_date_str()}' print(f'{company} - {status} {company.tte_days} to expiry') print() #creds smtphost = 'smtp.mail.yahoo.com' sender_email = '*****@*****.**' sender_pw = 'hcsxjloxlclhpejl' port = 465 sender = MailSender(sender_email, sender_pw, smtphost, port) #ehlo the server sender.connect() email_txts = {42: {'company': [], 'txt': '6wks.txt'}, 14: {'company': [], 'txt': '2wks.txt'},\ 0: {'company': [], 'txt':'today.txt'}} ##test cases testcomp1 = {'license': 'PE123456', 'name': 'testcomp1', 'expiry_date': '26/01/2021', \ 'email': '*****@*****.**'} companies.append(database.Company(testcomp1)) testcomp2 = {'license': 'PE123457', 'name': 'testcomp2', 'expiry_date': '9/2/2021', \ 'email': '*****@*****.**'}
def test_email_callback_works_first_time(self, mock_bespin_api, mock_work_queue_connection): mail_sender = MailSender(config=Mock()) mail_sender.email_callback(None, None, None, pickle.dumps({'send_email': '5'})) mock_bespin_api.return_value.email_message_send.assert_called_with('5')
def main(): parser = argparse.ArgumentParser() parser.add_argument('action', choices=['generate', 'check', 'send'], help='action to perform') parser.add_argument('config_filename', help='name of the YAML configuration file') args = parser.parse_args() if args.action == 'generate': pass #TODO handle generate option to create barebone YAML file with open(args.config_filename) as f: config = yaml.safe_load(f) log_filename = os.path.splitext(args.config_filename)[0] + '.log' start_datetime = get_last_update_datetime_from_log(log_filename) end_datetime = get_datetime() with open(log_filename, 'a') as logfile: if start_datetime is None: start_datetime = end_datetime log(logfile, f'last updated on {end_datetime.strftime(_datetime_format)}', verbose=False) start_datetime = start_datetime + timedelta(minutes=1) calendrical.add_next_dates_and_times(config, start_datetime) if args.action == 'check': messages = calendrical.next_dates(config) print(f'YAML is valid.') if messages: print('\nNext messages:') for message in messages: print( f" {message['when'].strftime(_datetime_format)} {message['rule']}" ) print('') with MailSender(from_email=config['smtp_email'], host=config['smtp_host']) as sender: pass # validate password only print(f'SMTP credentials are valid.') if args.action == 'send': log(logfile, f'starting from {start_datetime.strftime(_datetime_format)}') messages = calendrical.messages_before(config, end_datetime) if messages: log(logfile, f'connecting to SMTP server') with MailSender(from_email=config['smtp_email'], host=config['smtp_host'], passive=True) as sender: for message in messages: log( logfile, f"sending {message['subject']} to {config['recipient_email']}" ) sender.send(config['recipient_email'], message['subject'], message['body']) log(logfile, f'last updated on {end_datetime.strftime(_datetime_format)}')
writer = csv.writer(file) writer.writerow([serial, name, batch, contact, email]) file = open('serial.txt', 'w') serial = int(serial) + 1 file.write(str(serial)) file.close() from mailsender import MailSender username = '******' password = '******' sender = username images = list() images.append({'id': 'logo', 'path': 'output.jpg'}) with open('template.html') as template_html, open( 'template.txt') as template_plain: message_html = template_html.read() message_plain = template_plain.read() mail_sender = MailSender(username, password) mail_sender.send(sender, [email], 'Lucky draw ticket.', message_html=message_html, message_plain=message_plain, images=images) print('..') os.remove("output.jpg") print('Email Send')
def is_anonymous(self): return self.anonymous def get_id(self): """Return a unicode object that repsresents the users id""" return self.id #Tillfällig lösning ska egentligen sparas i DATABAS users_lst = [] user_emails = {"*****@*****.**": User("*****@*****.**", "pass")} @login_manager.user_loader def load_user(user_id): """Login manager, functionality required for flask_login. Tracks user IDs and delegates new user IDs.""" print(user_id, users_lst) for i in range(len(users_lst) - 1, 0, -1): print(users_lst[i].get_id()) if user_id == users_lst[i].get_id(): return users_lst[i] return None if __name__ == "__main__": """Sets up initial and necessary interfaces to interact with backend.""" manager, dbInterface = main.setUp() mail_sender = MailSender() app.run(debug=True)