def do_job(self): try: job_id = self.a_job.get_id() service_name = self.a_job.get_service_name() healthy_code = self.a_job.do_all_check() # Refresh job status Logger.report('job_id[%s] [%s] is healthy_code[%s]' % (job_id, service_name, healthy_code)) self.status_holder.set_one_status(job_id, healthy_code, self.a_job.get_check_cmd_healthy_code()) # Success if healthy_code is StatusCode.GREEN_CODE: return # Monitor operation occur error if healthy_code == StatusCode.WHITE_CODE or healthy_code == StatusCode.YELLOW_CODE: content = 'job_id[%s] [%s], healthy_code[%s] cat not be monitored successfully' % (job_id, service_name, healthy_code) Logger.error(content) SendMail.send(self.a_job.get_mail_receiver(), service_name, content) return # Do not need to be recovered if not self.a_job.get_auto_recover(): return # Stopped process stopped = self.a_job.stop() if stopped is None: content = 'job_id[%s] [%s] stop failed' % (job_id, self.a_job.get_service_name()) Logger.info(content) return # Check relies relies = self.a_job.get_all_rely() if not self.status_holder.is_group_healthy(relies): content = 'services job_id[%s] [%s] relying is not healthy' % (job_id, self.a_job.get_service_name()) Logger.info(content) return # Start process ok = self.a_job.start() if not ok: content = 'job_id[%s] [%s] start failed' % (job_id, self.a_job.get_service_name()) Logger.info(content) return # Start ok content = 'job_id[%s] [%s] start success' % (job_id, self.a_job.get_service_name()) Logger.info(content) SendMail.send(self.a_job.get_mail_receiver(), self.a_job.get_service_name(), content) except Exception, e: Logger.error(e.message)
def index(request): if request.method == 'POST': error = 0 try: form_detail = json.loads(request.body) team = RegistrationInfo() team.event_name = form_detail[u'event'] team.contact = json.dumps(form_detail[u'main_contact']) team.team_name = form_detail[u'team_name'] team.team_details = form_detail[u'team_details'] team.save() mail = SendMail(form_detail) mail.mail_coordinator() mail.mail_representative() except: error = 1 return HttpResponse(json.dumps({'error': error}), content_type='application/json') return render(request, 'home.html')
def Send(self, reminder_config): '''Filter the data and send the reminder. ''' query = reminder_config.get_query() self.logger.info('QUERY=%s' % query) total_records = self.db_cursor.execute(query) self.logger.info('Records in cursor set: %d' % total_records) send_mail = SendMail(self.mandrill_config) total_sent = 0 total_error = 0 fields = self.db_cursor.description for row in self.db_cursor: content = [{"name": x[0], "content": row[x[0]]} for x in fields] email = row['email'] name = row['name'] row_content = {x[0]: row[x[0]] for x in fields} attachments = self.__build_attachments_parameter(reminder_config.attachment_url, row_content) sent, reject_reason = send_mail.send_using_template(email, name, reminder_config.reminder_template_name, content, attachments) if sent == False: self.logger.error('Email {}. Reason: {}'.format(email, reject_reason)) total_error += 1 continue self.__update_record(reminder_config.update, row_content) total_sent += 1 self.logger.info('OK: Email {}'.format(email)) self.logger.info('Sent with success: {} Fail: {}'.format(total_sent, total_error)) return total_sent, total_error, query
def sendBookInfo(self): '''将预约成功信息发送到邮箱''' seat_name = self.book_result['data']['list']['spaceInfo']['name'] book_time = self.book_result['data']['list']['beginTime']['date'] deadline = time.mktime(time.strptime(book_time, '%Y-%m-%d %H:%M:%S')) + 1800 deadline = time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime(deadline)) # 格式化成 2020-09-16 19:45:33 形式 mail = SendMail() mail.smtp_server = self.stu.smtp_server mail.username = self.stu.from_email mail.password = self.stu.from_pw mail.to_email = self.stu.to_email mail.subject = f'已成功预约 {seat_name} 号座位' mail.message = (f'已成功为您预约了位于三楼平层北区的 {seat_name} 号座位~\n\n' f'预约开始时间: {book_time}\n' f'请务必于 {deadline} 之前抵达图书馆并签到\n\n' '“While there\'s life, there\'s hope.”\n' ' ― Marcus Tullius Cicero\n') mail.send()
def send(self, send_resume_to, template_name): send_mail = SendMail(self.mandrill_config) self.finish_time = datetime.now() content = [ {'name': 'start-time', 'content': self.start_time.strftime("%Y-%m-%d %H:%M:%S")}, {'name': 'records-processed', 'content': self.sent_with_success + self.sent_with_error}, {'name': 'success', 'content': self.sent_with_success}, {'name': 'error', 'content': self.sent_with_error}, {'name': 'finish-time', 'content': self.finish_time.strftime("%Y-%m-%d %H:%M:%S")}, {'name': 'command-line-parameters', 'content': self.command_line_parameters}, {'name': 'query-filter-used', 'content': self.query} ] sent, reject_reason = send_mail.send_using_template( send_resume_to, 'Reminder', template_name, content ) return sent, reject_reason
def NetDown(SwitchIP, compRoom): num = 0 flag = 0 for i in range(5): NetStatus = CheckNet(SwitchIP) if not NetStatus: num = num + 1 time.sleep(2) if num == 5: mylogger.info("###########5 connect fail,going to down #############") do(compRoom, flag) return True else: mylogger.info( "###########5 connect success,going to mail #############") SendMail(compRoom)
def run(day_format): #day format like 2017-10-23 year, month, day= day_format.split("-") domains = get_domain() for domain in domains: base_dir = "/usr/local/nginx/html/hdfs/download/" hdfs_path = domain + "/" + year + "/" + month + "/" + day local_path = base_dir + hdfs_path if is_path_exist(local_path): all_files = get_recursive_file_list(local_path) for file_path in all_files: local_size = get_file_size(file_path) hour = file_path.split("/")[-1] domain_path = "/"+domain day_path = "./" + day_format ftp_path = "/"+domain + "/" + day_format + "/" + day_format+"_"+hour ftp_size, cmds = push_file_ftp(file_path, domain_path, day_path, ftp_path) if ftp_size=="0": toollogger.error(traceback.format_exc()) SendMail().send_mail(day_format, cmds) else: toollogger.info( ftp_path + "\t" + str(local_size) + "\t" + ftp_size + "\t" +str(int(local_size) - int(ftp_size)))
debug_logger = getLogger("debug") result_logger = getLogger("result") debug_fh = FileHandler(debug_logfilename, "a+") result_fh = FileHandler(result_logfilename, "a+") debug_logger.addHandler(debug_fh) result_logger.addHandler(result_fh) debug_logger.setLevel(DEBUG) result_logger.setLevel(DEBUG) if __name__ == '__main__': args = sys.argv sendmail = SendMail("*****@*****.**", "*****@*****.**", property_path) # コマンドライン引数から、通貨とモード取得 instrument = args[1] mode = args[2] algo = args[3] config_name = args[4] base_time = datetime.now() if len(args) > 5: test_args = args[5] else: test_args = "live" if test_args == "test": end_time = datetime.strptime("2019-05-25 00:00:00", "%Y-%m-%d %H:%M:%S")
from netcup_crawler import NetcupCrawler from send_mail import SendMail crawler = NetcupCrawler() mail = SendMail() entries = crawler.fetch() if crawler.check(entries): crawler.save(entries) subject = "Netcup - Neues Sonderangebot" body = "" for entry in entries: body += "<br>Angebot: " + entry.title + "<br> Preis: " + entry.price + "<br>" recepients = {"*****@*****.**", "*****@*****.**"} mail.send_mail(subject, body, recepients) print("Email gesendet.") else: print("Keine Email gesendet.")
def gen_invalid_warn(): warncontent = "\r\n".join(invalidtask.values()) sendm = SendMail() sendm.settitle("邮件关闭提醒") sendm.settocopy(["*****@*****.**"]) body = warncontent + "\r\n当前的配置状态请查看附件;若不想关闭,请到%s修改%s\r\n,确保截止日期大于当前日期且设置开关状态为on\r\n" % ( sendm.hostname, task_status, ) print body return 0 sendm.setbody(body) sendm.setattach(task_status) # 发送当前的配置状态 sendm.send()
def insert_table_beneficiarioans(self, DF, path): competencia = None status = None try: status = 2 #File processing completed competencia = self.check_competencia(path)[1] DF['COMPETENCIA'] = competencia DF['BENEFICIARIO_ID'] = DF.index DF['CONFERENCIA_ID'] = DF.index DF['CD_MUNICIPIO'].fillna(0, inplace=True) DF['NUMERO'].fillna(0, inplace=True) DF['LOGRADOURO'].fillna('nan', inplace=True) DF['BAIRRO'].fillna('nan', inplace=True) DF['COMPLEMENTO'].fillna('nan', inplace=True) DF['CD_MUNICIPIO_RESIDENCIA'].fillna(0, inplace=True) DF['CCO_BENEFICIARIO_TITULAR'].fillna(0, inplace=True) DF['CNPJ_EMPRESA_CONTRATANTE'].fillna(0, inplace=True) DF['CPF'].fillna(0, inplace=True) DF['CNS'].fillna(0, inplace=True) DF['CEP'].fillna(0, inplace=True) DF['RESIDE_EXTERIOR'].fillna(0, inplace=True) DF['NR_PLANO_ANS'].fillna(0, inplace=True) DF['REL_DEPEND'].fillna(0, inplace=True) DF['MTV_CANCELAMENTO'].fillna(0, inplace=True) DF['DT_ATUALIZACAO'] = '20' + DF['DT_ATUALIZACAO'].str[ 6:9] + '-' + DF['DT_ATUALIZACAO'].str[3:5] + '-' + DF[ 'DT_ATUALIZACAO'].str[0:2] DF['DT_NASCIMENTO'] = '20' + DF['DT_NASCIMENTO'].str[ 6:9] + '-' + DF['DT_NASCIMENTO'].str[3:5] + '-' + DF[ 'DT_NASCIMENTO'].str[0:2] DF['DT_CANCELAMENTO'] = '20' + DF['DT_CANCELAMENTO'].str[ 6:9] + '-' + DF['DT_CANCELAMENTO'].str[3:5] + '-' + DF[ 'DT_CANCELAMENTO'].str[0:2] DF['DT_CONTRATACAO'] = '20' + DF['DT_CONTRATACAO'].str[ 6:9] + '-' + DF['DT_CONTRATACAO'].str[3:5] + '-' + DF[ 'DT_CONTRATACAO'].str[0:2] for i in range(len(DF)): BAIRRO = str(DF.BAIRRO[i].replace("'", '')) LOGRADOURO = str(DF.LOGRADOURO[i].replace("'", '')) COMPLEMENTO = str(DF.COMPLEMENTO[i].replace("'", '')) SQL = ( f'''EXEC SP_INSERT_BENEFICIARIOANS @p_BENEFICIARIO_ID= '{DF.BENEFICIARIO_ID[i]}', @p_CCO= '{DF.CCO[i]}', @p_SITUACAO= '{DF.SITUACAO[i]}' , @p_dataAtualizacao= '{DF.DT_ATUALIZACAO[i]}', @p_CONFERENCIA_ID= '{DF.CONFERENCIA_ID[i]}', @p_LOGRADOURO= '{LOGRADOURO}', @p_NUMERO= '{DF.NUMERO[i]}', @p_COMPLEMENTO= '{COMPLEMENTO}', @p_BAIRRO= '{BAIRRO}', @p_codigoMunicipio= {DF.CD_MUNICIPIO[i]}, @p_codigoMunicipioResidencia= {DF.CD_MUNICIPIO_RESIDENCIA[i]}, @p_CEP= {DF.CEP[i]}, @p_resideExterior= {DF.RESIDE_EXTERIOR[i]}, @p_tipoEndereco= '{DF.TP_ENDERECO[i]}', @p_CPF= {DF.CPF[i]}, @p_CNS= {DF.CNS[i]}, @p_NOME= '{DF.NOME[i]}', @p_SEXO= '{DF.SEXO[i]}', @p_dataNascimento= '{DF.DT_NASCIMENTO[i]}', @p_nomeMae= '{DF.NOME_MAE[i]}', @p_ccoBeneficiarioTitular= {DF.CCO_BENEFICIARIO_TITULAR[i]}, @p_cnpjEmpresaContratante= {DF.CNPJ_EMPRESA_CONTRATANTE[i]}, @p_codigoBeneficiario= '{DF.CD_BENEFICIARIO[i]}', @p_dataCancelamento= '{DF.DT_CANCELAMENTO[i]}', @p_datacontratacao= '{DF.DT_CONTRATACAO[i]}', @p_itensExcluidosCobertura= '{DF.ITENS_EXCLUIDOS_COBERTURA[i]}', @p_motivoCancelamento= {DF.MTV_CANCELAMENTO[i]}, @p_numeroPlanoANS= {DF.NR_PLANO_ANS[i]}, @p_relacaoDependencia= {DF.REL_DEPEND[i]}, @p_COMPETENCIA= '{DF.COMPETENCIA[i]}' ''' ) db.execute(SQL) SendMail().sendMail(DF) #Send mail except Exception as e: competencia = self.check_competencia(path)[1] status = 3 #error processing the file ANS log.insert_log_error(str(e), 'insert_table_beneficiarioans') SendMail().sendMail(e) #Send mail db.rollback() finally: self.update_status_processing(status, competencia) db.commit() db.__disconnect__()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from receive_mail import FetchEmail from extract_content import extract_content from send_mail import SendMail # receivemail # 下载对应邮箱的附件图片,下载到对应的文件夹 received mail_server = '' username = '' password = '' # 此处填写授权码 fetch_email = FetchEmail(mail_server, username, password) emails = fetch_email.fetch_unread_messages() # 调用相应的代码进行处理,识别内容,生成xlsx save_dir_path = "to_send" extract_content(save_dir_path) # sendmail from_mail = '' tolist = [''] username = '' password = '' # 此处填写授权码 send = SendMail(from_mail, tolist, username, password) send.send_mail('./to_send')
def start(): # Command line arguments ap = argparse.ArgumentParser() ap.add_argument('-t', '--tune', type=bool, default=False, help="pass -t True for hyperparameter tuning") args = vars(ap.parse_args()) batch_size = 20 n_epochs = 1 # loads data and returns train, valid and test data train_load, valid_load, test_load, classes = load_data(batch_size) if not args['tune']: learning_rate = 0.001 optimizer = 'Adam' model = define_model() cr, op = loss_and_optim(model, learning_rate, optimizer) print("Training the network without hyperparameter tuning") train(n_epochs, model, train_load, valid_load, cr, op) accuracy = test(batch_size, model, test_load, classes, cr, op) accuracy = int(accuracy) with open('accuracy.txt', 'w') as f: f.write(str(accuracy)) else: n_epochs = 2 learning_rates = [0.01, 0.001] optimizers = ['Adam', 'SGD'] acc = [] max_acc = 0 best_lr = 0 best_opt = '' for learning_rate in learning_rates: for optimizer in optimizers: print( "\n ** Training with {} optimizer and {} learning rate **\n" .format(optimizer, learning_rate)) model = define_model() cr, op = loss_and_optim(model, learning_rate, optimizer) model = train(n_epochs, model, train_load, valid_load, cr, op) accuracy = test(batch_size, model, test_load, classes, cr, op) if accuracy > max_acc: max_acc = accuracy best_opt = optimizer best_lr = learning_rate # Save the best performing model torch.save(model.state_dict(), 'model_cifar.pt') print("Saving best model...") print( "\nBest Learning Rate : {}\nBest Optimizer : {}\nBest Accuracy: {}" .format(best_lr, best_opt, str(max_acc))) # Send email user about the model performance and best hyperparameter so far print("Sending email to the user...") s = SendMail(str(max_acc) + '%', best_lr, best_opt) s.send_mail() max_acc = int(max_acc) with open('accuracy.txt', 'w') as f: f.write(str(max_acc))
def main_process(): # 1. 调用receive_mail.py # 下载对应邮箱的附件图片,下载到对应的文件夹 received receiver_mail_server = config['receiver']['mail_server'] receiver_username = config['receiver']['username'] receiver_password = config['receiver']['password'] logger.info("Receive from mail_server is :{}, username is :{}!", receiver_mail_server, receiver_username, feature="f-strings") flag = True while flag: try: fetch_email = FetchEmail(receiver_mail_server, receiver_username, receiver_password) emails = fetch_email.fetch_unread_messages() logger.info("Receiving from mail_server...please wait...") if emails: flag = False logger.info("Receive mail attachment success!") time.sleep(1) except Exception as e: logger.debug("Receive mail attachment error, error is {}!", e, feature="f-strings") # 2. 调用extract_content.py # 对下载的图片进行识别,识别后内容生成xls try: save_dir_path = "to_send" extract_content(save_dir_path) logger.info("Extract mail attachment success!") except Exception as e: logger.debug("Extract mail attachment error, error is {}!", e, feature="f-strings") # 3. 调用sendmail.py # 将生成的xls发送到对应的邮箱列表 sender_mail_server = config['sender']['sender_mail_server'] to_username = config['sender']['to_username'] sender_username = config['sender']['sender_username'] sender_password = config['sender']['sender_password'] # 此处填写授权码 logger.info( "Send mail from sender_mail_server is :{}, sender_username is :{}, to_username is :{}!", sender_mail_server, sender_username, to_username, feature="f-strings") try: send = SendMail(sender_mail_server, to_username, sender_username, sender_password) send.send_mail('./to_send') logger.info("Send extract xls success!") except Exception as e: logger.debug("Send extract xls error, error is {}!", e, feature="f-strings")
import getpass import time import numpy as np from matplotlib import pyplot as plt from send_mail import SendMail from model import MobiFallNet from DataGenerator import MobiFallGenerator import os sender = input("Type email address from which you want to send alerts: ") password = getpass.getpass('Password:'******'STD': 0, 'WAL': 1, 'JOG': 2, 'JUM': 3, 'STU': 4, 'STN': 5, 'SCH': 6, 'CSI': 7, 'CSO': 8, 'FOL': 9, 'FKL': 10, 'BSC': 11, 'SDL': 12 }