def bkpcheckmain(): connectioninfo = [ "35.224.121.101", 3306, "yiming", "yiming", "schedulerDB" ] # main mysql sqlstr = "SELECT debugmode, job_last_ping_time FROM schedulerDB.realtime_status WHERE name='main';" db = MySQLdb.connect(host=connectioninfo[0], port=connectioninfo[1], user=connectioninfo[2], passwd=connectioninfo[3], db=connectioninfo[4]) cursor = db.cursor() cursor.execute(sqlstr) retlst = cursor.fetchall()[0] if retlst[ 0] == 'debug': # if its debug model we dont send email, which stop sending soooo many emails return if timecheck(retlst[1]) is False: se.sendemail("error!", "Hi man, Main scheduler is out of order!", [ '*****@*****.**', ]) ####Turn to debug cursor.execute( "UPDATE schedulerDB.realtime_status SET debugmode='debug' WHERE name='main';" ) db.commit() cursor.close() db.close()
def run(): for i in range(1000000): cheapSeen = False html = content(url) items = parse(html) item = items[0] if item['amount'] < THRESHOLD: print item['amount'] print item['href'] cheapSeen = True subject = 'Cheapest knife: %s' % item['name'] if item['amount'] not in sent: webbrowser.open(item['href'], new=1) sendemail(subject.encode('utf-8'), prettyMessage(item)) sent.append(item['amount']) if not cheapSeen: if len(items) > 0: print '#', i, ': Cheapest is ', items[0]['amount'] time.sleep(1)
def poll2(self): #url = 'http://d.web2.qq.com/channel/poll2' url = 'http://d1.web2.qq.com/channel/poll2' data = {"ptwebqq":self.ptwebqq, "clientid":53999199, "psessionid":self.psessionid, "key":"" } headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0)', 'Host':'d1.web2.qq.com', 'Origin':'http://d1.web2.qq.com', 'Referer':'http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2' # 等待检测 } postdata = urllib.urlencode({'r':json.dumps(data)}) request = urllib2.Request(url=url, data=postdata, headers=headers) #logging.info('send to poll msg_id') try: html = self.opener.open(request).read() self.gerror = 0 except urllib2.HTTPError, e: logging.warning('{0}'.format(e)) self.gerror += 1 if self.gerror > 10: sendemail('poll2错误次数太多', u'请查看输入日志') logging.error(u'poll2错误次数太多') exit() return None
def maincheckbkp(): connectioninfo = [ "104.197.118.95", 3306, "yiming", "yiming", "schedulerDB" ] sqlstr = "SELECT debugmode, job_last_ping_time FROM schedulerDB.realtime_status WHERE name='bkp';" db = MySQLdb.connect(host=connectioninfo[0], port=connectioninfo[1], user=connectioninfo[2], passwd=connectioninfo[3], db=connectioninfo[4]) cursor = db.cursor() cursor.execute(sqlstr) retlst = cursor.fetchall()[0] if retlst[0] == 'debug': return if timecheck(retlst[1]) is False: se.sendemail("error!", "Hi man, Bkp scheduler is out of order!", [ '*****@*****.**', ]) ####Turn to debug cursor.execute( "UPDATE schedulerDB.realtime_status SET debugmode='debug' WHERE name='bkp';" ) db.commit() cursor.close() db.close()
def poll2(self): #url = 'http://d.web2.qq.com/channel/poll2' url = 'http://d1.web2.qq.com/channel/poll2' data = { "ptwebqq": self.ptwebqq, "clientid": 53999199, "psessionid": self.psessionid, "key": "" } headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0)', 'Host': 'd1.web2.qq.com', 'Origin': 'http://d1.web2.qq.com', 'Referer': 'http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2' # 等待检测 } postdata = urllib.urlencode({'r': json.dumps(data)}) request = urllib2.Request(url=url, data=postdata, headers=headers) #logging.info('send to poll msg_id') try: html = self.opener.open(request).read() self.gerror = 0 except urllib2.HTTPError, e: logging.warning('{0}'.format(e)) self.gerror += 1 if self.gerror > 10: sendemail('poll2错误次数太多', u'请查看输入日志') logging.error(u'poll2错误次数太多') exit() return None
def send(self, subject, body): # encode string as ascii ignoring encoding errors subject = subject.encode('ascii', errors='ignore') body = body.encode('ascii', errors='ignore') cfg = ConfigParser.ConfigParser() cfg.read(self.cfgfile) try: from_address = cfg.get('report', 'from') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): self.logger.error( 'No "from" option defined in "report" section of file "%s".\n' % self.cfgfile) return try: mail_dest = [ x.strip() for x in cfg.get('email', 'dest').split(',') ] except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_dest = [] try: mail_username = cfg.get('email', 'username') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_username = None try: mail_password = cfg.get('email', 'password') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_password = None try: mail_server = cfg.get('email', 'server') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_server = 'mail.mozilla.com' try: mail_port = cfg.getint('email', 'port') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_port = 465 try: mail_ssl = cfg.getboolean('email', 'ssl') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_ssl = True sendemail(from_addr=from_address, to_addrs=mail_dest, subject='%s%s' % (self.subject_prefix, subject), username=mail_username, password=mail_password, text_data=body, server=mail_server, port=mail_port, use_ssl=mail_ssl)
def save_to_database(self): self.cur.execute('SELECT header FROM Notices WHERE header = ? LIMIT 1 ',(self.header,)) try: row =self.cur.fetchone()[0] print 'No new notice' except: # print self.header self.cur.execute('''INSERT INTO Notices VALUES (?,?,?,?,?)''', (None,self.header,self.data_url,self.content,self.times)) send_text = self.header+'\n'+self.noticedetail # sign = weixin.send_msg(self.header) sendemail.sendemail('<notice>'+self.header,self.noticedetail,to_list = sendemail.TO_LIST) time.sleep(4) sendemail.sendemail(self.header,self.content,to_list = sendemail.TO_LIST1)
def rage_call(self): ultra_val = rs.sensor() light_val = ls.light() if self.mode == 1: print(ultra_val,light_val) if ultra_val == 1 or light_val != self.pre: self.pre = light_val self.show_meme() sendemail.sendemail() self.root.after(3000, self.rage_call) else: self.pre = light_val self.root.after(1000, self.rage_call)
def back_to_normal_email(self, user, queue_data): exchange = self._exchange_from_queue(queue_data) subject = 'Pulse warning: queue "{0}" is back to normal'.format(queue_data['name']) body = '''Your queue "{0}" on exchange "{1}" is now back to normal ({2} ready messages, {3} total messages). '''.format(queue_data['name'], exchange, queue_data['messages_ready'], queue_data['messages'], self.del_queue_size) if self.emails and user.email is not None: sendemail(subject=subject, from_addr=config.email_from, to_addrs=[user.email], username=config.email_account, password=config.email_password, text_data=body)
def start(filename, user): filename = filename + '_' + date.today().isoformat() self.data.prettyname = 'Toilet Literature, ' + date.today().isoformat() self.data.name = filename self.data.filename = filename + '.html' feeds = self.get_feed(user.feeds) article = codecs.open(os.path.join(self.path, 'html', filename + '.html'), 'w+', encoding='utf-8') article.write(self.content(feeds).decode('utf-8')) article.close() welcome = codecs.open(os.path.join(self.path, 'html', 'welcome.html'), 'w+', encoding='utf-8') welcome.write(self.welcome()) welcome.close() toc = codecs.open(os.path.join(self.path, 'html', 'toc.html'), 'w+', encoding='utf-8') toc.write(self.toc(feeds).decode('utf-8')) toc.close() ncx = codecs.open(os.path.join(self.path, 'html', filename + '.ncx'), 'w+', encoding='utf-8') ncx.write(self.ncx(feeds)) ncx.close() opf = codecs.open(os.path.join(self.path, 'html', filename + '.opf'), 'w+', encoding='utf-8') opf.write(self.opf().decode('utf-8')) kindlegen = sh.Command(os.path.join(self.path, 'bin', 'kindlegen')) kindlegen(os.path.join(opf.name), '-gif', _ok_code=[0, 1]) opf.close() sender = user.email password = user.email_password recipient = user.kindle_device subject = 'Daily Digest ' + date.today().isoformat() message = 'Sir, your daily digest. xoxo --Kindress' sendemail(sender, password, recipient, subject, message)
def send(self, subject, body): # encode string as ascii ignoring encoding errors subject = subject.encode('ascii', errors='ignore') body = body.encode('ascii', errors='ignore') cfg = ConfigParser.ConfigParser() cfg.read(self.cfgfile) try: from_address = cfg.get('report', 'from') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): self.logger.error('No "from" option defined in "report" section of file "%s".\n' % self.cfgfile) return try: mail_dest = [x.strip() for x in cfg.get('email', 'dest').split(',')] except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_dest = [] try: mail_username = cfg.get('email', 'username') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_username = None try: mail_password = cfg.get('email', 'password') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_password = None try: mail_server = cfg.get('email', 'server') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_server = 'mail.mozilla.com' try: mail_port = cfg.getint('email', 'port') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_port = 465 try: mail_ssl = cfg.getboolean('email', 'ssl') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_ssl = True sendemail(from_addr=from_address, to_addrs=mail_dest, subject='%s%s' % (self.subject_prefix, subject), username=mail_username, password=mail_password, text_data=body, server=mail_server, port=mail_port, use_ssl=mail_ssl)
def monitory_v2(): web3 = connect_http(local_http) new_contract_address = [] while 1: transactions_info, transactions_receipt = get_transaction_info(web3) for info , receipt in zip(transactions_info , transactions_receipt): print(info['from']) if str(info['from']) == v2_contract_address: new_contract = receipt['contractAddress'] new_contract_address.append(new_contract) subject = "new contarct from v2 factory contract." print(subject) msg = new_contract sendemail.sendemail(subject,msg) print("send email") time.sleep(1)
def checkfallen(): try: if (float(sensors['ytilt']) < float (-80) or float(sensors['ytilt']) > float (80) and float(sensors['speed']) < 5 ): print ("Caida detectada") try: sendemail.sendemail(sensors['latitude'], sensors['longitude']) except: print ("Imposible enviar Aviso") return True else: return False except: print ("El GPS no ha enviado la primera medida aun")
def deletion_email(self, user, queue_data): exchange = self._exchange_from_queue(queue_data) subject = 'Pulse warning: queue "{0}" has been deleted'.format(queue_data['name']) body = '''Your queue "{0}" on exchange "{1}" has been deleted after exceeding the maximum number of unread messages. Upon deletion there were {2} messages in the queue, out of a maximum {3} messages. Make sure your clients are running correctly and are cleaning up unused durable queues. '''.format(queue_data['name'], exchange, queue_data['messages'], self.del_queue_size) if self.emails and user.email is not None: sendemail(subject=subject, from_addr=config.email_from, to_addrs=[user.email], username=config.email_account, password=config.email_password, text_data=body)
def resendemail(): try: if current_user.is_anonymous or current_user.confirmed: return redirect(url_for('index')) else: token = current_user.generate_confirmation_token() sendemail(current_user.email, 'confirm Your Account', 'confirm', user=current_user, token=token) return redirect(url_for('index')) #return redirect(url_for('index')) except: return render_template('error.html', title='Signup Fail', value='Fail to send email')
def back_to_normal_email(self, user, queue_data): exchange = self._exchange_from_queue(queue_data) subject = 'Pulse warning: queue "{0}" is back to normal'.format( queue_data['name']) body = '''Your queue "{0}" on exchange "{1}" is now back to normal ({2} ready messages, {3} total messages). '''.format(queue_data['name'], exchange, queue_data['messages_ready'], queue_data['messages'], self.del_queue_size) if self.emails and user.email is not None: sendemail(subject=subject, from_addr=config.email_from, to_addrs=[user.email], username=config.email_account, password=config.email_password, text_data=body)
def recover_token(): val = parser.getData(request) vres = parser.validate(parser.getRecoveryRegex(), val) if vres: resp = jsonify(**vres) resp.status_code = 400 return resp rres = recover.checkCombination(val['email'], val['mac']) if rres: resp = jsonify(**rres) resp.status_code = 404 return resp else: resp_mail = db.getNodeMac(val['mac']) sendemail(getMail(resp_mail), [resp_mail['email']]) resp = val resp['status'] = 'success' return jsonify(**resp)
def __init__(self): self.emailutil = sendemail.sendemail() self.price = 200 self.to = [ '*****@*****.**', '*****@*****.**' ] reload(sys) sys.setdefaultencoding('utf-8')
def signup(): form = SignupForm() try: if form.validate_on_submit(): user_name = request.form.get('username', None) password = request.form.get('password', None) email = request.form.get('email', None) if not checkusername(user_name): return render_template('error.html', title='Signup Fail', value='Illegal username') if not checkemail(email): return render_template('error.html', title='Signup Fail', value='Wrong email format') user = User(user_name) user.email = email if not user.exists(): token = user.generate_confirmation_token() user.password = password sendemail(user.email, 'confirm Your Account', 'confirm', user=user, token=token) return redirect(url_for('index')) #if ret: #return redirect(url_for('index')) #else: #return render_template('error.html',title='Signup Fail', value='Fail to send email') else: return render_template('error.html', title='Signup Fail', value='User or email exists') else: return render_template('error.html', title='Signup Fail', value='Please fill all part') except: return render_template( 'error.html', title='Signup Fail', value= 'Oops, we encounter some problems, please contact us for details.')
def send(self, subject, body): cfg = ConfigParser.ConfigParser() cfg.read(self.cfgfile) try: from_address = cfg.get('report', 'from') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): logging.error('No "from" option defined in "report" section of file "%s".\n' % options.config_file) return try: mail_dest = [x.strip() for x in cfg.get('email', 'dest').split(',')] except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_dest = [] try: mail_username = cfg.get('email', 'username') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_username = None try: mail_password = cfg.get('email', 'password') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_password = None try: mail_server = cfg.get('email', 'server') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_server = 'mail.mozilla.com' try: mail_port = cfg.getint('email', 'port') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_port = 465 try: mail_ssl = cfg.getboolean('email', 'ssl') except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): mail_ssl = True sendemail(from_addr=from_address, to_addrs=mail_dest, subject=subject, username=mail_username, password=mail_password, text_data=body, server=mail_server, port=mail_port, use_ssl=mail_ssl)
def warning_email(self, user, queue_data): exchange = self._exchange_from_queue(queue_data) subject = 'Pulse warning: queue "{0}" is overgrowing'.format( queue_data['name']) body = '''Warning: your queue "{0}" on exchange "{1}" is overgrowing ({2} ready messages, {3} total messages). The queue will be automatically deleted when it exceeds {4} messages. Make sure your clients are running correctly and are cleaning up unused durable queues. '''.format(queue_data['name'], exchange, queue_data['messages_ready'], queue_data['messages'], self.del_queue_size) if self.emails and user.email is not None: sendemail(subject=subject, from_addr=config.email_from, to_addrs=[user.email], username=config.email_account, password=config.email_password, text_data=body)
def generate(self, user_id, email_monitor): self.key = randint(1000, 9999) filename = '{0}'.format(str(user_id)) pathname = os.path.abspath(os.path.join('tokens', filename)) save = '{0}:{1}:{2}'.format(str(self.key), str(user_id), email_monitor) f = open(os.path.abspath(os.path.join('tokens', filename)), 'w').write(save) key_hash = self.hash_id.encrypt(self.key) result_send = sendemail(email_monitor, key_hash) return result_send
def save_to_database(self): self.cur.execute( 'SELECT header FROM Notices WHERE header = ? LIMIT 1 ', (self.header, )) try: row = self.cur.fetchone()[0] print 'No new notice' except: # print self.header self.cur.execute( '''INSERT INTO Notices VALUES (?,?,?,?,?)''', (None, self.header, self.data_url, self.content, self.times)) send_text = self.header + '\n' + self.noticedetail # sign = weixin.send_msg(self.header) sendemail.sendemail('<notice>' + self.header, self.noticedetail, to_list=sendemail.TO_LIST) time.sleep(4) sendemail.sendemail(self.header, self.content, to_list=sendemail.TO_LIST1)
def send(self, subject, body): if not self.from_address or not self.mail_dest: return # encode string as ascii ignoring encoding errors subject = subject.encode('ascii', errors='ignore') body = body.encode('ascii', errors='ignore') try: sendemail(from_addr=self.from_address, to_addrs=self.mail_dest, subject='%s%s' % (self.subject_prefix, subject), username=self.mail_username, password=self.mail_password, text_data=body, server=self.mail_server, port=self.mail_port, use_ssl=self.mail_ssl) except socket.error: self.logger.exception('Failed to send email notification: ' 'subject: %s, body: %s' % (subject, body))
def deletion_email(self, user, queue_data): exchange = self._exchange_from_queue(queue_data) subject = 'Pulse warning: queue "{0}" has been deleted'.format( queue_data['name']) body = '''Your queue "{0}" on exchange "{1}" has been deleted after exceeding the maximum number of unread messages. Upon deletion there were {2} messages in the queue, out of a maximum {3} messages. Make sure your clients are running correctly and are cleaning up unused durable queues. '''.format(queue_data['name'], exchange, queue_data['messages'], self.del_queue_size) if self.emails and user.email is not None: sendemail(subject=subject, from_addr=config.email_from, to_addrs=[user.email], username=config.email_account, password=config.email_password, text_data=body)
def email(): if request.method == 'GET': return render_template('sendemail.html') else: receive = request.form.get('email') id = session.get('id') name = session.get('name') if sendemail(id, receive, name): flash('', 'OK') return render_template('sendemail.html') else: flash('', 'error') return render_template('sendemail.html')
def send(self, subject, body): if not self.from_address or not self.mail_dest: return # encode string as ascii ignoring encoding errors subject = subject.encode('ascii', errors='ignore') body = body.encode('ascii', errors='ignore') try: sendemail(from_addr=self.from_address, to_addrs=self.mail_dest, subject='%s%s' % (self.subject_prefix, subject), username=self.mail_username, password=self.mail_password, text_data=body, server=self.mail_server, port=self.mail_port, use_ssl=self.mail_ssl) except socket.error: logger = utils.getLogger() logger.exception('Failed to send email notification: ' 'subject: %s, body: %s', subject, body)
def getnew(): while True: try: now = int(time.time()) beforehour = now - 3600 select = """ select * from proxies where guoqitime < {} and guoqitime > {} """.format(now + 300, beforehour) num = curosr.execute(select) print("一小时内获取的ip数是:", num) # print(type(num)) # exit() if num >= 100: sendemail.sendemail("*****@*****.**", "IP异常获取", "1小时内获取了超过100IP") return False ip = requests.get(url).text re = requests.get("http://icanhazip.com", proxies={"http": ip[0:-2]}, timeout=(3, 10)) insert = """ insert into proxies(ip,guoqitime) values ('{}','{}') """.format(ip[0:-2], now + 300) curosr.execute(insert) db.commit() print("新获取了一个ip:" + ip[:-2]) return ip[:-2] except TimeoutError: print("新ip连接超时,重新获取") time.sleep(1) except Exception as e: print("新获取的ip发生错误") print(str(e)) time.sleep(2)
def start(filename, user): filename = filename+'_'+date.today().isoformat() self.data.prettyname = 'Toilet Literature, '+date.today().isoformat() self.data.name = filename self.data.filename = filename+'.html' feeds = self.get_feed(user.feeds) article = codecs.open(os.path.join(self.path,'html',filename+'.html'),'w+',encoding='utf-8') article.write(self.content(feeds).decode('utf-8')) article.close() welcome = codecs.open(os.path.join(self.path, 'html','welcome.html'),'w+',encoding='utf-8') welcome.write(self.welcome()) welcome.close() toc = codecs.open(os.path.join(self.path, 'html','toc.html'),'w+',encoding='utf-8') toc.write(self.toc(feeds).decode('utf-8')) toc.close() ncx = codecs.open(os.path.join(self.path, 'html',filename+'.ncx'), 'w+',encoding='utf-8') ncx.write(self.ncx(feeds)) ncx.close() opf = codecs.open(os.path.join(self.path, 'html',filename+'.opf'), 'w+',encoding='utf-8') opf.write(self.opf().decode('utf-8')) kindlegen = sh.Command(os.path.join(self.path, 'bin', 'kindlegen')) kindlegen(os.path.join(opf.name), '-gif',_ok_code=[0,1]) opf.close() sender = user.email password = user.email_password recipient = user.kindle_device subject = 'Daily Digest '+date.today().isoformat() message = 'Sir, your daily digest. xoxo --Kindress' sendemail(sender, password, recipient, subject, message)
def process_new(): # check for invalid data val = parser.getData(request) vres = parser.validate(parser.getNodeRegex(), val) if vres: resp = jsonify(**vres) resp.status_code = 400 return resp # check for duplicates ddres = dedup.checkDups(val['hostname'], val['mac'], val['key'], None) if ddres: resp = jsonify(**ddres) resp.status_code = 409 return resp # if we reach this part the data should be correct resp = val resp['token'] = token.getToken() db.addNode(resp) ffmap.genAliasJson() fastd.genFastdConf() alias.genAliasMap() sendemail(getMail(resp), [resp['email']]) resp['status'] = 'success' return jsonify(**resp)
def regQuery(self, interval=60): while True: try: # sleep for the remaining seconds of interval time_remaining = interval - time.time() % interval time.sleep(time_remaining) db = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db, charset='UTF8') cur = db.cursor() # 选择时间已到的事件 sql = ( """select * from event where UNIX_TIMESTAMP(alarm_time) = '%d' and if_email = '%s'""" % (int(time.time()), '1')) cur.execute(sql) res = cur.fetchall() if res: for row in res: print(row) msgto = row[0] title = row[2] alarm_time = row[5] action_time = row[6] delta = action_time - alarm_time #print(delta.days, delta.seconds) days = delta.days hours = delta.seconds // 3600 minutes = delta.seconds // 60 #print(hours, minutes, seconds) text = ('您好,您的事件' + title + '还有' + str(days) + '天' + str(hours) + '小时' + str(minutes) + '分就要开始了') # 发送email Send = sendemail.sendemail() Send.sendto(msgto, text) else: pass db.close() except Exception as e: print(e)
for j in i: print j, print while not time.sleep(1): try: r=login(stuid) l=today_data(r) #print 'local times',last_num,',live times',len(l), print l if not last_num==len(l): #print for i in l: for k in i: print k, print last_num=len(l) print l[-1:] text=l[-1:][0][1]+", "+l[-1:][0][2]+', '+str(l[-1:][0][4]) #sendsmsex(phone,text) sendemail(text) except: pass for i in months_data(r): print i
content = jsonData['result'][0]['value']['content'][1] fromuin = jsonData['result'][0]['value']['from_uin'] #senduin = jsonData['result'][0]['value']['send_uin'] # 发送者的uin value = ['group_message', fromuin, content] # 群 群的uin 文本 群qq #print 'value',value return value except Exception, e: logging.error('Error {0}'.format(e)) if retcode == 116: self.ptwebqq = jsonData.get('p') elif retcode == 121: logging.error(u'程序出现未知错误,可能断网,账号在别处登录(这是一个调试语句,请反馈)') os.remove('image.jpg') sendemail('121错误', u'121错误') exit() elif retcode == 103: logging.error(u'程序出现未知错误, 代码103') sendeoail('103错误', u'103错误') exit() def send_qun(self, group_uin, content): """发送群消息 send_qun(群的uin不是群号码,要说的内容) """ #r:{"to":3497160265,"content":"[\"44\",[\"font\",{\"name\":\"宋体\",\"size\":10,\"style\":[0,0,0],\"color\":\"000000\"}]]","face":0, # "clientid":53999199,"msg_id":80120003,"psessionid":""}\ url = 'http://d1.web2.qq.com/channel/send_qun_msg2' headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0)', 'Host':'d1.web2.qq.com',
content = jsonData['result'][0]['value']['content'][1] fromuin = jsonData['result'][0]['value']['from_uin'] #senduin = jsonData['result'][0]['value']['send_uin'] # 发送者的uin value = ['group_message', fromuin, content] # 群 群的uin 文本 群qq #print 'value',value return value except Exception, e: logging.error('Error {0}'.format(e)) if retcode == 116: self.ptwebqq = jsonData.get('p') elif retcode == 121: logging.error(u'程序出现未知错误,可能断网,账号在别处登录(这是一个调试语句,请反馈)') os.remove('image.jpg') sendemail('121错误', u'121错误') exit() elif retcode == 103: logging.error(u'程序出现未知错误, 代码103') sendeoail('103错误', u'103错误') exit() def send_qun(self, group_uin, content): """发送群消息 send_qun(群的uin不是群号码,要说的内容) """ #r:{"to":3497160265,"content":"[\"44\",[\"font\",{\"name\":\"宋体\",\"size\":10,\"style\":[0,0,0],\"color\":\"000000\"}]]","face":0, # "clientid":53999199,"msg_id":80120003,"psessionid":""}\ url = 'http://d1.web2.qq.com/channel/send_qun_msg2' headers = { 'User-Agent':
import BFS_crawl import sendemail def main(): # Default keyword and crawling method keyword = "java" method = "dfs" information = "" if len(sys.argv) == 3: keyword = sys.argv[1] method = sys.argv[2] if method == "dfs": DFS_crawl.dfs_search(keyword) else: BFS_crawl.bfs_search(keyword) if __name__ == '__main__': print "Do you want the routine send email tell you the routine is over?" print "Please input yes or no" issend = raw_input() if issend == 'yes': print 'Please input your gamil address:' username = raw_input() print 'Please input your password' psw = raw_input() main() if issend == 'yes': sendemail.sendemail(username, psw)
import sendemail import relay import gps import alcohol A = 3.4 #currently pre defined , we'll put the gps function for repository B = 5.7 #currently pre defined , we'll put the gps function for repository i = 0 while True: val = alcohol.alcoholval() i = 0 if val == 1: i = i + 1 if i <= 0: sendemail.sendemail(A, B) relay.fuel_stop() else: relay.fuel_flow()
def send_mail(mailConn): from sendemail import main as sendemail sendemail(**mailConn)
posted_videos = open('videos.json','r+') #Read the current JSON formatted list of videos processed video_arr = json.loads(posted_videos.read()) #Read into array response = urllib.request.urlopen(call_url); #Call the API URL to get the 20 last videos data = json.loads(response.readall().decode('utf-8')) #Read the result into a JSON array for item in data['items']: #For each Item in the array video = item['id'] #Grab the current video if 'videoId' in video: #If the video has an ID vid_id = video['videoId'] #Grab the video ID if vid_id not in video_arr: #If the videoID isn't in the JSON file of videos processed video_arr.append(vid_id) #Add this videoID to the processed array video_url = 'http://www.youtube.com/watch?v='+vid_id #Set the video URL title = item['snippet']['title'] #Grab the video title r.submit(subreddit,title,url=video_url) #Submit the video to reddit newvideo = 'new video ' + title # New video string sendemail.sendemail("LPBot9000 new Video",newvideo +' '+ video_url) #Send email to address print (newvideo) #Print the new video to console clear_vid = open('videos.json','w') #Re-open the posted videos file in Write mode clear_vid.close() #Close again to clear the file jdata = json.dumps(video_arr, indent=4, skipkeys=False, sort_keys=False) #Dump the json array posted_videos.seek(0) #Seek to the beginning of the posted_videos file posted_videos.write(jdata) #Write the json data posted_videos.close() print ('LPBot9000 finished at: ' + time.strftime("%b %d %Y %H:%M:%S",time.localtime())) #Print finished to console except Exception as e: #If error errortext = "Error running LPBot9000 \n{0}".format(e) #Format the error text sendemail.sendemail("LPBot9000 Error", errortext) #Email the error print (errortext) #Print the error text pass time.sleep(120) #Wait for 2 minutes
def keymath(): # keylist = ["建筑", "劳务", "建筑劳务", "建筑工程", "消防工程", "监理", "工程建设", "工程建筑", '工程','消防安全工程'] keylist = ["消防工程"] keyword_list = [] citylist = [] with open("gongsi2.txt", "r") as f: for line in f: citylist.append(line[0:-1]) for key in keylist: for line in citylist: keyword_list.append(line + key) return keyword_list if __name__ == '__main__': # time.sleep(20000) # exit() try: run(118, "乌鲁木齐市消防工程") except IndexError as e: print(str(e)) sendemail.sendemail("*****@*****.**", "程序停止啦", "错误信息是:" + str(e)) exit() except Exception as f: print(str(f)) # print(parsed("岳阳市建筑劳务",1))
def email(msg): sendemail('*****@*****.**','*****@*****.**','TRobot Error',msg)
#for k, v in records.items(): # rpt_less_3s.write(str(v)) # rpt_less_3s.write(',') rpt_less_3s.write('\n') records = { 'Time': '', 'ReqUID': '', 'CorpNum': '', 'UserID': '', 'RTAction': '', 'TimeCost': '' } else: print('ignor line', (str(line)).strip()) f.close() rpt_more_3s.close() rpt_less_3s.close() os.remove(out_fullname) #shutil.rmtree(path, ignore_errors, onerror) #email the reports sendemail.sendemail( ["*****@*****.**"], "DOL RT Log Stat - " + out_timestamp, "Production DOL real-time performance statistic reports attached.", [more3s])
import sendemail as se home_id = "123" # get home id from deployment.db # ================= for email sending ====(begin)==================================================================================# subject = "CRITICAL: Home [" + home_id + "] Base station" # CRITICAL, ALERT, NOTIFICATION source = "Laptop process" error = "[ProcessCheckThread]" message = "XXX Process stops running" # describe the error explanation = "The audio program is not working/processing the data. UVA needs to log on the laptop and identify the error. " # copy error message & potential solution if there is one contact = "UVa Team" semail = se.sendemail() msg = semail.emailMsg(subject, home_id, source, error, message, explanation, contact) semail.send(msg) # print msg # self.server.sendmail(self.fromaddr, self.toaddrs, msg) # ================= for email sending ====(end)==================================================================================#
elems = webPage.select(htmlTags) # Check number of prices found (should only be 1, but just in case) if len(elems) > 1: logging.info('%i prices were found' % len(elems)) elif len(elems) == 1: logging.info('1 price was found') elif len(elems) < 1: logging.info('No prices were found') # Log prices for i in elems: logging.info('The current price is %s' % i.getText()) # Check if price has changed if len(elems) == 1: try: cleanPrice = re.sub('[^0-9,.]+', '', elems[0].getText().replace(',', '.')) currentPrice = float(cleanPrice) if currentPrice < standardPrice: logging.info('ALERT: Price has lowered!') sendemail(currentPrice) elif currentPrice > standardPrice: logging.info('ALERT: Price has increased!?') logging.info('Not sending email.') else: logging.info('No price change detected.') logging.info('Not sending email.') except Exception as exc: logging.error('There was an error: %s' % (exc))