def main(): pic_dir, nginx_dir = gen_pic_dir(pic_dir_prefix) get_word(get_word_loc, word_file) index = 1 report_content = "" mail_title = Template.html_h3_title("如下查询结果可能有乱码,请确认") mail_title = Template.html_h3_title("本次运行的截图目录为:%s" % nginx_dir) mail_res = "" for word in word_list: print("process %d word" % index) try: # ready screenshot tmp_list = word.split() query = tmp_list[0] vrid = tmp_list[1] _craw_url = url_prefix + quote(query) vrstr = 'div.vrResult[id*="sogou_vr_' + vrid + '"],div.vrResult[id*="sogou_vr_kmap_' + vrid + '"]' vrstr = quote(vrstr) picname = pic_dir + "/" + "_".join( [str(index), quote(query), vrid + ".png"]) nodejs_scrpit = 'spec-selector.js' path = '/search/odin/yinjingjing/python/garbled_detector/' child = subprocess.Popen(['/bin/node', nodejs_scrpit, \ '-t', 'android', '-m', 'css', \ '-k', vrstr, '-n', picname, \ '-u', quote(_craw_url)], shell=False, \ cwd = path, stdout=subprocess.PIPE) nodejs_res = child.stdout.read() if nodejs_res != b'0\n': utf8stdout("pupppeter ERROR. query:%s, vrid:%s, error:%s" % (query, vrid, nodejs_res)) continue else: garble, res = check_garbled(query, picname) utf8stdout( "query:%s, vrid:%s, gDetect-api result:%s, is_garble:%s" % (query, vrid, res, garble)) if garble: mail_info = "index:%d, query:%s, vrid:%s, gDetect-api result:%s" % ( index, query, vrid, res) mail_res += "<p>" + mail_info + "</p>\n" child.wait() index = index + 1 except Exception as err: print(err) index = index + 1 continue #当检测有乱码结果时才发邮件 #if mail_res: # utf8stdout("mail_res is not null, Send mail") report_content = mail_title + mail_res DataFile.write_full_file(report_tmp_path, report_content) Mail.sendMail("立知&图谱结果乱码检测", report_tmp_path, mail_to)
def _mail_logfile(self, logpath='', imgpath=''): self.logger.debug("_mail_logfile called") data = self._get_entrydata() result = self._validate_data(data) if result: dlg = SPWidgets.Dialog("The following entries are empty or have to little text:\n%s" % result,dialogwidth=500, \ buttons=["OK"], title='Error !') dlg.run() return self.screen.blit(self.surf, (25, 25)) # If we have network troubles, the smtp client timesout in 10 seconds. line = _("Your email will be send, please wait.....") s = utils.char2surf(line, fsize=24, fcol=DARKGREEN,bold=True) self.screen.blit(s, (50, 300)) pygame.display.update() try: Mail.mail(subject=data['short'], description=data['long'], \ component=data['component'], prio=data['prio'], \ assigned=data['assigned'], milestone=data['milestone'], \ name=data['name'], \ logpath=logpath, imgpath=imgpath) except Mail.SendmailError,err: self.activity_info_dialog(_("Failed to send the email. Error: %s") % err)
def process_file(self, inputfile, outputdir, filename): rename = str(filename).replace('.csv', '.txt') output_file = outputdir + "/" + rename failed = True csv_file = open(inputfile, 'r') csv_file1 = open(inputfile, 'r') input_file = csv.reader(csv_file, delimiter=',') input_file1 = csv.reader(csv_file1, delimiter=',') validator = Validator() header_problems = validator.header_validator(input_file1) value = len(header_problems) self.log.info("header validation completed with " + str(value) + " problems") if value != 0: write_problems(header_problems, open(output_file, 'w')) Mail().send_mail(rename, output_file) return failed else: data_problems = validator.data_validator(input_file) value = len(data_problems) self.log.info("data validation completed with " + str(value) + " problems") if value != 0: write_problems(data_problems, open(output_file, 'w')) Mail().send_mail(rename, output_file) return failed return False
def _mail_logfile(self, logpath='', imgpath=''): self.logger.debug("_mail_logfile called") data = self._get_entrydata() result = self._validate_data(data) if result: dlg = SPWidgets.Dialog("The following entries are empty or have to little text:\n%s" % result,dialogwidth=500, \ buttons=["OK"], title='Error !') dlg.run() return self.screen.blit(self.surf, (25, 25)) # If we have network troubles, the smtp client timesout in 10 seconds. line = _("Your email will be send, please wait.....") s = utils.char2surf(line, fsize=24, fcol=DARKGREEN, bold=True) self.screen.blit(s, (50, 300)) pygame.display.update() try: Mail.mail(subject=data['short'], description=data['long'], \ component=data['component'], prio=data['prio'], \ assigned=data['assigned'], milestone=data['milestone'], \ name=data['name'], \ logpath=logpath, imgpath=imgpath) except Mail.SendmailError, err: self.activity_info_dialog( _("Failed to send the email. Error: %s") % err)
def confirmFunction(self): self.closeInfoWindow() if self.info_type == "receiver": # send mail and take picture process current_time = time.strftime( "%d_%m_%Y_%H.%M.%S") # creating current time value receiver_ID = self.receiver_ID.split("@") self.cllback(receiver_ID[0], current_time) values_PNR = [ self.DB_RowValue[0][3], self.DB_RowValue[0][0], self.DB_RowValue[0][1], self.pnr_or_tracking, current_time ] # creating values for mail Mail.SendMail("Receiving_Cargo", values_PNR) elif self.info_type == "Locker": # send mail and take picture process current_time = time.strftime( "%d_%m_%Y_%H.%M.%S") # creating current time value receiver_ID = self.receiver_ID.split("@") self.cllback(receiver_ID[0], current_time) values_PNR = [ self.DB_RowValue[0][3], self.DB_RowValue[0][0], self.DB_RowValue[0][1], self.pnr_or_tracking, current_time ] # creating values for mail Mail.SendMail("Receiving_Locker", values_PNR) self.w = CabinNum_Window.CabinNum_Window(self.info_type, self.box_no) self.w.show()
def main(): arr_lst = ['name', 'allname', 'year'] get_word(get_word_loc, word_file) index = 1 report_content = "" mail_title = Template.html_h3_title("如下查询结果可能有乱码,请确认") mail_res = "" for word in word_list: utf8stdout("process %d word" % index) try: # ready get qa_text tmp_list = word.split() query = tmp_list[0] vrid = tmp_list[1] response = get_response(query, 'wap', '1') if not response: utf8stdout("source response is null. query:%s, vrid:%s" % (query, vrid)) index = index + 1 continue extract_text = get_att_name(query, response, arr_lst) utf8stdout("extract_text:%s" % extract_text) if not extract_text: utf8stdout("extract text is null. query:%s, vrid:%s" % (query, vrid)) index = index + 1 continue garble, res = check_garbled(query, extract_text) utf8stdout( "query:%s, vrid:%s, gDetect-api result:%s, is_garble:%s" % (query, vrid, res, garble)) if garble: f_res.write("index:%d, query:%s, vrid:%s\n" % (index, query, vrid)) f_res.write("gDetect-api result:%s\n" % res) f_res.write("extract_text:%s\n" % extract_text) f_res.write('\n') index = index + 1 except Exception as err: utf8stdout(err) index = index + 1 continue f_res.close() #当检测有乱码结果时才发邮件 if os.path.getsize(result_file) > 0: report_content = mail_title + mail_res DataFile.write_full_file(report_tmp_path, report_content) Mail.sendMail("图谱推荐结果乱码检测", report_tmp_path, mail_to, attachment=result_file)
def main(): get_word(get_word_loc, word_file) index = 1 report_content = "" mail_title = Template.html_h3_title("附件结果可能有乱码,请确认") for word in word_list: utf8stdout("process %d word" % index) try: # ready get qa_text tmp_list = word.split() query = tmp_list[0] vrid = tmp_list[1] node = Node(query, vrid) node.gen_url() node.get_response() if not node.html: utf8stdout("source html is null. query:%s, vrid:%s" % (query, vrid)) index = index + 1 continue node.get_qa_text() if not node.qa_text: utf8stdout("qa text is null. query:%s, vrid:%s" % (query, vrid)) index = index + 1 continue node.check_garbled() node_res = node.output_garble() if node_res: f_res.write("index:%d, query:%s, vrid:%s\n" % (index, query, vrid)) f_res.write("gDetect-api result:%s\n" % node.garble_res) f_res.write("qa_text:%s\n" % node.qa_text) f_res.write('\n') index = index + 1 except Exception as err: utf8stdout(err) index = index + 1 continue f_res.close() #当检测有乱码时才发送邮件 if os.path.getsize(result_file) > 0: report_content = mail_title DataFile.write_full_file(report_tmp_path, report_content) Mail.sendMail("立知问答结果乱码检测", report_tmp_path, mail_to, attachment=result_file)
def main(): get_word(get_word_loc, word_file) index = 1 report_content = "" mail_title = Template.html_h3_title("附件结果可能有乱码,请确认") for word in word_list: utf8stdout("process %d word" % index) try: # ready get qa_text tmp_list = word.split() query = tmp_list[0] vrid = tmp_list[1] html = get_response(query) if not html: utf8stdout("source html is null. query:%s, vrid:%s" % (query, vrid)) index = index + 1 continue qa_text = get_qa_text(query, html) if not qa_text: utf8stdout("qa text is null. query:%s, vrid:%s" % (query, vrid)) index = index + 1 continue garble, res = check_garbled(query, qa_text) utf8stdout("query:%s, vrid:%s, is_garble:%s" % (query, vrid, garble)) utf8stdout("gDetect-api result:%s" % res) utf8stdout("qa_text:%s" % qa_text) if garble: f_res.write("index:%d, query:%s, vrid:%s\n" % (index, query, vrid)) f_res.write("gDetect-api result:%s\n" % res) f_res.write("qa_text:%s\n" % qa_text) f_res.write('\n') index = index + 1 except Exception as err: utf8stdout(err) index = index + 1 continue #当检测有乱码结果时才发邮件 #if mail_res: # utf8stdout("mail_res is not null, Send mail") f_res.close() report_content = mail_title DataFile.write_full_file(report_tmp_path, report_content) Mail.sendMail("立知问答结果乱码检测", report_tmp_path, mail_to, attachment=result_file)
def mail_guide(id_guide): g.db = connect_db(app.config['USER_DB']) mail = "" cur = g.db.execute('select id_user from user_group where id_group = ?', [1]) users = [row[0] for row in cur.fetchall()] for user in users: cur = g.db.execute('select mail from user_description where id = ?', [user]) mail = [row[0] for row in cur.fetchall()][0] Mail.send(mail, "Nouveau guide", ("Un nouveau guide (ou une mise a jour d'un guide) est disponible.\n%s" % url_for('guide', id = id_guide)))
def add_order(): ensure_admin() data = json.loads(request.stream.read()) db = DataAccessOrders() or_handler = OrderHandler(db) order = Order(data["date"], data["time"], data["name"], data["telefon"], data["email"], data["location"], data["eventType"], data["note"]) mail = Mail() mail.send_mail(order) return jsonify(or_handler.add_new_order(order))
def Send(self): while True: scrPic = GetScrPic.ScrPic() picname = scrPic.Get('') info = self.hook.GetInfo() if info == '': info ="无输入" print info #info.encode('utf-8') Mail.send(self.ip,info,picname) #os.remove(picname)为了加快图片删除的速度将改代码放入了mail模块中 time.sleep(600)
def send_mail(task_id): try: report_content = "" url = "http://fs.sogou/lizhi_accu_compare/mission_list/" + str( task_id) + "/" mail_title = Template.html_h3_title("立知结果精度对比运行完毕,请对结果进行标注:") mail_content = Template.html_p(url) report_content = mail_title + mail_content DataFile.write_full_file(report_tmp_path, report_content) Mail.sendMail("立知结果精度对比运行完毕,请对结果进行标注", report_tmp_path, mail_to) except Exception as err: print("[send_mail]:%s" % err)
def main(): db = DBMS.DBMS() mail = Mail.Mail() while True: print("\n\n\n\n\n") multi = -1 while multi < 0 or multi > 5: multi = eval( input("0. Exit.\n" "1. Update from Database.\n" "2. Update from Form.\n" "3. Check Memberships.\n" "4. Display.\n" "5. Send Mails")) if multi == 1: db.update_from_db() elif multi == 2: db.update_from_form() elif multi == 3: db.membership() elif multi == 4: choice = -1 while choice != 2 and choice != 1: choice = eval(input("\n1. Individual.\n2. Group.")) db.membership(choice) elif multi == 5: mail.send_mail() else: return
def send_mail(self, event): if (self.textCtrl9.GetValue() == "" or self.textCtrl10.GetValue() == ""): wx.MessageBox('To and Subject can not be blank', 'Info', wx.OK | wx.ICON_EXCLAMATION) else: to = self.textCtrl9.GetValue() subject = self.textCtrl10.GetValue() body = self.styledTextCtrl1.GetText() attach = self.textCtrl13.GetValue() self.login_id = self.textCtrl11.GetValue() self.pswd = self.textCtrl12.GetValue() sender = self.textCtrl14.GetValue() if (self.textCtrl11.GetValue() == "" or self.textCtrl12.GetValue() == ""): wx.MessageBox('Login Id or Password can not be blank', 'Info', wx.OK | wx.ICON_EXCLAMATION) else: msg = Mail.SendMail(self.login_id, sender, self.pswd, to, subject, body, attach) if (msg == "Error Sending mail" or msg == "Error in Authentication"): wx.MessageBox(msg, 'Error', wx.OK | wx.ICON_ERROR) else: wx.MessageBox('Mail Sent!', 'Info', wx.OK | wx.ICON_INFORMATION)
def new_user_login(self): name = input("Your name:") last_name = input("Your last name:") while True: user_name = input("Your user name:") user1 = Datum().user_name(user_name) if user1: print("Such a username already exists..") else: break while True: password = input( "Your password must be at least 6 digits.\nYour password:"******"Your password is short") else: break while True: mail = input("Your mail:") user1 = Datum().user_mail(mail) if user1: print("Such a mail already exists..") else: break balance = input("Your balance:") new_user = User(name, last_name, user_name, password, mail, balance) Datum().user_login(new_user) time.sleep(2) Mail.Mail().user(new_user.user_name) time.sleep(2) print("Privilege welcome to shopping {} :)".format(new_user.name))
def sayfaKontrol(self): try: elem = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='mainTabView:gidisSeferTablosu:1:j_idt109:0:somVagonTipiGidis1_label']"))) if elem != "": for row in range(1, 15): try: if self.time == self.driver.find_element_by_xpath('/html/body/div[3]/div[2]/div/div/div/div/form/div[1]/div/div[1]/div/div/div/div[1]/div/div/div/table/tbody/tr[{0}]/td[1]/span'.format(row)).text: message=self.driver.find_element_by_xpath('//*[@id="mainTabView:gidisSeferTablosu:{0}:j_idt109:0:somVagonTipiGidis1_label"]'.format(row - 1)).text if message[22] != '0': Mail.Mail(self.email, message).sendMail() print(message) return "successful" else: print("Aradığınız seferde boş yer yok...") self.driver.quit() return except: print ("Saatinizde hata var...") self.driver.quit() sys.exit() else: print("Aradığınız seferde boş yer yoktur...") except (TimeoutException,NoSuchElementException) as ex: print ("TCDD sitesi yüklemede bir hata meydana geldi... Tekrar deneniyor...") self.driver.quit() except UnexpectedAlertPresentException as ex1: print("Güzergah bilgilerinde hata meydana geldi. Kontrol ederek tekrar deneyiniz. İstasyonları doğru girdiğinizden emin olunuz") self.driver.quit() exit()
def main(): # detects if settings.ini is present and creates one if not create_config = Config.Config() config_path = 'settings.ini' if not os.path.exists(config_path): create_config.create_config(config_path) config = ConfigParser.ConfigParser() config.read(config_path) # ---------------------Variables under this line----------------------------------- user_name = config.get('UserInfo', 'username') mail_sender = config.get('UserInfo', 'usermail') mail_recipient = config.get('MailRecipient', 'recipient') text = 'input something here later' filename = 'weeknumber.xlsx' mail_tester = Mail.Mail() workbook = ExcelDoc.ExcelDoc() # -------------------Main loop under this line---------------------------------------- workbook.fill_excel_doc(config_path, filename)
def __init__(self, user, url, sameUser=False): threading.Thread.__init__(self) self.user = user self.sso = Login_sso.Login_sso(url) self.mail = Mail.Mail(url) self.sameUser = sameUser self.message = 'OK'
def exceptQuit(lock_file, conf, build_log = ''): os.remove(lock_file) traceback.print_exc() mail = Mail.BuildMail() mail.sendBuildFailMail(conf.product_name_cn, build_log, conf.fail_dst_addr) print '' os.system('pause') exit()
def submit(self): if tk.messagebox.askyesno("Confirm Submit" , "Are you sure you want to submit? Once submitted , it cannot be undone."): load = Loading() body="Open Palm Service Mail" ml = mail.Mail("<Receiver Mail>", body , "<sender mail>[email protected]" , "<The password>") #Enter the password of the email address or else it will give error if ml.send_mail(): tk.messagebox.showinfo("Done" , "Mail Send") else: tk.messagebox.showinfo("Failed" , "Failed to send the mail. Check your internet connection or call your admin")
def buildTestInfo(self, directoryPath, givenClass): listOfWords = [] wordFreqDict = {} files = list(os.walk(directoryPath))[0][2] for file in files: filePath = directoryPath + "/" + file with open(filePath, encoding='utf-8', errors="ignore") as mailFile: listOfWords = helper.getWords(mailFile.read()) wordFreqDict = helper.getWordFreq(listOfWords) self.totTestSetInfo[file] = m.Mail(listOfWords, wordFreqDict, givenClass)
def confirmFunction(self, name, surname, phone, email): # run function when confirmbutton clicked self.checkIdenties(name, surname, phone, email) # Checking if ID is registered name = name.upper() surname = surname.upper() receiver_Person_ID = email.split("@") if self.security.isChecked() is True: security = 1 else: security = 0 safetybox = self.CB_SafetyBoxs.currentText() county = self.CB_Counties.currentText() city = self.CB_Cities.currentText() identities_ID = self.database.getIdentity_withPhone(phone) if self.box_no == "0": info_dialog = QtWidgets.QMessageBox(self) info_dialog.setIcon(QMessageBox.Warning) info_dialog.setWindowIcon( QIcon('/home/pi/Desktop/SafetyBox/icons/info.png')) info_dialog.setWindowTitle("Uyarı") info_dialog.setText( "Maalesef seçtiğiniz boyuttaki \ndolaplarımız doludur") button = QPushButton("Tamam", self) info_dialog.addButton(button, QMessageBox.RejectRole) info_dialog.show() else: PNR, Tracking, QRCode, datetime = self.Code_Generator.Generate_AllCodes( "R", surname, name, county, city) self.database.create_Cargo(Tracking, QRCode, PNR, security, self.box_no, identities_ID[0][0], datetime, 0) self.database.setBoxState_isEmpty("0", str(self.box_no)) self.getSafetyName() SB_Split = self.CB_SafetyBoxs.currentText().split(" - ") value = [ name, surname, "", email.lower(), Tracking, PNR, SB_Split[0], SB_Split[1], county, city ] Mail.SendMail("Creating_Cargo", value) Path("/home/pi/Desktop/receiver_Person/" + receiver_Person_ID[0]).mkdir( parents=True, exist_ok=True) # create folder if not exist
def __getMail(self): def extract_body(payload): if isinstance(payload,str): return payload else: return '\n'.join([extract_body(part.get_payload()) for part in payload]) #__conn=imaplib.IMAP4_SSL(config.host,993) #__conn.login(config.username,config.password) self.__conn.select() typ, data=self.__conn.search(None, 'UNSEEN') index = data[0].split() print index self.mailAmount=self.mailAmount+len(index) mails=[] i=0 try: for num in index: mails.append(Mail.myMail()) typ,msg_data=self.__conn.fetch(num, '(RFC822)') for response_part in msg_data: if isinstance(response_part,tuple): msg=email.message_from_string(response_part[1]) mails[i].trackNumber=num mails[i].fro=msg['from'] subject=msg['subject'] print i mails[i].header=email.Header.decode_header(subject)[0][0] payload=msg.get_payload() body=extract_body(payload) type=msg.get_content_charset() mails[i].content_charset=type print type if type==None: mails[i].content=body else: mails[i].content=body.decode("base64") i=i+1 return mails typ,response=__conn.store(num,'+FLAGS',r'(\Seen)') finally: try: print "Done" except: pass
def load(): name = f"{txtName.get()} {txtVName.get()}" data = MatchLoader.LoadData(name) if googlevar.get(): eventset = GoogleCal.get_events() userEvents = [ event["summary"] + event["start"]["dateTime"][:-6] for event in eventset ] else: userEvents = [] if emailvar.get(): message = "Hey " + name + "\n\nHier zijn je aanduidingen voor het moment:\n\n" + '\n'.join( [ str(match) for match in data ]) + "\n\nDir bericht werd automatisch gegenereerd met MatchScript" Mail.sendMail(txtEmail.get(), message) for i, match in enumerate(data): if googlevar.get(): if match.getmatch() + match.date.isoformat() not in userEvents: GoogleCal.create_event(match.date, match.getmatch()) if appleVar.get(): if match.getmatch() in [ event['title'] for event in AppleCal.get_events( txtAppleUsername.get(), txtApplePassword.get(), match.date.date - timedelta(days=1), match.date.date + timedelta(days=1)) ]: AppleCal.create_event(txtAppleUsername.get(), txtApplePassword.get(), match.date, match.getmatch()) tk.Label(window, text=str(match)).grid(row=5 + i, columnspan=20, sticky=tk.W)
def announce(self, game, subject, message): if game.tester or 'SOLITAIRE' in game.rules: return groups = [game.map.notify] if not host.observers: pass elif type(host.observers) is list: groups += [host.observers] else: groups += [[host.observers]] groups += [x.address for x in [game.gm] + game.powers if x.address] for addresses in groups: if not addresses: continue mail = Mail.Mail(', '.join(addresses), subject, ('', game.gameDir + '/mail')[host.copy], host.dpjudge, '') mail.write(message) mail.close()
def manage_server(listening_sock): # start listening listening_sock.listen(1) threads = [] count_users = 0 while Helper.get_users_num(ATTENDING_EVENT_FILE_NAME) < 5: # new conversation socket client_soc, client_address = listening_sock.accept() # from now on, the client and server are connected try: t = threading.Thread(target=manage_conversation, args=(client_soc, 1)) t.start() threads.append(t) count_users += 1 except ConnectionResetError as e: print(e) print( "Error: [WinError 10054] An existing connection was forcibly closed by the remote host" ) for x in threads: x.join() listening_sock.close( ) # isn't necessary because the server will be closed manually teams = teams_building.divide_teams( Helper.read_file_to_dict(ATTENDING_EVENT_FILE_NAME)) print(teams) Mail.manage_mail(teams[0], teams[1]) delete_file()
def GeraCertificados(self): for nome in self.arquivo['Nome']: #gera nome do certificado, gera o arquivo do certificado e o título do arquivo filename = os.path.join(self.diretorio, nome + ' - Certificado ' + self.titulo + '.pdf') c = canvas.Canvas(filename, pagesize = landscape(A4)) c.setTitle(nome + " - Certificado" + self.titulo) print('Gerando ' + filename) #poe o background no fundo do certificado cW, cH = c._pagesize c.drawInlineImage(self.imagem_fundo, 0, 0, width = cW, height = cH) texto = self.TextoOpcao(nome) y = 380 for i in texto: c.setFont('Helvetica', 20) c.drawCentredString(400, y, i) y -= 30 #fecha arquivo pdf e o salva c.showPage() c.save() if(self.email_var.get() == 1): email_c = self.arquivo[self.arquivo['Nome'] == nome]['email'] for i in email_c: email = i try: print("Enviando certificado via email para " + str(email)) Mail.send_email(email, filename, subject='Certificado ' + self.opcao + ' de ' + self.titulo, message="Segue anexo o certificado referente à(ao) " +self.opcao+ ' de ' + self.titulo + " ocorrida em " + self.datai) except: print("Email não enviado") else: print('Enviado com sucesso!') print('Certificados gerados com sucesso!')
def buildTrainingInfoWOStopWords(self, directoryPath, givenClass, stopPath): listOfWords = [] wordFreqDict = {} #print(stopPath) stopWords = helper.readStopWords(stopPath) files = list(os.walk(directoryPath))[0][2] for file in files: filePath = directoryPath + "/" + file with open(filePath, encoding='utf-8', errors="ignore") as mailFile: listOfWords = helper.getWordsSansStopWords( mailFile.read(), stopWords) wordFreqDict = helper.getWordFreq(listOfWords) self.totTrainingSetInfo[file] = m.Mail(listOfWords, wordFreqDict, givenClass)
def read_mail(self, path: str): subject: str = "" body: str = "" with open(path, encoding="utf8") as file: subject = file.readline().replace("Subject: ", "") file.readline() body = file.readline() subject_words = subject.replace("\n", "").split(" ") body_words = body.replace("\n", "").split(" ") subject_words = map( int, subject_words) if (subject_words[0] != "") else [0] body_words = map(int, body_words) if (body_words[0] != "") else [0] return Mail(path, subject_words, body_words)
def submit(self): """This method generates a prompt whenever the user clicks the submit button""" if tk.messagebox.askyesno( "Confirm Submit", "Are you sure you want to submit? Once submitted , it cannot be undone." ): # noqa E501 body = "Open Palm Service Mail" # Enter the password of the email address ml = mail.Mail("", body, "", "") if ml.send_mail(): tk.messagebox.showinfo("Done", "Mail Send") else: tk.messagebox.showinfo( "Failed", "Failed to send the mail. Check your internet connection or call your admin" ) # noqa E501
def list(self, email, subject=''): import Mail results = '' subject = ('DPjudge openings list (%s)' % host.dpjudgeID, 'RE: ' + subject)[subject != ''] for gameName in self.listGames('waiting') + self.listGames('forming'): if 'unlisted' not in self.dict[gameName]: try: game = self.load(gameName) if not game.private: results += game.shortList() except: pass mail = Mail.Mail(email, subject, mailAs=host.openingsAddress) mail.write((':: Judge: %s\n:: URL: %s%s\n\n' % (host.dpjudgeID, host.dpjudgeURL, '/index.cgi' * (os.name == 'nt'))) + (results or 'No Openings!')) mail.close()
def mainProc(config_file_name): print '正在读取配置……' conf = Config.Config(config_file_name) conf.parseConfig() print '正在复制文件……' util = Util.Util() version = conf.getVersion(conf.rc_conf.ver_major, conf.rc_conf.ver_minor, conf.rc_conf.ver_revision, conf.rc_conf.ver_build - 1) out_file = conf.outputFile(version) print '文件 ' + out_file + ' 从 ' + conf.output_dir + ' 到 ' + conf.publish_dir util.copyFile(conf.output_dir, conf.publish_dir, out_file) print '正在发送发布成功邮件……' mail = Mail.BuildMail() mail.sendBuildSuccessMail(conf.publish_download_url + out_file, conf.product_name_cn, '', conf.publish_dst_addr) print '\n\n发布流程成功。\n--------------------------------------------------' os.system('pause')
def sendMail(subject, toMail, msg, attachmentFiles, isHtml): try: # 配置邮件服务器信息 smtp = smtplib.SMTP_SSL(_smtpServer, _smtpPort) # 传入相应的账号密码 smtp.login(_fromMail, _password) mail = Mail.buildMailWithAttribute(subject, toMail) if isHtml is False: Mail.addTextMailBody(mail, msg) else: Mail.addHtmlMailBody(mail, msg) if len(attachmentFiles) != 0: Mail.addMailAttachment(mail, attachmentFiles) # 发送邮件 smtp.sendmail(_fromMail, toMail, mail.as_string()) except smtplib.SMTPException as e: print(e.message) finally: smtp.quit()
def sayfa_kontrol(driver): try: elem = WebDriverWait(driver, 10).until( EC.visibility_of_element_located(( By.XPATH, "//*[@id='mainTabView:gidisSeferTablosu:1:j_idt108:0:somVagonTipiGidis1_label']" ))) if elem != "": sayi = driver.find_element_by_css_selector( '#mainTabView\:gidisSeferTablosu\:1\:j_idt108\:0\:somVagonTipiGidis1_label' ) if sayi.text[22] != '0': mail = Mail.Mail("*****@*****.**", "Yer boşaldı " + sayi.text) mail.sendMail() print(sayi.text) exit() else: print("Yer Yok") driver.quit() except TimeoutException as ex: driver_get(driver)
def checkMail(self,addr): res=Mail.checkGmail() return res
# Sqlite self.con = sqlite3.connect(filename) try: self.create_table() except Exception, e: if re.match(r'table .* already exists', e.message): print "table already exists" else: raise e else: print "create table WeatherBoulder successfully" # requests self.s = requests.Session() self.fileds = ['RunID', 'Temperature', 'TemperatureH', 'TemperatureL', 'Description', 'Wind', 'Humidity', 'Time'] self.mail = Mail.weatherMail() def create_table(self): cu = self.con.cursor() cu.execute('''CREATE TABLE [WeatherBoulder] ( [RunID] integer NOT NULL ON CONFLICT REPLACE PRIMARY KEY, [Temperature] integer, [TemperatureH] integer, [TemperatureL] integer, [Description] varchar(40), [Wind] integer, [Humidity] integer, [Time] varchar(40)); ''') cu.execute('CREATE INDEX [RunID] ON [WeatherBoulder] ([RunID] ASC);') cu.close()
soup = BeautifulSoup(con, "html.parser") #con = soup.prettify().replace(u'\xf1', u' ').replace(u'\xa0', u' ') for wplist in soup.find_all('a'): if wplist.has_attr('target') and wplist.has_attr('alt'): #print(wplist.get('title')) href = wplist.get('href') # parsing the page and get the article page address with request.urlopen(hostlink + href) as pagefile: pagemain = pagefile.read(); pagesoup = BeautifulSoup(pagemain, "html.parser") #print(pagesoup.find('title')) # print(pagesoup.prettify().replace(u'\xf1', u' ').replace(u'\xa0', u' ')) mailtext += '<b>' + pagesoup.find('title').get_text() + '</b>' for meta in pagesoup.find_all('meta'): #get content if not meta.has_attr('http-equiv'): mailtext += '<p>' + meta.get('content').replace('演讲人:','<p>演讲人:').replace('.', '.<p>').replace('报告人', '<p>报告人').replace('时间', '<p>时间').replace('地点', '</p><p>地点').replace('简介:', '<p>简介:</p>').replace('主持人:', '<p>主持人:') + '</p>' #print(meta.get('content').replace(u'\xa0', u' '))#.replace(u'\xf1', u' '). cont = "" try: cont = open('total_old.html', 'r').read() except: pass with open('total_old.html', 'w',) as oldfile: if cont != mailtext: #print(cont) maillist = ['*****@*****.**','*****@*****.**','*****@*****.**', '*****@*****.**'] for tar in maillist: mail = Mail(target = tar) #收件邮箱 mail.sendMail(mailtext) oldfile.write(mailtext)
def checkMail(self): """Fonction pour checker toutes les addresses mails de l'utilisateur""" res = Mail.checkGmail() return res