def main(): current_time = datetime.now() current_month_and_yr = datetime.now().strftime("%B %Y") new_dir = make_directory(DESKTOP_PATH, current_month_and_yr) #capture = cv2.VideoCapture(-1) # needed dimensions scr_w, scr_h = get_monitor_res() # codec #fourcc = cv2.VideoWriter_fourcc(*"XVID") # path combined_save_path = new_dir + "\\combined_" + current_time.strftime( DATE_FILE_FORMAT) + FILE_EXT cap_class = Capture(-1, combined_save_path, [scr_w, scr_h]) #writer capture = cap_class.capture writer = cap_class.get_writer() while True: img = ImageGrab.grab() img_np = np.array(img) screen_frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB) # Capture frame-by-frame ret, cam_frame = capture.read() if not ret: break cv2.imshow("Frame", cam_frame) cam_frame_resized = cap_class.resize(cam_frame) cam_frame_merged = cap_class.merge_frame(cam_frame_resized) screen_frame_merged = cap_class.merge_frame(screen_frame) output = cap_class.get_output(cam_frame_merged, screen_frame_merged) writer.write(output) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break # When everything done, release the capture capture.release() writer.release() cv2.destroyAllWindows() # send email on certain date if datetime.now().day == SET_DAY: host, port, address, password = get_settings(SETTINGS_FILE) sender = EmailSender(host, port, address, password) message = "Monthly Email of Video Capture" sender.send_message(message=message, dt_file_path=new_dir, attach=True)
def update_incident(): data_str = request.stream.read() decoded = json.loads(data_str) incident_list = parse_incident(decoded) for incident in incident_list: short_msg = parse_short_status(incident) long_msg = parse_long_status(incident) # Email and SMS update to individual subscriber from SMSSender import SMSSender sms_client = SMSSender(short_msg, incident['gps_location']) sms_client.start() #print "SMS content: ", short_msg from EmailSender import EmailSender email_client = EmailSender('*****@*****.**', 'incidents', long_msg, incident['gps_location']) email_client.start() #print "Sent email", long_msg ret = { "success": True } return jsonify(ret)
def run(self): first_time = True logger.info('CityThread start, cityid=%s, zoneid=%s'%(City_Id, Zone_Id)) while True: city_info = self.get_city_info(City_Id, Zone_Id) users = city_info['users'] logger.info('Get %d users'%(len(users))) if not first_time: # check new user for user in users: userId = user['userId'] userName = user['userName'] level = user['level'] if not uid_dict.has_key(userId): msg = 'Found new user name=%s level=%s'%(userName, level) logger.info(msg) es = EmailSender() es.send_mail(msg, '') es.close() else: first_time = False for user in users: userId = user['userId'] uid_dict[userId] = user logger.info('CityThread will sleep %d seconds'%(Sleep_Time)) time.sleep(Sleep_Time)
def send_verification_email(subscription): from EmailSender import EmailSender config = ConfigParser.ConfigParser() config.read(os.path.dirname(os.path.realpath(__file__)) + '/../../server.cfg') local_address = config.get('OS', 'subscribe') emailclient = EmailSender('*****@*****.**', 'incidents') emailclient.send_email_to(subscription.email, "Verification of Subscription", "Please click the link below to verify your registration." + local_address + "verify?hash=" + subscription.email_hash)
def test_mail(to_email, type, context): env = Environment(loader=FileSystemLoader(os.path.dirname(os.path.realpath(__file__)) + '/templates')) template = env.get_template('register.html') rendered = template.render(username=context['username']).encode('utf-8') email = Email(to_email, 'Subject', rendered) email_sender = EmailSender(env) email_sender.send_email(email)
def main(): print "Report server starts." email_client = EmailSender('*****@*****.**', 'incidents', "test") title = 'Crisis Report on ' + str(datetime.datetime.now()) file_name = ReportGenerator.generate_report() msg = "Dear officer, <br />" msg += "This is the incident report for the past 30 minutes. <br />" msg += "Regards, <br />" msg += "Crisis Management System Singapore" email_client.send_email_to("*****@*****.**", title, msg, file_name)
def test_mail(to_email, type, context): env = Environment(loader=FileSystemLoader( os.path.dirname(os.path.realpath(__file__)) + '/templates')) template = env.get_template('register.html') rendered = template.render(username=context['username']).encode('utf-8') email = Email(to_email, 'Subject', rendered) email_sender = EmailSender(env) email_sender.send_email(email)
class Registration: def __init__(self, db): self.db = db #using localhost as SMTP server self.email_sender = EmailSender("registration@pswdb", "localhost") def _validate_input(self, login, password, password_validation, name, last_name, email): error_message = [] if len(name) < 2 or len(last_name) < 2: error_message.append( "name and last name have to be at least 2 characters long") if not re.match(r"[^@]+@[^@]+\.[^@]+", email): error_message.append("incorrect e-mail address") if len(login) < 3: error_message.append("login has to be at least 3 characters long") if len(password) < 8: error_message.append( "password has to be at least 8 characters long") if password != password_validation: error_message.append("passwords do not match") if len(error_message) != 0: error_message = ", ".join(error_message) error_message = f"Error: {error_message}." raise Exception(error_message) def register(self, login, password, password_validation, name, last_name, email): self._validate_input(login, password, password_validation, name, last_name, email) new_user = User(0, name, last_name, login, password, email, "user", str(datetime.date.today())) if self.db.is_login_taken(new_user): raise Exception("Error: login already in use.") self.db.insert_user(new_user) try: self.email_sender.send_email(email, f"{name} {last_name}") except: return ("Warning!", "Account created, but confirmation mail couldn't be sent.") return ("Success!", "You created an account.")
def emailAboutBooksIfNecessary(self, toAccount, fromAccount, books): overdueBooks = [] dueTodayBooks = [] for dueDate in books: if datetime.strptime(dueDate, "%m/%d/%Y").date() < date.today(): for book in books[dueDate]: overdueBooks.append({'dueDate': dueDate, 'book': book}) if datetime.strptime(dueDate, "%m/%d/%Y").date() == date.today(): for book in books[dueDate]: dueTodayBooks.append(book) if len(overdueBooks) > 0 or len(dueTodayBooks) > 0: es = EmailSender() dueTodayString = "" overdueString = "" if len(dueTodayBooks) > 0: dueTodayString = "%d book%s due today" % (len(dueTodayBooks), "s" if len(dueTodayBooks) > 0 else "") if len(overdueBooks) > 0: overdueString = "%d book%s overdue" % (len(overdueBooks), "s" if len(overdueBooks) > 0 else "") summaryString = "" subjectString = "" if len(dueTodayBooks) > 0 and len(overdueBooks) > 0: summaryString = "%s and %s" % (dueTodayString, overdueString) else: summaryString = "%s%s" % (dueTodayString, overdueString) subject = message = "There %s %s at the library!" % ("is" if len(dueTodayBooks) + len(overdueBooks) == 1 else "are", summaryString, ) message += "\n" if len(dueTodayBooks) > 0: booksDueTodayString = "Due today:\n" for book in dueTodayBooks: booksDueTodayString += "%s %s\n" % (book["title"], book["author"]) message += booksDueTodayString if len(overdueBooks) > 0: overdueBooksString = "Overdue:\n" for bookStruct in overdueBooks: overdueBooksString += "%s %s - Due: %s\n" % (bookStruct["book"]["title"], bookStruct["book"]["author"], bookStruct["dueDate"]) message += overdueBooksString es.sendEmail(toAccount, fromAccount, subject, message)
def to_two_wave_result(i): logger.info('Run PID (%s)...' % os.getpid()) new_df, check_number_new_df = to_one_wave_result( rid_df_list_new[i], sku_df_list_new[i], answer_df_list_new[i], sku_verification_df_list_new[i], multi_option_df_list_new[i], year_new[i], i) old_df, check_number_old_df = to_one_wave_result( rid_df_list_old[i], sku_df_list_old[i], answer_df_list_old[i], sku_verification_df_list_old[i], multi_option_df_list_old[i], year_old[i], i) new_df = pd.merge(new_df, store_new_df, how='left', on='addressIDnum') old_df = pd.merge(old_df, store_old_df, how='left', on='addressIDnum') new_df = pd.merge(new_df, old_df, how='left', on='addressIDnum', suffixes=('', '_old')) new_df.drop_duplicates(subset='rid', inplace=True) new_df['check_total_shelf'] = new_df.apply( lambda x: check_vs_pp_total_shelf(x.total_shelf, x.total_shelf_old), axis=1) new_df['check_pg_shelf'] = new_df.apply( lambda x: check_vs_pp_pg_shelf(x.pg_shelf, x.pg_shelf_old), axis=1) new_df['check_pg_display'] = new_df.apply( lambda x: check_vs_pp_pg_display(x.total_display, x.pg_display, x.total_display_old, x.pg_display_old), axis=1) new_df['check_pg_sku'] = new_df.apply( lambda x: check_vs_pp_sku(i, x.actual_sku, x.actual_sku_old), axis=1) new_df['check_all'] = new_df.apply( lambda x: check_all(x.check_recent, x.shelf_display_verification_1, x.shelf_display_verification_2, x.sku_verification_count, x.check_total_shelf, x.check_pg_shelf, x.check_pg_display, x.check_pg_sku), axis=1) report_new_df = new_df.reindex(columns=report_order[i]) report_old_df = old_df.reindex(columns=report_order[i]) checkpoint_new_df = new_df.reindex(columns=checkpoint_order[i]) checkpoint_old_df = old_df.reindex(columns=checkpoint_order[i]) report_new_df.to_excel(new_file[i], category[i], columns=report_order[i], index=False) report_old_df.to_excel(old_file[i], category[i], columns=report_order[i], index=False) writer_checkpoint = pd.ExcelWriter(checkpoint_file[i]) checkpoint_new_df.to_excel(writer_checkpoint, category[i] + '_new', index=False) checkpoint_old_df.to_excel(writer_checkpoint, category[i] + '_old', index=False) check_number_new_df.to_excel(writer_checkpoint, category[i] + '_number_new', index=False) check_number_old_df.to_excel(writer_checkpoint, category[i] + '_number_old', index=False) writer_checkpoint.close() subject = category[i] + datetime.now().strftime('%Y-%m-%d') contents = ['附件中为前后两月数据及需检查的数据', ] attachments = [new_file[i], old_file[i], checkpoint_file[i]] with EmailSender(**email) as email_sender: email_sender.send_email(to=to, subject=subject, contents=contents, attachments=attachments) os.remove(new_file[i]) os.remove(old_file[i]) os.remove(checkpoint_file[i]) with MySQLInstance(**mysql_db_bi_task, dict_result=True) as db: db.executemany(sql_insert_report_new, [tuple(x) for x in new_df.reindex(columns=insert_table_order_new).values]) db.executemany(sql_insert_report_old, [tuple(x) for x in old_df.reindex(columns=insert_table_order_old).values])
def main(): subject = 'P&G_HSM_Checkpoint_' + month_three + '_' + datetime.now().strftime('%Y-%m-%d') contents = ['附件中为' + month_three + '全部对比复核数据', ] attachments = pd_file_one attachments.extend(pd_file_two) attachments.extend(sku_file) with EmailSender(**email) as email_sender: email_sender.send_email(to=to, subject=subject, contents=contents, attachments=attachments) store_info_df = query_data_frame(mysql_db_ppzck_task, sql_get_store_info) data = [] for index1 in range(8): data.append(pd.read_excel(file[index1], category[index1])) data[index1] = data[index1][data[index1]['check_sku'] == 1] data[index1].drop_duplicates(subset='addressIDnum', inplace=True) store_info_df = pd.merge(store_info_df, data[index1].reindex(columns=['addressIDnum', 'rid']), how='inner', on='addressIDnum', sort=False, copy=False) result = pd.concat(data) result['shelf_url'] = 'http://pc.ppznet.com/task_pc//shenhe/aicorrect/images.jsp?responseid=' + result['rid'] result_gb = result.groupby('addressIDnum').sum() result_gb.reset_index(inplace=True) result_gb['category'] = 'total' result = pd.concat([result, result_gb], sort=False) result['month'].fillna(method='ffill', inplace=True) store_info_df.drop(columns=store_info_df.columns[15:], inplace=True) result = pd.merge(store_info_df, result, how='inner', on='addressIDnum', sort=False, copy=False) engine = create_engine("mysql+pymysql://{}:{}@{}:{}/{}?charset={}".format( mysql_db_bi_task['username'], mysql_db_bi_task['password'], mysql_db_bi_task['host'], mysql_db_bi_task['port'], mysql_db_bi_task['schema'], 'utf8')) con = engine.connect() result.to_sql(name='t_pg_report_hsm_visualization', con=con, if_exists='replace', index=False) con.close() for i in range(8): os.remove(pd_file_one[i]) os.remove(pd_file_two[i]) os.remove(sku_file[i]) os.remove(file[i])
def main(): category = ['hair', 'pcc', 'laundry', 'oral', 'fem', 'baby', 'skin', 'br'] report_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), ('pg_hsm_report_' + month + '.xlsx')) writer = pd.ExcelWriter(report_path) report_file = [] report_data = [] report_data_number = [] for i in range(8): report_file.append( os.path.join( os.path.dirname(os.path.realpath('__file__')), ('pg_hsm_report_' + category[i] + '_' + month + '.xlsx'))) report_data.append(pd.read_excel(report_file[i], category[i])) for k in report_data[i].columns: if '_pic' in k: report_data[i][k] = report_data[i][k].map( lambda x: '' if pd.isna(x) else '=' + x) report_data[i].to_excel(writer, category[i], index=False) report_data_number.append( pd.read_excel(report_file[i], category[i] + '_number')) report_data_number[i].to_excel(writer, category[i] + '_number', index=False) os.remove(report_file[i]) writer.close() subject = 'P&G_HSM_Report_' + month + '_' + datetime.now().strftime( '%Y-%m-%d') contents = [ '附件中为' + month + '全部数据及需检查的数据', ] attachments = [report_path] with EmailSender(**email) as email_sender: email_sender.send_email(to=to, subject=subject, contents=contents, attachments=attachments)
def main(): cnx = mysqllib.get_connection() cursor = cnx.cursor() today = datetime.datetime.today() ts = today.strftime("%Y-%m-%d") sql = "select code, name from new_stock where `date`='%s'" % (ts) cursor.execute(sql) stocks = [] for (code, name) in cursor: stocks.append("%s-%s" % (code, name)) if len(stocks) > 0: ns = "申购新股:%s" % (' '.join([f.encode('utf-8') for f in stocks])) es = EmailSender() es.send_mail("申购新股", ns) es.close() utils.print_with_time(ns.decode('utf-8')) utils.print_with_time("Done") cursor.close() cnx.close()
def notify(msg): msg = USER_INFO[DEFAULT_USER]['USERNAME'] + ' --- ' + msg es = EmailSender() es.send_mail(msg, '') logger.info('Send an email: "%s"'%(msg)) es.close()
def __init__(self, db): self.db = db #using localhost as SMTP server self.email_sender = EmailSender("registration@pswdb", "localhost")
def to_two_wave_result(i): logger.info('Run PID (%s)...' % os.getpid()) sku_df_new = query_data_frame( mysql_db_ppzck_task, sql_get_sku % (task_new[i], time_selection_new, status_not_in_new)) answer_df_new = query_data_frame( mysql_db_ppzck_task, sql_get_answer % (task_new[i], time_selection_new, status_not_in_new)) sku_verification_df_new = query_data_frame( mysql_db_ppzck_task, sql_get_sku_verification % (task_new[i], time_selection_new, status_not_in_new)) sku_df_old = query_data_frame( mysql_db_ppzck_task, sql_get_sku % (task_old[i], time_selection_old, status_not_in_old)) answer_df_old = query_data_frame( mysql_db_ppzck_task, sql_get_answer % (task_old[i], time_selection_old, status_not_in_old)) sku_verification_df_old = query_data_frame( mysql_db_ppzck_task, sql_get_sku_verification % (task_old[i], time_selection_old, status_not_in_old)) sku_df_new.drop_duplicates(subset=['rid', 'product_id'], inplace=True) answer_df_new.drop_duplicates(subset=['rid', 'qid'], inplace=True) sku_df_old.drop_duplicates(subset=['rid', 'product_id'], inplace=True) answer_df_old.drop_duplicates(subset=['rid', 'qid'], inplace=True) if i == 0 or i == 1 or i == 2: multi_option_df_new = query_data_frame( mysql_db_ppzck_task, sql_get_multi_option % ('联合陈列_', task_new[i])) multi_option_df_new.drop_duplicates(subset=['qid', 'option_index'], inplace=True) multi_option_df_old = query_data_frame( mysql_db_ppzck_task, sql_get_multi_option % ('联合陈列_', task_old[i])) multi_option_df_old.drop_duplicates(subset=['qid', 'option_index'], inplace=True) elif i == 5: multi_option_df_new = query_data_frame( mysql_db_ppzck_task, sql_get_multi_option % ('样品展示_', task_new[i])) multi_option_df_new.drop_duplicates(subset=['qid', 'option_index'], inplace=True) multi_option_df_old = query_data_frame( mysql_db_ppzck_task, sql_get_multi_option % ('样品展示_', task_old[i])) multi_option_df_old.drop_duplicates(subset=['qid', 'option_index'], inplace=True) else: multi_option_df_new = DataFrame() multi_option_df_old = DataFrame() new_df, check_number_new_df = to_one_wave_result(rid_df_list_new[i], sku_df_new, answer_df_new, sku_verification_df_new, multi_option_df_new, year_new[i], i) old_df, check_number_old_df = to_one_wave_result(rid_df_list_old[i], sku_df_old, answer_df_old, sku_verification_df_old, multi_option_df_old, year_old[i], i) new_df = pd.merge(new_df, store_new_df, how='left', on='addressIDnum') old_df = pd.merge(old_df, store_old_df, how='left', on='addressIDnum') new_df = pd.merge(new_df, old_df, how='left', on='addressIDnum', suffixes=('', '_old')) new_df.drop_duplicates(subset='rid', inplace=True) new_df['check_total_shelf'] = new_df.apply( lambda x: check_vs_pp_total_shelf(x.total_shelf, x.total_shelf_old), axis=1) new_df['check_pg_shelf'] = new_df.apply( lambda x: check_vs_pp_pg_shelf(x.pg_shelf, x.pg_shelf_old), axis=1) new_df['check_pg_display'] = new_df.apply(lambda x: check_vs_pp_pg_display( x.total_display, x.pg_display, x.total_display_old, x.pg_display_old), axis=1) new_df['check_pg_sku'] = new_df.apply( lambda x: check_vs_pp_sku(i, x.actual_sku, x.actual_sku_old), axis=1) new_df['check_all'] = new_df.apply(lambda x: check_all( x.check_recent, x.shelf_display_verification_1, x. shelf_display_verification_2, x.sku_verification_count, x. check_total_shelf, x.check_pg_shelf, x.check_pg_display, x.check_pg_sku ), axis=1) report_new_df = new_df.reindex(columns=report_order[i]) report_old_df = old_df.reindex(columns=report_order[i]) checkpoint_new_df = new_df.reindex(columns=checkpoint_order[i]) checkpoint_old_df = old_df.reindex(columns=checkpoint_order[i]) report_new_df.to_excel(new_file[i], category[i], columns=report_order[i], index=False) report_old_df.to_excel(old_file[i], category[i], columns=report_order[i], index=False) writer_checkpoint = pd.ExcelWriter(checkpoint_file[i]) checkpoint_new_df.to_excel(writer_checkpoint, category[i] + '_new', index=False) checkpoint_old_df.to_excel(writer_checkpoint, category[i] + '_old', index=False) check_number_new_df.to_excel(writer_checkpoint, category[i] + '_number_new', index=False) check_number_old_df.to_excel(writer_checkpoint, category[i] + '_number_old', index=False) writer_checkpoint.close() subject = category[i] + datetime.now().strftime('%Y-%m-%d') contents = [ '附件中为前后两月数据及需检查的数据', ] attachments = [new_file[i], old_file[i], checkpoint_file[i]] with EmailSender(**email) as email_sender: email_sender.send_email(to=to, subject=subject, contents=contents, attachments=attachments) os.remove(new_file[i]) os.remove(old_file[i]) os.remove(checkpoint_file[i])
from EmailSender import EmailSender import pandas # Read Emails contact_emails = pandas.read_csv("./Recipients_list.csv") Emails = contact_emails["Email"].to_list() # text- This is a list, 1st element will be in normal font, 2nd element will be in bold, 3rd element will in normal font .... # For Line gaps and all used """ """ comment and define the element text = ["normal text", "Bold text"] # Send Emails mailer = EmailSender(sender_email=" ", sender_password="******", mail_subject=" ", mail_body=text) mailer.send_mails(driver_path="./chromedriver.exe", emails=Emails)
def monitoringServer(interval, ADDRESS, PASSWORD, TO_ADDR): emailSender = EmailSender(ADDRESS, PASSWORD, TO_ADDR) print('\nserver:launch server\n') #IPv4を指定 for res in socket.getaddrinfo(HOST, PORT, socket.AF_INET, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: sock0 = socket.socket(af, socktype, proto) except socket.error as msg: sock0 = None print('server:' + msg) continue try: sock0.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock0.bind(sa) sock0.listen(5) except socket.error as e: print(e) sock0.close() print('server:socket error') sock0 = None continue break if sock0 is None: print('could not open socket') import sys sys.exit(1) finalconftime = {} #addr -> time 辞書型配列 deathflag = {} #addr -> (0 or 1) 辞書型配列 readfds = [sock0] print('server:runninng') try: while True: rready, wready, xready = select.select(readfds, [], [], 1) for sock in rready: if sock is sock0: #接続要求があった場合 conn, (address, port) = sock.accept() # conn, address= sock.accept() print(address) print('server:connected from ' + address) #新たなクライアントと通信する場合 if address not in finalconftime: print('server:confirmed new client') elif deathflag[address] == 1: print('server:a dead client has revived') subject = 'monitoring info' body = address + ' has revived' if emailSender.send(subject, body): print('server:success to send email') else: print('server:due to an error, cannot send email') finalconftime[address] = time.time() deathflag[address] = 0 readfds.append(conn) else: #データの送信があった場合 try: msg = sock.recv(bufsize).decode() #EOF if len(msg) == 0 or len(msg) == -1: sock.close() readfds.remove(sock) #サーバー停止処理 elif msg == 'kill': print('server:received termination signal') return #クライアントの離脱処理 elif msg == 'close': finalconftime.pop(address) #(addr:time)辞書型配列 deathflag.pop(address) #データを受け取った場合 else: print('server:message received \"' + msg + '\"') sock.send(msg.encode()) except socket.timeout: pass except Exception as e: print("server:an error occurred") print("server:errror " + str(e)) #print("server:message "+e.message) for addr, fct in finalconftime.items(): #基準時間以降応答がない場合応答なしの場合メール送信 if fct + interval < time.time() and deathflag[addr] == 0: print('server:death confirmed') subject = 'monitoring info' body = addr + ' is dead' if emailSender.send(subject, body): print('server:success to send email') else: print('server:due to an error, cannot send email') deathflag[addr] = 1 except KeyboardInterrupt: print("server:KeyboardInterrupt") pass finally: for sock in readfds: sock.close() print('server:all socket closed')
def send_email_report(sender, receiver, subject, text, attachments, server, server_user, server_pw, ssl, unsecure): print("Composing your email...") print("Sender:", sender) print("Receiver:", receiver) print("Server:", server) if ssl is None: ssl = False elif ssl.lower() == "true": ssl = True else: ssl = False if unsecure is None: unsecure = False elif unsecure.lower() == "true": unsecure = True else: unsecure = False if server_user.lower() == "none": server_user = None if server_pw.lower() == "none": server_pw = None reporter = EmailSender() reporter.set_sender_address(sender_address=sender) reporter.set_receiver_addresses(receiver_addresses=receiver) reporter.set_subject(subject=subject) reporter.set_server(server=server, use_ssl=ssl, use_unsecure=unsecure) reporter.set_server_auth(usr=server_user, pw=server_pw) reporter.prepare_header() reporter.prepare_payload(text=text, attachments=attachments) reporter.send() print("email sent to: ", receiver)