def read_inbox(): mail.select('Inbox') # Returned data is a tuple # - we're only interested in data, so a placeholder is placed _, data = mail.search(None, '(UNSEEN)') # search for unread emails inbox_item_list = data[0].split() # list of references to emails if not inbox_item_list: print('No unread emails') # not logging due to memory else: for item in inbox_item_list: # Returned data are tuples of message part envelope and data # The latter type of payload is indicated as multipart/* or message/rfc822 _, email_data = mail.fetch( item, '(RFC822)') # returns email in byte form # extracting the body, which is raw text of the whole # email including headers and alternate payloads string_email = email_data[0][1].decode("utf-8") email_message = email.message_from_string( string_email) # converting to object if get_invoices(email_message): db.log('Found email - Invoice Collected') else: sender_email = email_message['From'] SendMail.send_email(sender_email) # sends default mail db.log('Found email with no valid attachment', 1) mail.uid('STORE', item, '+FLAGS', '\\SEEN') # marking email as read
def watchForFileAndSendMail(emailAddress, url, uri): """ Watch for the dump file to appear and send an email to the user after it has appeared. """ for i in range(0, 100): filePath = util.getPath(STATIC_GENERATED_FILE_LOCATION + uri) if os.path.exists(filePath) and os.stat(filePath).st_size != 0: message = "This is an automatically generated message.\n"\ + "The requested data has been generated.\n"\ + "Please retrieve your data from the following URL: \n"\ + url \ + "\nYou must retrieve this file within 24 hours." util.debugPrint(message) SendMail.sendMail(message, emailAddress, "Your Data Download Request") return else: util.debugPrint("Polling for file " + filePath) time.sleep(10) message = "This is an automatically generated message.\n"\ + "Tragically, the requested data could not be generated.\n"\ + "Sorry to have dashed your hopes into the ground.\n" SendMail.sendMail(message, emailAddress, "Your Data Download Request")
def queryjianshu(self, num): url = self.server # 添加headers headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0' } html = requests.get(url, headers=headers).text soup = BeautifulSoup(html, 'lxml') # 根据条件筛选元素 divs = soup.find_all('span', class_="time") completed = False for tex in divs: # 寻找写作的时间,如果有今天时间就日更完成,不然提醒 writertime = tex.get('data-shared-at')[0:10] ntime = time.strftime("%Y-%m-%d", time.localtime()) if writertime == ntime: completed = True # completed判断是否写作完成了 if completed: self.janshucom = True s = '很好完成日更了' SendMail().accesssendmail(s) else: s = '无日更!!!!第' + str(num) + '次提醒' print(s) SendMail().accesssendmail(s)
def csrrequest(request,*args, **kwargs): if request.method == 'POST': if request.user.is_authenticated(): username = request.user.email email = username fname = request.user.first_name print "I am in if loop" received_json_data=json.loads(request.body) data = request.body #Raw Data: "{"cname":"example.com","org":"test","department":"test","city":"test","stateProvince":"test","country":"IN","keySize":"2048","emailId":"*****@*****.**"}" data = json.loads(data) timestr = time.strftime("%Y%m%d-%H%M%S") csrfile = os.path.join('/app/csr-key', data['cname'] +'-'+ timestr + '.csr') keyfile = os.path.join('/app/csr-key', data['cname'] +'-'+ timestr + '.key') print 'Raw Data: "%s"' % request.body x = generateCSR(data,csrfile,keyfile) if x: Subject = "CSR Request : %s" % (data['cname']) # Message = "<b>Hi Dear,</b><br></br><p>Your request for CSR generation for domain: %s was sucessful. Find the CSR in attached document.</p>" % (data['cname']) Message = "<b>Dear %s,</b><br></br><p>Your request for CSR generation for domain: %s was sucessful. Find the CSR in attached document.<br></br>Below information were provided to create CSR</p><br></br><b>Common Name:</b> %s<br></br><b>Organization:</b> %s<br></br><b>Oraganization Unit:</b> %s<br></br><b>Locality:</b> %s<br></br><b>State:</b> %s<br></br><b>Country:</b> %s<br></br><b>Key Size:</b> %s<br></br><b>Email:</b> %s<br></br> " % (fname, data['cname'], data['cname'], data['org'], data['department'], data['city'], data['stateProvince'], data['country'], data['keySize'], data['emailId']) #send email print "Sending email for CSR request" SendMail.notification(Subject, email, Message, csrfile) newdoc = CsrRequest(requester_emailid=request.user.email,domain_name=data['cname'], organization=data['org'], department=data['department'], city=data['city'], state=data['stateProvince'], country=data['country'], keysize=data['keySize'], admin_emailid=data['emailId'], csr_file_name=csrfile, key_file_name=keyfile) newdoc.save() return render(request, 'success.html', context = {'Success Check your email': "Sucess"}) else : return render(request, 'success.html', context = {'Failure! Kindly check with Dev Ops team': 'Failure'}) else : print "I am in else loop" return render(request, 'csrreq.html', context = {"hi": "I want to print" })
def generateUserDenyAccountEmail(emailAddress, serverUrlPrefix): """ Generate and send email. This is a thread since the SMTP timeout is 30 seconds """ message = "This is an automatically generated message from the Spectrum Monitoring System.\n"\ + "We regret to inform you that your request for a new account from the CAC Measured Spectrum Occupancy Database was denied.\n"\ + "Please contact the system administrator for more information.\n" util.debugPrint(message) SendMail.sendMail(message, emailAddress, "Account information")
def setup_mail(settings): email_slot = settings["general"].get("email_server", "gmail").lower() if email_slot != "fromfile": SendMail.delegate_send(email_slot) else: if os.path.exists("email_function.txt"): with open('email_function.txt') as f: c = f.read().strip().lower() SendMail.delegate_send(c)
def get(self): key_name = self.request.get("key") try: key = db.Key(key_name) member = db.get(key) msgBody = 'Hello ' + member.firstName + ' (aka. member number <b>' + str(member.memberNo) + '</b>), \n\n' \ '<p>Welcome to the world of UBC Badminton! ' \ '<p>Here is some useful information regarding upcoming events:</p>' \ '<p><u>Gym Nights:</u></p>' \ '<p>For term 1, gym nights will be Tuesdays from 4-6pm and Fridays from 6:30-11pm. ' \ 'The last gym night of Term 1 will be Friday, Dec. 4. '\ 'Gym nights are held at the Osbourne Center - Gym A (next to Thunderbird Arena).</p>' \ '<p><u>New Members Orientation</u></p>' \ '<p>Happening Tuesday, Sept. 29th from 4-6pm at Osbourne, all new members are invited to attend the New Members Orientation where we\'ll be introducing the club to all you newbies. '\ 'This event is for <i>new</i> members only.</p>' \ '<p><u>IceBreaker!</u></p>' \ '<p><i>Question:</i> how heavy is a polar bear? <i>Answer:</i> enough to break the ice! Hehe. '\ 'Be sure to sign up for our IceBreaker event which is happening Friday, Oct. 2 at 4:30pm (2 hours before the first Friday gym night). '\ 'If you want to sign up, let us know by emailing us!</p>'\ '<p>For more information about any of these events or about the club itself, check us out on our webpage. ' email = SendMail(users.get_current_user().email(), member.email, 'Registration Confirmation ' + member.emailHash, msgBody) email.send() pageContent = '<p>' + member.firstName + ' (aka member number <b>' + str(member.memberNo) + '</b>),</p>' \ '<p>Woot! Congratulations on becoming a member of the UBC Badminton Club! Your confirmation code is <i>' + member.emailHash + '</i>.</p>' \ '<p><b>Important Dates:</b></p>' \ '<ul><li><i>Tuesday, Sept. 29</i> - New Members Orientation. We\'ll introduce the world of UBC Badminton to all the newbies. As such, gym night will be open to <u>new</u> members only.</li>' \ ' <li><i>Friday, Oct. 2</i> - IceBreaker! and first gym night open to all members (new and returning)</li></ul>' \ '<p>Don\'t worry about copy all this information down. ' \ 'An email was just sent to your inbox containing the same information.</p>' urlList = [] urlList.append(Url('Back', '/register')) template_values = { 'content' : pageContent, 'urlList' : urlList } path = os.path.join(os.path.dirname(__file__), 'templates', 'basic.html') self.response.out.write(template.render(path, template_values)) except: logging.warn('Error retreiving member with key %s' % key_name) template_values = { 'content' : "404 - Uh Oh! We weren't able to retreive the member with that particular id. Please talk to your nearest executive for HeLp!" , } path = os.path.join(os.path.dirname(__file__), 'templates', 'basic.html') self.response.out.write(template.render(path, template_values))
def generateUserAccountPendingAuthorizationEmail(emailAddress, serverUrlPrefix): """ Generate and send email. This is a thread since the SMTP timeout is 30 seconds """ message = "This is an automatically generated message from the Spectrum Monitoring System.\n"\ + "You requested a new account for the CAC Measured Spectrum Occupancy Database.\n"\ + "Your request has been sent to the system administrator for authorization.\n" util.debugPrint(message) SendMail.sendMail(message, emailAddress, "Account pending authorization")
def generateChangePasswordEmail(emailAddress, serverUrlPrefix): """ Generate and send email. This is a thread since the SMTP timeout is 30 seconds """ message = "This is an automatically generated message from the Spectrum Monitoring System.\n"\ + "Your password has been changed to value you entered into " + str(serverUrlPrefix + "/spectrumbrowser") + "\n"\ + "If you did not originate the change password request, please contact the system administrator.\n" util.debugPrint(message) SendMail.sendMail(message, emailAddress, "change password link")
def fun_create_issue(): global count try: create_issue() count = 0 except Exception, e: count += 1 SendMail.send_email_by_smtp('create ALM BUG error', e.message, '*****@*****.**')
def main(): if db_connection: invoices = check_for_new_invoices() # returns array of invoices for invoice in invoices: completed, invoice_data = extract_data(invoice) if completed: add_invoice(invoice_data) else: # Probably due to wrong input data as connection is already established print('Extraction Failure') from_address = invoice.split()[-2].replace('<', '').replace('>', '') # Due to above theory SendMail.send_email(from_address)
def run(self): while self.running: now = datetime.now() for k in self.kittys: diff = now - k.lastHeard diff = diff.days * 86400 + diff.seconds print 'Seconds since ', k.name, ' heard: ', diff if diff > k.ttw: message = 'Alert: ' + k.name + ' NOT DETECTED for ' + str( diff) + ' SECONDS!' SendMail.sendMail(message) k.incrementTTW() time.sleep(30)
def generateResetPasswordEmail(emailAddress, serverUrlPrefix, token): """ Generate and send email. This is a thread since the SMTP timeout is 30 seconds """ urlToClick = serverUrlPrefix + "/spectrumbrowser/resetPassword/" + emailAddress + "/" + str( token) util.debugPrint("URL to Click for reset password email" + urlToClick) message = "This is an automatically generated message from the Spectrum Monitoring System.\n"\ + "You requested to reset your password to a password you entered into " + str(serverUrlPrefix + "/spectrumbrowser") + "\n"\ + "Please click here within 2 hours to reset your password\n"\ + "(or ignore this mail if you did not originate this request):\n"\ + urlToClick + "\n" util.debugPrint(message) SendMail.sendMail(message, emailAddress, "reset password link")
def sendattachmentinmail(): print "Sending Email....." body = """\ <html>Hi All,<br><br> Please find attached the Stock Equity Summary Report.<br><br> Regards,<br> Stock Analytics Team </html> """ SendMail.proceedWithAttachments(SUBJECT, RECEIVER_ID, body, DataFile + "/" + "StockEquitySummary.xlsx", fileType="xlsx") print "Email Sent....."
def generateUserActivateAccountEmail(emailAddress, serverUrlPrefix, token): """ Generate and send email. This is a thread since the SMTP timeout is 30 seconds """ hyperlink_format = '<a href="{link}">{text}</a>' urlToClick = serverUrlPrefix + "/spectrumbrowser/activateAccount/" + emailAddress + "/" + str( token) util.debugPrint("URL to Click for generateUserActivateAccountEmail" + urlToClick) message = "This is an automatically generated message from the Spectrum Monitoring System.\n"\ + "You requested a new account for the CAC Measured Spectrum Occupancy Database.\n"\ + "Please click " + hyperlink_format.format(link=urlToClick, text='here') + " within 2 hours to activate your account\n"\ + "(or ignore this mail if you did not originate this request)." util.debugPrint(message) SendMail.sendMail(message, emailAddress, "Account activation link", True)
def process(mac, rssi): found = False for k in config.kittys: if mac == k.mac: k.lastHeard = datetime.now() print 'Heard ', k.name, ' at ' + str(rssi) + 'dBm!' if k.ttw != 180: SendMail.sendMail(k.name + ' reacquired') k.ttw = 180 found = True break if not found: print 'Unkown mac: ', mac sys.stdout.flush()
class Parser: sendMail = SendMail.SendMail() msg = '' # msg = jsondata(sender, receiver, subject), HTML id, def setMsg(self, msg): self.msg = msg def parsing(self): params = self.msg.decode('utf-8') dictParams = json.loads(params) self.sendMail.setMailInfo(dictParams['htmlId'], dictParams['verifyingKey'], dictParams['sender'], dictParams['receiver'], dictParams['subject']) #edit html edit = editHTML.EditHTML() edit.setTemplateId(dictParams['htmlId']) edit.setVerifyKey(dictParams['verifyingKey']) edit.editHTML() self.sendMail.setMsg("hello") #send self.sendMail.sendMail()
def mail_res(): #Starts the mailing, displays an error if it fails to send = Toplevel(initial) setup(send) send.title("Sucessful Submission") send.attributes('-topmost', True) sts = StringVar() lab = Label(send, textvariable = sts) sts.set("Sucessfully Submitted!\n" +"Sending an Email of your responses...") lab.grid(row = 0, column = 1, padx = 20, pady = 20) but = ttk.Button(send, text = "Exit", command = send.destroy, state = 'disabled') but.grid(row = 1, column = 1, padx = 20, pady = 20) log = Label(send, image = logo) log.image = logo log.grid(row = 0, column = 0, rowspan = 2, padx = 20, pady = 20) try: term.destroy() except: pass try: mail.Send_response(res_email) sts.set("Email has been sent successfully!") but.config(state = 'normal') except Exception as e: sts.set(("Failed to send Email!\n" +"This may happend due to various reasons, see USER GUIDE.\n" +"A local copy of your response has been saved.\n" +"You may find it in PIERA-ZONE\Student Responses.\n" +"You can share it as per the instructions.")) but.config(state = 'normal')
def SelectMenu(SelectKey): if SelectKey == "1": GeoInfoLibrary.main() elif SelectKey == "2": ListGoodFoodService.main() elif SelectKey == "3": ListMarketInfoServer.main() elif SelectKey == "4": SearchCulturalFacilitiesDetailService.main() elif SelectKey == "5": SendMail.main() elif SelectKey == "9": global loopFlag loopFlag = 0 else: pass
def main(): invoices = check_for_new_invoices() # returns array of invoices if invoices: for invoice in invoices: completed, invoice_data = extract_data(invoice) db.log('Extraction Completed: ' + completed.__str__()) if completed: add_invoice(invoice_data) else: # Due to wrong input data db.log('Extraction failure', 1) # as from address is stored in file name from_address = invoice.split()[-2].replace('<', '').replace( '>', '') # Informing sender SendMail.send_email(from_address) # logging in module db.log('Email sent due to extraction error', 1) update(invoices)
def checkFreezeRequest(self): self.acquire() try: frozen = self.mc.get(FROZEN) currentTime = time.time() if frozen is not None: freezeRequester = frozen[USER_NAME] t = frozen[TIME] if frozen[STATE] == PENDING_FREEZE and self.getSessionCount() == 0: SendMail.sendMail("No sessions active - please log in within 15 minutes and do your admin actions", freezeRequester, "System ready for administrator login") frozen[STATE] = FROZEN frozen[TIME] = time.time() self.mc.set(FROZEN, frozen) elif frozen[STATE] == FROZEN and currentTime - t > FIFTEEN_MINUTES \ and not self.isUserLoggedIn(freezeRequester): self.mc.delete(FROZEN) finally: self.release()
def alert(self, gamecode, language, region, server_id, alert_per, now_online, his_online, alert_value, dbconn): w = and_( self.games_triggers.c.gamecode == gamecode, self.games_triggers.c.language == language, self.games_triggers.c.region == region, self.games_triggers.c.serverid == server_id, ) s = select([self.games_triggers]).where(w) r = dbconn.execute(s) if r.rowcount == 0: ins = self.games_triggers.insert().values(gamecode=gamecode, language=language, region=region, serverid=server_id, time=int(time.time())) dbconn.execute(ins) else: u = self.games_triggers.update().where(w).values( time=int(time.time())) dbconn.execute(u) return mail_to = '[email protected],[email protected]' subject = 'Problem: %s-%s-S%s 在线人数报警!' % (gamecode, region, server_id) content = ''' <h6 id="toc_0">在线人数报警</h6> <blockquote> <p>游戏: <code>%s</code><br/> 语言: <code>%s</code><br/> 地区: <code>%s</code><br/> 游戏服: <code>%s</code><br/> 下跌百分比: <code>%s</code><br/> 当前15分钟内平均在线人数: <code>%s</code><br/> 历史五天同一时间平均在线人数: <code>%s</code><br/> 报警阈值: <code>%s</code><br/> 【可通过信息自行判断是否为异常】</p> </blockquote> ''' % (gamecode, language, region, server_id, alert_per, now_online, his_online, alert_value) sm.send_mail(mail_to, subject, content)
def alert(self, gamecode, language, region, server_id, alert_per, now_online, his_online, alert_value, dbconn): w = and_( self.games_triggers.c.gamecode == gamecode, self.games_triggers.c.language == language, self.games_triggers.c.region == region, self.games_triggers.c.serverid == server_id, ) s = select([self.games_triggers]).where(w) r = dbconn.execute(s) if r.rowcount == 0: ins = self.games_triggers.insert().values( gamecode=gamecode, language=language, region=region, serverid=server_id, time=int(time.time()) ) dbconn.execute(ins) else: u = self.games_triggers.update().where(w).values(time=int(time.time())) dbconn.execute(u) return mail_to = '*****@*****.**' subject = 'Problem: %s-%s-S%s 在线人数报警!' % (gamecode, region, server_id) content = ''' <h6 id="toc_0">在线人数报警</h6> <blockquote> <p>游戏: <code>%s</code><br/> 语言: <code>%s</code><br/> 地区: <code>%s</code><br/> 游戏服: <code>%s</code><br/> 下跌百分比: <code>%s</code><br/> 当前15分钟内平均在线人数: <code>%s</code><br/> 历史五天同一时间平均在线人数: <code>%s</code><br/> 报警阈值: <code>%s</code><br/> 【可通过信息自行判断是否为异常】</p> </blockquote> ''' % (gamecode, language, region, server_id, alert_per, now_online, his_online, alert_value) sm.send_mail(mail_to, subject, content)
def start_uploading(settings): """ start uploading process based on "upload_scheduler.txt" :return: None """ today = datetime.date.today() with open("upload_scheduler.txt", "r") as f: lines = [l for l in f if l.strip()] for i, lin in enumerate(lines): path, time, status = lin.split() program = os.path.basename(os.path.dirname(path)) target_date = datetime.datetime.strptime(time, "%Y-%m-%d").date() if status == "pending" and target_date == today: if program not in args.observing_programs: Message.addMessage( "skipping uploading program: {} ({})".format( program, os.path.basename(path)), dump="header") continue Message.clearMessage("program") Message.clearMessage("session") Message.clearMessage("download") Message.clearMessage("log") upload = settings[program].get("upload", "no").lower() if upload == "ivs": code = os.path.basename(os.path.dirname(path)) Transfer.upload(path) emails = Helper.read_emails(settings[program], args.fallback_email) SendMail.writeMail_upload(code, emails) elif upload == "no": pass elif upload == "gow": code = os.path.basename(os.path.dirname(path)) Transfer.upload_GOW_ftp(path) emails = Helper.read_emails(settings[program], args.fallback_email) SendMail.writeMail_upload(code, emails) else: emails = upload.split(",") with open(os.path.join(path, "selected", "email.txt"), "r") as f: body = f.read() SendMail.writeMail(os.path.join(path, "selected"), emails, body) lines[i] = lin.replace("pending", "uploaded") with open("upload_scheduler.txt", "w") as f: for lout in lines: path, time, status = lout.split() target_date = datetime.datetime.strptime(time, "%Y-%m-%d").date() # do not list sessions older than 1 year in upload_scheduler.txt if target_date + datetime.timedelta(days=365) > today: f.write(lout)
def read_inbox(): mail.select('Inbox') # Returned data is a tuple # - we're only interested in data, so a placeholder is placed _, data = mail.search(None, '(UNSEEN)') # search for unread emails inbox_item_list = data[0].split() # list of references to emails if not inbox_item_list: print('No unread emails') for item in inbox_item_list: # Returned data are tuples of message part envelope and data # The latter type of payload is indicated as multipart/* or message/rfc822 _, email_data = mail.fetch(item, '(RFC822)') # returns email in byte form string_email = email_data[0][1].decode("utf-8") # extracting email_message = email.message_from_string( string_email) # converting to object if get_invoices(email_message): print('Invoice collected') else: sender_email = email_message['From'] SendMail.send_email(sender_email) # sends default mail mail.uid('STORE', item, '+FLAGS', '\\SEEN') # marking email as read
def main(): running = True kittyChecker = CheckKittys() scanner = BLESerialScanner(process) # dev_id = 0 # try: # sock = bluez.hci_open_dev(dev_id) # print "ble thread started" # except: # print "error accessing bluetooth device..." # sys.exit(1) # blescan.hci_le_set_scan_parameters(sock) # blescan.hci_enable_le_scan(sock) kittyChecker.daemon = True kittyChecker.kittys = config.kittys kittyChecker.running = True kittyChecker.start() scanner.start() message = "Kitty Tracker Active! Now tracking " + ", ".join( str(k.name) for k in config.kittys) print message SendMail.sendMail(message) try: while running: time.sleep(1) except KeyboardInterrupt: running = False kittyChecker.running = False scanner.running = False print "Terminating..."
def generateAdminAuthorizeAccountEmail(firstName, lastName, emailAddress, serverUrlPrefix, token): """ Generate and send email. This is a thread since the SMTP timeout is 30 seconds """ hyperlink_format = '<a href="{link}">{text}</a>' urlToClickToAuthorize = serverUrlPrefix + "/spectrumbrowser/authorizeAccount/" + emailAddress + "/" + str( token) util.debugPrint( "urlToClickToAuthorize for generateAdminAuthorizeAccountEmail email" + urlToClickToAuthorize) urlToClickToDeny = serverUrlPrefix + "/spectrumbrowser/denyAccount/" + emailAddress + "/" + str( token) util.debugPrint( "urlToClickToDeny for generateAdminAuthorizeAccountEmail email" + urlToClickToDeny) message = "This is an automatically generated message from the Spectrum Monitoring System.\n"\ + firstName + " " + lastName + " (" + emailAddress + ") requested a new account for the CAC Measured Spectrum Occupancy Database.\n"\ + "Please click " + hyperlink_format.format(link=urlToClickToAuthorize, text='here') + " within 48 hours if you wish to authorize the account and email the user,\n"\ + "or please click " + hyperlink_format.format(link=urlToClickToDeny, text='here') + " within 48 hours if you wish to deny the account and email the user.\n" util.debugPrint(message) SendMail.sendMail(message, Config.getSmtpEmail(), "Account authorization link", True)
def task(start, end): global counter sql = MySQLdb.connect("localhost", "root", "****", "www", charset="utf8") cur = sql.cursor() #end=start+50 for x in range(start, end): try: print counter handleOnePage(getPage(str(x), "16-17-3"), sql, cur) counter = counter + 1 except Exception as e: print e SendMail.SendMail("*****@*****.**", "Inform", str(start) + "-" + str(end) + " Finished!") cur.close() sql.close()
st.write("Total score : ",total_score,"%") st.write("Result : ",Result) st.write("Grade : ",Grade) if data['total_score'][0] >=85: st.success("**Congratulations! Keep going!!! Best of luck!!**") elif data['total_score'][0] >=50 and data['total_score'][0] < 85: st.success("**Nice! You can still do better. Best of luck!!**") else: st.warning("**Woops!!! You need to work hard. Don't loose hope and keep working hard. Best of luck!!**") sm = SendMail.Mail(name_ip, roll_no_ip, total_score, Result, Grade, email_ip) sm.send_mail() with st.spinner('!!Mail sent to given email address!!'): time.sleep(2) list_1 = [[roll_no_ip, name_ip, email_ip, gender_ip, p_level_ip, lunch_ip, test_prep_ip, math_ip, read_ip, write_ip, total_score, Grade, Result]] data_1 = pd.DataFrame(list_1, columns = ['Roll No.','Name','Parent\'s Email ID','Gender', 'Parental Level of Education', 'Lunch', 'Test Preparation Course', 'Maths Score', 'Reading Score', 'Writing Score', 'Total Score', 'Grade', 'Result']) if os.path.exists(path+'/Data/Student_data.xlsx'): wb = load_workbook(path+'/Data/Student_data.xlsx') sheet = wb.active for row in list_1:
'Samples':[ 'WW-LO', 'WZ', 'ZZ', 'TTToSemiLeptonic', '_WpWmJJ_', '_WpWpJJ_', 'ST_t', 'TTW', 'TTZ', 'WJetsToLN', 'DYJets', 'QCD', ], } job=latinoTransfer() job.Production=dic['Production'] job.Step=dic['Step'] for s in dic['Samples']: this_list=job.MakeList(Sample=s) job.Run(this_list) from SendMail import * SendMail(GetScriptName())
subjectPostPend = "" #print(a.checkDict) try: for k, v in a.checkDict.items(): for item, itemData in v['results'].items(): count = count + 1 mail = mail + "<p style=\"font-size:%spx\">Alarm on item %s while \"%s\"</p>\n" % ( fontsize, item, v['name']) mail = mail + "<p style=\"color:#770000; font-size:%spx\">%s</p>\n" % ( fontsize - 3, pprint(itemData)) mail = mail + "<table>" for itemDataK, ItemDataV in itemData.items(): mail = mail + "<tr><td style=\"font-size:%spx\">%s</td<><td style=\"font-size:%spx\">%s</td></tr>" % ( fontsize - 3, itemDataK, fontsize - 3, ItemDataV) mail = mail + "</table>" subjectPostPend = " | %s" % v['name'] except: pass mail = mail + "</body></html>\n" if count >= 1: from SendMail import * smtpResp = SendMail( config.toAddrs, mail, "Alarm from %s %s" % (socket.gethostname(), subjectPostPend)) #for to in config.toAddrs: # print("[a] mail to %s from %s"%(to,config.toAddrs)) # smtpResp = SendMail(to,mail,"Alarm from RedELK") print("[A] we had %s alarm lines" % count) else: print("[ ] no alarms")
for i in range(len(bottleKeys)): for j in range(2): if(imageInfos[j].find(bottleKeys[i]) > -1): result = open("/srv/nfs/IoT/result", "w") result.write("bottle") result.close() sys.exit() generalGarbage = open("/srv/nfs/IoT/code/generalGarbage", "r") generalGarbageKeys = generalGarbage.read().splitlines() generalGarbage.close() for i in range(len(generalGarbageKeys)): for j in range(len(imageInfos)): if(imageInfos[j].find(generalGarbageKeys[i]) > -1): result = open("/srv/nfs/IoT/result", "w") result.write("generalGarbage") result.close() sys.exit() result = open("/srv/nfs/IoT/result", "w") result.write("other") result.close() SendMail.send(imagePath) for i in range(30): sleep(2) if(FetchMail.fetch()): break
import SendMail as sm sender = "*****@*****.**" sender_password = "******" receiver = "you@your_provider.com" subject = "the subject" message = "the message" mail_ = sm.SendMail(sender, sender_password, receiver, subject, message) mail_.SendEmail()
def main(): short_opts = "hvawclt:d:r" long_opts = [ "help", "verbose", "wizard", "automatic", "clean" "no-checkout", "no-log", "max-threads=", "driver="] try: opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts) except getopt.GetoptError: usage() sys.exit(1) # Initialize of general stuff global verbose rc_file = '' checkout_step = 1 log_step = 1 clean = 0 verbose = 0 maxthreads = 2 driver = "mysql" if args == []: usage() sys.exit(0) # Config file comes from args rc_file = args[0] for o, a in opts: if o in ("-h", "--help"): usage() sys.exit(0) elif o in ("-a", "--automatic"): wz.automatic_wizard(rc_file) sys.exit(0) elif o in ("-t", "--max-threads"): maxthreads = a elif o in ("-c", "--no-checkout"): checkout_step = 0 elif o in ("-l", "--no-log"): log_step = 0 elif o in ("-w", "--wizard"): wz.wizard(rc_file) sys.exit(0) elif o in ("-d", "--driver"): driver = a elif o in ("-r", "--clean"): clean = 1 elif o in ("-v", "--verbose"): verbose = 1 print credits # Parse config file cprint ("[*] Reading config file: " + str(rc_file)) rc = parsermodule.ParserConfigFile() rc.read_rcfile(rc_file) rc.buildstamps() # Get values from config file workspace = rc.get_workspace() user = rc.get_username() password = rc.get_password() host = rc.get_hostname() database = rc.get_database() # Create workspace if os.path.isdir(workspace): cprint ("[*] Using workspace: " + str(workspace)) else: cprint ("[*] Creating workspace: " + str(workspace)) gb.Globals.createdir(workspace) # Access Database conection = driver + "://" + user + ":" + password + "@" + host + "/" + database gb.Globals.connection = conection db = dbmodule.Database(conection) # Create database and tables db.create_database() db.create_table('files',Tables.files) db.create_table('commiters',Tables.commiters) db.create_table('dates',Tables.dates) db.create_table('directories', Tables.directories) db.create_table('functions', Tables.functions) cprint ("[*] Database %s succesfully created" % (database)) # CVS/SVN interactive parser = rpmodule.RepositoryFactory.create(rc.config_map['type'], maxthreads) parser.modules = rc.get_modules() parser.repository = rc.get_repository() parser.type = rc.get_type() # Main Loop. All actions should be under this 'for' for mydate in rc.dates: # create table for actual annotate timestamp taux = 'annotates_' + str(mydate).replace("-","_") db.create_table(taux, Tables.annotates) # Add to the Timestamp object the new reference timemodule.Timestamp.settimes(mydate,db) # Config values for checkout and create dir parser.src_dir = workspace + 'src_' + str(mydate) parser.date = mydate gb.Globals.createdir(workspace + 'src_' + str(mydate)) if checkout_step: parser.checkout() # Log step in time if log_step: # blame method creates new Line objects cprint ("[*] Parsing logs for date: " + str(mydate)) parser.collect() parser.annotate() print "\n" # clean checkout if clean: cprint ("[*] Deleting checkout ...") parser.clean() cprint ("[*] Creating index database...") db.create_index(taux, ["line_id","file_id","dir_id","commiter_id","revision"],"index_"+taux) # Directories dmodule.Directory.directory2sql(db) # Functions fmodule.Function.functions2sql(db) db.close() # Only if user has set send mail if rc.config_map['sendmail']: server = rc.config_map['smtpserver'] mail = rc.config_map['mail'] mailmodule.sendMail('carnarvon',mail, server, database) cprint ("\nProcess Completed! \n")
def start_scheduling(settings): """ start VieSched++ AUTO processing :return: None """ prefix = settings["general"].get("prefix_output_folder", "Schedules") if os.sep == "\\": prefix = prefix.replace("/", "\\") path_scheduler = settings["general"].get("path_to_scheduler") if not os.path.exists("upload_scheduler.txt"): with open("upload_scheduler.txt", "w"): pass Message.addMessage("VieSched++ AUTO report", dump="header") today = datetime.date.today() Message.addMessage("date: {:%B %d, %Y}".format(today), dump="header") Message.addMessage("computer: {}, Python {}".format( platform.node(), platform.python_version()), dump="header") if settings["general"].get("institute") is not None: Message.addMessage("institution: {}".format( settings["general"].get("institute")), dump="header") Message.addMessage( "This is an automatically generated message. Do NOT reply to this email directly!", dump="header") # download files if not args.no_download: Transfer.download_ftp() Transfer.download_http() else: Message.addMessage("no downloads", dump="header") # start processing all programs for program in settings.sections(): if program == "general": continue if program not in args.observing_programs: print("skipping scheduling observing program: {}".format(program)) continue s_program = settings[program] emails = Helper.read_emails(s_program, args.fallback_email) delta_days = s_program.get("schedule_date", "10") if args.date is not None: try: target_day = datetime.datetime.strptime(args.date, '%Y-%m-%d') delta_days = (target_day.date() - today).days year = target_day.year % 100 except ValueError: print("ERROR while interpreting target date (-d option): {}". format(args.date)) print( " must be in format \"yyyy-mm-dd\" (e.g.: 2020-01-31)") return else: try: target_day = datetime.datetime.strptime(delta_days, '%Y-%m-%d') delta_days = (target_day.date() - today).days year = target_day.year % 100 except ValueError: if delta_days.isnumeric(): delta_days = int(delta_days) target_day = today + datetime.timedelta(days=delta_days) year = target_day.year % 100 else: delta_days = delta_days.lower() year = today.year % 100 delta_days_upload = s_program.getint("upload_date", 7) statistic_field = s_program.get("statistics").split(",") upload = True if s_program.get("upload", "no").lower() == "no": upload = False # read master files template_master = Template(s_program.get("master", "master$YY.txt")) master = template_master.substitute(YY=str(year)) master = os.path.join("MASTER", master) sessions = Helper.read_master(master) try: pattern = s_program["pattern"] f = Helper.find_function(select_best_functions, s_program["function"])[0] f_pre = Helper.find_function( pre_scheduling_functions, s_program.get("pre_scheduling_functions", "")) f_post = Helper.find_function( post_scheduling_functions, s_program.get("post_scheduling_functions", "")) start(sessions, path_scheduler, program, pattern, f, emails, delta_days, delta_days_upload, statistic_field, prefix, upload, f_pre, f_post) except: Message.addMessage("#### ERROR ####") Message.addMessage(traceback.format_exc()) SendMail.writeErrorMail(emails)
def dealError(content): print('Server Error') SendMail.sendErrorInfo(res) # 发送错误数据
# MAIL_LIST = ["*****@*****.**"] # MAIL_LIST = ["*****@*****.**", "*****@*****.**", "*****@*****.**"] MAIL_LIST = ["*****@*****.**","*****@*****.**","*****@*****.**"] MAIL_HOST = "mail.ebscn.com" MAIL_USER = "******" MAIL_PASS = "******" MAIL_POSTFIX = "ebscn.com" MAIL_FROM = MAIL_USER + "<"+MAIL_USER + "@" + MAIL_POSTFIX + ">" contents = "新闻内容: \t" + title.decode('gbk').encode('utf8') + "\n" contents = contents + "新闻链接: \t" + urlnews + "\n" contents = contents + "搜索关键词: \t" + input.decode('gbk').encode('utf8') + "\n\n" contents = contents + "关联股票: \t" for wordLev1 in topWordLev1: contents = contents + str(wordLev1[0]) + " " if topWordLev1.index(wordLev1) == 9 and len(topWordLev1) != 10: contents = contents + "\n\t\t" contents = contents + "\n" title=u'[光大新闻分析引擎]'.encode('utf8')+title.decode('gbk').encode('utf8') if SendMail.send_mail(title, contents ,[wordSeqpic,jpgfile], MAIL_LIST, MAIL_HOST, MAIL_USER, MAIL_PASS, MAIL_POSTFIX, MAIL_FROM): print "发送成功...".decode('utf8').encode('gbk') else: print "发送失败...".decode('utf8').encode('gbk') #------------------- End --------------------# #ie.quit() time.sleep(5) # os.system('pause')