def reset_password(): username = input("(Reset Password)Enter your username: "******"Your new password is :" + password_generator() email_subject = "Reset password" SendEmail.send_email(email_to, email_text, email_subject)
def send_invitations(self): """ Assigns secret santa to every participant and sends an email invite to respective members informing the same. """ event_date_str = self.txt_date.get() if event_date_str: try: event_date = datetime.strptime(event_date_str, '%m/%d/%Y') except ValueError: messagebox.showerror("Error", "Invalid date format.") return event_date_str = datetime.strftime(event_date, "%A - %d %b, %Y") else: event_date_str = '-' budget = self.txt_budget.get() try: budget = int(budget) except ValueError: messagebox.showerror("Error", "Invalid budget value.") return email_dict = {} participants = [] for i in range(NO_OF_ENTITIES): email = self.txt_email[i].get() name = self.txt_name[i].get() if name and email: email_dict[email] = name participants.append(email) else: if email and not name: messagebox.showerror("Error", f"Name not found for entity no. {i+1}.") return if name and not email: messagebox.showerror("Error", f"Email mandatory for entity no. {i+1}.") return if (len(participants)) < 2: messagebox.showerror("Error", "Insufficient participants.") return random.shuffle(participants) email_formatter = EmailFormatter(event_date_str, budget) for i, _ in enumerate(participants): giver = participants[i] receiver = participants[(i + 1) % (len(participants))] send_email = SendEmail(['smtp.gmail.com', 587, \ '*****@*****.**', 'xxxxxxxxx'], True) send_email.send(from_name="Secret Santa Generator", to_address=[giver], \ subject=email_formatter.subject(email_dict[giver]), \ body=email_formatter.body(email_dict[giver], \ email_dict[receiver])) messagebox.showinfo("Success", "Invitations sent.")
def sendmessage(self): print "start send ..." self.check_items() print "check finished" data = self.update_config() if self.update_config() else self.config_data data['date'] = self.report_date.get() data['today_data'] = self.today_task.get(1.0, END) data['unfinished_data'] = self.unfinished_task.get(1.0, END) data['tomorrow_data'] = self.tomorrow_task.get(1.0, END) data['think_data'] = self.think_task.get(1.0, END) daily_docx = built_docx(data) if daily_docx: data["file_path"] = daily_docx se = SendEmail(data) se_status = se.send_email() if se_status: tkMessageBox.showinfo(u"邮件发送成功",daily_docx) # self.clear() else: tkMessageBox.showinfo(u"发送失败,请重试") # self.clear() else: tkMessageBox.showinfo(u"保存失败,请检查。")
def compare_send_email(self, item_id, item_price_inner, item_name_inner): cursor = conn.cursor() sql = 'select user_price from monitor where item_id = %s' % item_id print '查询语句为:', sql cursor.execute(sql) user_price = cursor.fetchone( ) # user_price: tuple user_price[0]: decimal item_price: unicode if float( user_price[0]) >= float(item_price_inner): # 转为float才可以对比,可以改进 sql = 'update monitor set status = 0 where item_id = %s' % item_id cursor.execute(sql) conn.commit() sql = 'select user_email from user where user_id = ( select user_id from monitor where item_id = %s )' % item_id cursor.execute(sql) user_email = cursor.fetchone() user_email = str(user_email[0]) # 改进 email_text = '您监控的商品:' + str(item_name_inner) + ',现在价格为:' + str( item_price_inner) + ',您设定的价格为:' + str( user_price[0]) + ' 赶紧抢购吧!' email_zhuti = '您监控的商品降价了!' sendemail = SendEmail(email_text, 'admin', 'user', email_zhuti, user_email) sendemail.send() print '该商品降价,已发送邮件提醒用户' cursor.close()
def __init__(self, url, cookies2=None, proxies=None, cookies=None): self.url = url self.proxies = proxies self.email = SendEmail() # cookies = cookies2 if cookies2 else self._get_cookies() self.session = requests.Session() self.session.cookies = cookiejar_from_dict(cookies) # session设置cookie headers = { 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Host': 'antirobot.tianyancha.com', 'Cookies': cookies, 'Referer': 'https://antirobot.tianyancha.com/captcha/verify?return_url={}&rnd=' .format(self.url), 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36', 'X-CSRFToken': 'null', 'X-Requested-With': 'XMLHttpRequest', }
def __init__(self, conf_file): self.pidfile = "/tmp/hermes.pid" self.conf_file = conf_file self.conf_data = self.__read_conf() # Initiate objects self.file_system = FileSystem(self.conf_data['archive_path']) self.mail = SendEmail(self.conf_data['mail'])
def email_alarm(participants, test): plist = [] for p in participants: if p['email_address'] != '': plist.append(p['email_address']) if plist: logstr = "Send email to: %s" % ", ".join(plist) log.info(logstr) # Now send all email notifications send_email = SendEmail(*db.email_settings()) for email_addr in plist: send_email.deliver('*****@*****.**', email_addr, *db.email_notification(test))
def compare_send_email(self, user_id_inner, item_id_inner, item_price_inner, item_name_inner): cursor = self.conn.cursor() try: sql = 'select user_price from monitor where item_id = %s and user_id = %s' % (item_id_inner, user_id_inner) # print 'SQL query: ', sql cursor.execute(sql) user_price = cursor.fetchone() # user_price: tuple, user_price[0]: decimal, item_price: unicode except mysql.connector.errors.InternalError: note = '拥有重复商品,每个商品只能有一个监控,否则会导致监控失败。' sql = 'update monitor set note = \'%s\' where item_id = %s and user_id = %s' % (note, item_id_inner, user_id_inner) print 'Have same item id in one user, skip this round.' cursor.execute(sql) self.conn.commit() cursor.close() return if float(item_price_inner) == -1.00: # 抓取到-1不发邮件,状态依然为1 note = '商品已经下架或者ID不正确。' sql = 'update monitor set note = \'%s\' where item_id = %s and user_id = %s' % (note, item_id_inner, user_id_inner) print 'Wrong item price: -1, skip this round.' cursor.execute(sql) self.conn.commit() cursor.close() return if float(user_price[0]) >= float(item_price_inner): # 转为float才可以对比,可以改进 # try: sql = 'update monitor set status = 0 where item_id = %s and user_id = %s' % (item_id_inner, user_id_inner) cursor.execute(sql) self.conn.commit() sql = 'select user_email from user where user_id = %s' % user_id_inner cursor.execute(sql) user_email = cursor.fetchone() user_email = str(user_email[0]) # linux可用,win会报下面的错误 # item_url = 'https://item.jd.com/' + item_id_inner + '.html' # 邮件网址,怀疑是垃圾邮件原因 email_text = '您监控的商品:' + item_name_inner + ',' + ',现在价格为:' + item_price_inner + ',您设定的价格为:' + str(user_price[0]) + ' 赶紧抢购吧!'.encode('utf-8') email_text = email_text email_zhuti = '您监控的商品降价了!' sendemail = SendEmail(email_text, 'admin', 'user', email_zhuti, user_email) sendemail.send() print '该商品降价,已发送邮件提醒用户' ''' except UnicodeEncodeError as e: sql = 'update monitor set status = 1 where item_id = %s and user_id = %s' % (item_id_inner, user_id_inner) cursor.execute(sql) self.conn.commit() print '发送邮件过程中发生错误,等待下轮重试,正在监控状态继续', e except UnicodeDecodeError as e: sql = 'update monitor set status = 1 where item_id = %s and user_id = %s' % (item_id_inner, user_id_inner) cursor.execute(sql) self.conn.commit() print '发送邮件过程中发生错误,等待下轮重试,正在监控状态继续', e ''' cursor.close()
def send_mail(): while RedisA.exists_key(UserEmail): user_email = RedisA.rc.lpop(UserEmail) mail = SendEmail() prefix = 'EMA' title = '亚马逊自助采集服务' # context = '您的采集任务已完成,请登录网页( https://data.banggood.cn/bgbdp/index#/dataApplication/ponelThree )查看采集结果。' # msg = MIMEText(context, 'plain', 'utf-8') with open('email.html', encoding='utf-8') as f: context = f.read() msg = MIMEText(context, 'html', 'utf-8') mail.send_message(prefix, user_email, title, msg) print('wait 30 s') time.sleep(30)
def get(self): logging.info("SummaryTask starting...") # init class and variables bucket_name = os.environ.get( 'BUCKET_NAME', app_identity.get_default_gcs_bucket_name()) bucket = '/' + bucket_name trendManager = TrendManager() dataModelConverter = DataModelConverter() csvUtils = CsvUtils() cloudStorageUtils = CloudStorageUtils() previous_day_timestamp = int(time.time()) - Globals._1_DAY q_futures = [] for region in self.getRegions(): try: date = TimezoneAwareDate(region, self.request.get('date')) trendsJson = self.getTrends(region, trendManager) self.saveToCloudStorage(dataModelConverter, csvUtils, cloudStorageUtils, trendsJson, region, bucket, date) self.saveToDatastore(q_futures, trendsJson, region, date) self.deleteFromDatastore(q_futures, region, previous_day_timestamp) except Exception, e: traceback.print_exc() Error(msg=str(e), timestamp=int(time.time())).put() SendEmail().send('Error on SummaryTask', str(e)) self.retry()
def flush_msg(): global queue messages = queue queue = [] for msg in messages: myLogger.log(msg) SendEmail(msg, msg)
def sendEmail(): start = int(time.time()) path = r'' receiver1 = ['xxxxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxx'] c = Crawler(path) count = c.doJob() send = SendEmail() send.getInstanse(receiver1, count) i = int(time.time()) - start interval = 86400 - i timer = threading.Timer(interval, sendEmail) timer.start()
def readDateInfo(self, retry=True): try: result = self.rpc.get_result() if result.status_code == 200: data = result.content jsonData = json.loads(data) return jsonData['formatted'].split()[0] else: if retry: time.sleep(1) return self.readDateInfo(False) else: SendEmail().send('Error on TimezoneAwareDate', 'Timezonedb api request error.') except Exception, e: traceback.print_exc() Error(msg=str(e), timestamp=int(time.time())).put() SendEmail().send('Error on TimezoneAwareDate', str(e))
def get(self): send_to = self.get_argument("to", "") subject = self.get_argument("subject", "") context = self.get_argument("message", "") html = self.get_argument("html", "") if send_to.find(','): send_to_list = send_to.split(',') else: send_to_list = [send_to] subject = urllib.unquote(subject) html = urllib.unquote(html) if not html: s = SendEmail(send_to_list, subject, context) if s.send_mail(): self.write("Succeed") else: self.write("Failed") else: if '\n' in html: html = html.replace('\n', '<br>') s = SendEmail(send_to_list, subject, html) if s.send_mail_html(): self.write("Succeed") else: self.write("Failed")
def notif(self, notificon): global _notification_header global _notification_description # Get notification data from HTTP header try: new_notification_header = base64.urlsafe_b64decode(cherrypy.request.headers['NOTIFHEADER']) new_notification_description = base64.urlsafe_b64decode(cherrypy.request.headers['NOTIFDESCRIPTION']) except: # Maintain compatibility with old application new_notification_header = cherrypy.request.headers['NOTIFHEADER'].replace('\x00', '').decode('iso-8859-1', 'replace').encode('utf-8') new_notification_description = cherrypy.request.headers['NOTIFDESCRIPTION'].replace('\x00', '').decode('iso-8859-1', 'replace').encode('utf-8') # Ensure the notification is not a duplicate if (_notification_header != new_notification_header) \ or (_notification_description != new_notification_description): _notification_header = new_notification_header _notification_description = new_notification_description new_notification_description = new_notification_description[:-14] #remove (via twitter) ts = "https://twitter.com/search?q=" tweet = self.clean_tweet(new_notification_description) twitterSearch = ts + urllib.quote(tweet) sixWords = self.get_first_n_words(7,tweet) twitterSearchTwo = ts + urllib.quote(sixWords) bonus = self.add_description(new_notification_header, new_notification_description) now = datetime.datetime.now() if (not self.filter_tweet(tweet)): SendEmail.send(new_notification_header + " - " + new_notification_description, new_notification_description + "\n\n" + twitterSearch + "\n\n" + twitterSearchTwo + "\n\n" + bonus) logmessage = (now.strftime("%Y-%m-%d %H:%M") + " " + new_notification_header + " - " + new_notification_description) print (logmessage[:98].replace('\n', ' ')) return "true"
def config_log(directory, log_name, max_files_uncompressed=1, max_level="IMPORTANT", compress=True, develop=False, send_email=False, to_emails=None, from_email=None, pwd=None, send_sms=False, to_phones=None, auth_id=None, auth_token=None): """ Configure log using a default pattern and create a new level (important). Args: directory: folder to save logs; log_name: first part of the log name; max_files_uncompressed: max number of remaining not compressed files; max_level: max level of log; compress: indicates if compress the logs or no; develop: set output from logging.important to standard ouput (normal print); send_email: boolean to activate or not alert by Email on CRITICAL, ERROR or NOTIFY leve.; to_emails (needed if send_email is True): list of emails to receive alert; from_email (needed if send_email is True): email used to send email alert; pwd (needed if send_email is True): from_email password; send_sms: boolean to receive or not alert by SMS on CRITICAL, ERROR or NOTIFY level; to_phones (needed if send_sms is True): list of phones to receive alert; auth_id (needed if send_sms is True): auth id from Plivo; auth_token (needed if send_sms is True): auth token from Plivo; """ end_with = '.log' directory = _to_path(directory) if not path.exists(directory): makedirs(directory) email_handler = None sms_handler = None if send_email: email_handler = SendEmail(log_name, to_emails, from_email, pwd) if send_sms: sms_handler = SendSMS(log_name, to_phones, auth_id, auth_token) _set_logger(directory, log_name, _get_log_level(max_level), develop, email_handler, sms_handler) if compress and not develop: _clean_up_logs(directory, log_name, end_with, max_files_uncompressed)
def notify(self, subject, body, email_to): # initialize send mail class send_email = SendEmail() # print(body) send mail to active users send_email.send(email_to, subject, body) send_email.quit()
def contact(): form = ContactForm() if request.method == 'POST': if form.validate() == False: flash('All fields are required.') return render_template('contact_form.html', form=form) else: post =Contact(name=request.form['name'],email=request.form['email'],phone_number=request.form['phone_number'],message=request.form['message']) db.session.add(post) db.session.commit() name =request.form['name'] sender_email = request.form['email'] to_email = '*****@*****.**' message = request.form['message'] phone = request.form['phone_number'] SendEmail().send_email_from_website(name,sender_email, to_email, message,phone) # return render_template('success.html') return redirect(url_for('response_contact')) elif request.method == 'GET': return render_template('contact_form.html', form=form)
def get(self): logging.info("GetTrendsTask starting...") try: # create twitter client client = TwitterApi( consumer_key=Crenditals.CONSUMER_KEY, consumer_secret=Crenditals.CONSUMER_SECRET, access_token_key=Crenditals.CLIENT_TOKEN, access_token_secret=Crenditals.CLIENT_SECRET) q_futures = [] for region in Globals.REGIONS: # request trends from twitter response = client.getTrendsByWoeid(woeid=region) # get current timestamp in seconds timestamp = int(time.time()) # put trends to db entityList = [] for trend in response: entityList.append( TrendWindow( name=trend['name'], woeid=region, timestamp=timestamp, time=10, volume=trend['tweet_volume'])) q_futures.extend(ndb.put_multi_async(entityList)) self.updateCacheValues(region, entityList) # wait all async put operations to finish. ndb.Future.wait_all(q_futures) except ValueError as v_e: logging.error(v_e) # self.retry() except Exception, e: traceback.print_exc() Error(msg=str(e), timestamp=int(time.time())).put() SendEmail().send('Error on GetTrendsTask', str(e))
# -*- coding: utf-8 -*- from send_email import SendEmail mailto_list = ['*****@*****.**'] subject = 'Time to book dinner !!!!!!!' msg = 'Time to book dinner !!!!!!!' s = SendEmail(mailto_list, subject, msg) if s.send_mail(): print("发送成功") else: print("发送失败")
from threading import Thread import network_test_class as ntc from send_email import SendEmail from getpass import getpass if __name__ == '__main__': # Define all parameters in order to send frequent email-reports email_report = SendEmail() email_report.sender_from_email = input("Type email address for login:"******"Type email address for receiving the report:") email_report.password = getpass( "Type your password for login to email account and hit enter:") # Start thread which does the actual network analysis Thread(target=ntc.InteractivePlots()).start() # Start thread which sends frequent email reports Thread(target=email_report.send_weekly_report())
import time from store import AmazonStorePro from settings import MYSQL_CONFIG_SERVER from send_email import SendEmail import datetime sql_asin = "update crawler_amazon_track_task set wtc_crawl_time=%s where wtc_status=1" def update_time(ut): store = AmazonStorePro(**MYSQL_CONFIG_SERVER) # 服务器本地切换 store.execute_sql(sql_asin, ut) store.close() if __name__ == '__main__': crawl_time = '23:50:55' crawl_date_time = '{} {}'.format(time.strftime("%Y-%m-%d"), crawl_time) crawl_date = datetime.datetime.strptime(crawl_date_time, "%Y-%m-%d %H:%M:%S") set_crawl_date = crawl_date - datetime.timedelta(days=1) print(set_crawl_date) update_time(set_crawl_date) send_email = SendEmail() context = '采集任务时间设置为: {}'.format(set_crawl_date) send_email.send_message('设置任务采集时间', '*****@*****.**', '成功设置任务采集时间', context)
txtEmail += Html.br() + Html.hr() except Exception as e: txtEmail += Html.tag('p', 'FALHA AO RECUPERAR A TABELA DE RODIZIOS') print(e) try: saneparNivel = SaneparNivelReservatorioCrawler() niveis = saneparNivel.crawl(True) txtEmail += Html.tag('h2', 'NÍVEL DOS RESERVATÓRIOS') txtEmail += Html.tag('p', saneparNivel.data_atualizacao) txtEmail += Html.table(niveis, { 'border': 1, 'cellpadding': 5, 'cellspacing': 0, }) txtEmail += Html.tag( 'p', '*Sistema de Abastecimento de Água Integrado de Curitiba') except Exception as e: txtEmail += Html.tag( 'p', 'FALHA AO RECUPERAR DADOS DE NIVEIS DOS RESERVATÓRIOS') print(e) dt = datetime.datetime.now().astimezone( timezone('America/Sao_Paulo')).strftime("%d/%m/%Y %H:%M:%S") email = SendEmail() email.send('Rodízio Sanepar ' + dt, txtEmail)
sys.path.append('./function') from HTMLTestRunner import HTMLTestRunner from send_email import SendEmail test_dir = './interface' test_report = './report' discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py') def new_report(testreport): lists = os.listdir(testreport) #查找最新报告 lists.sort(key=lambda fn: os.path.getmtime(testreport + "\\" + fn)) file_new = os.path.join(testreport, lists[-1]) #print(file_new) return file_new if __name__ == "__main__": em = SendEmail() now = time.strftime("%Y-%m-%d %H_%M_%S") filename = './report/' + now + '_result.html' fp = open(filename, 'wb') runner = HTMLTestRunner(stream=fp, title='Test Report', description='Implementation Example with:') runner.run(discover) fp.close() new_report = new_report(test_report) em.sendemail(new_report)
import time import sys from store import AmazonRedis from send_email import SendEmail if __name__ == '__main__': rds = AmazonRedis() mail_today = rds.get_hash_field('amazon:di:cy:mail', 'today') detail_today = rds.get_hash_field('amazon:di:cy:dc01:markdate', 'today') if detail_today: detail_today = detail_today.split()[0] today = time.strftime("%Y-%m-%d") if mail_today == today: print('DI finish') sys.exit() if detail_today == today and not rds.exists_key('amazon:di:cy:repeatasin'): email = SendEmail() context = 'ok' email.send_message('DI', '*****@*****.**', '今日采集完成', context) today_date = time.strftime("%Y-%m-%d") rds.set_hash('amazon:di:cy:mail', {'today': today_date}) else: print('DI no finish')
class Send_Click(object): """ 点触验证码 """ def __init__(self, url, cookies2=None, proxies=None, cookies=None): self.url = url self.proxies = proxies self.email = SendEmail() # cookies = cookies2 if cookies2 else self._get_cookies() self.session = requests.Session() self.session.cookies = cookiejar_from_dict(cookies) # session设置cookie headers = { 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Host': 'antirobot.tianyancha.com', 'Cookies': cookies, 'Referer': 'https://antirobot.tianyancha.com/captcha/verify?return_url={}&rnd=' .format(self.url), 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36', 'X-CSRFToken': 'null', 'X-Requested-With': 'XMLHttpRequest', } # self.session.headers = headers @staticmethod def _get_cookies(): """ 获取cookie 拼接cookie :return: """ cookie = {} with open('cookies.txt', 'r') as f: result = json.load(f) for c in result: name = c.get('name') value = c.get('value') cookie[name] = value return cookie def get_xpath(self, response, xpath, html=None): """ 解析器 :param response: :param xpath: :param html: :return: """ if html is None: html = etree.HTML(response) return html.xpath(xpath) else: return response.xpath(xpath) def download(self, url, params=None, proxies=None): """ 下载器 :param url: :param params: :return: """ return self.session.get(url, params=params) def verify(self, response): """ 验证是不是点触验证码 :param response: :return: """ # response_html = etree.HTML(response.text) # company_id = response_html.xpath('//div[@class="search-result-single "]/@data-id') title = re.search(r'<title>(.*?)</title>', response) return title.group(1) if title else None def slice(self, targetImage, bgImage): """ 拼接图片验证码 :param targetImage: 验证图片 点击顺序字符 :param bgImage: 验证图片 字符 :return: """ # 打开文件二进制流图片bytes数据 img = Image.open(BytesIO(base64.urlsafe_b64decode(targetImage))) img2 = Image.open(BytesIO(base64.urlsafe_b64decode(bgImage))) # new_image 是拼接好的图片 new_image = Image.new('RGB', (320, 130), 'red') new_image.paste(img, (0, 0)) new_image.paste(img2, (0, 30)) # new_image.show() # new_image.save('captcha.jpg') chaojiying = Chaojiying_Client("L54555", "Li891004", '90004') # 用户中心>>软件ID 生成一个替换 96001 # im = open('a.jpg', 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要// bytes_image = BytesIO() new_image.save(bytes_image, format='PNG') new_image = bytes_image.getvalue() dict_data = chaojiying.PostPic( new_image, 9004) # 1902 验证码类型 官方网站>>价格体系 3.4+版 print 后要加() pic_str = dict_data.get('pic_str').split('|') print(pic_str) lis = [] if pic_str[0]: [ lis.append({ 'x': int(data.split(',')[0]), 'y': int(data.split(',')[1]) - 30 }) for data in pic_str ] # ===============模拟打码平台================= # for _ in range(4): # x = int(input('请输入坐标x:')) # if x == 0: # break # y = int(input('请输入坐标y:')) # lis.append({'x': x, 'y': y}) return lis # 返回坐标列表 def verify_image(self): # 获取图片验证码返回的图片 b64串 # dt = str(int(datetime.now().timestamp() * 1000)) url = "http://antirobot.tianyancha.com/captcha/getCaptcha.json?t={}&_={}".format( str(int(datetime.now().timestamp() * 1000)), str(int(datetime.now().timestamp() * 1000) - 100)) result = self.download(url) # 获取数据 data = result.json().get('data') targetImage = data.get('targetImage') # 拿到要顺序点击的字符 bgImage = data.get('bgImage') # 拿到字符图片 captchaId = data.get('id') # 拿到图片id print(result.json()) # 拼接图片 函数里面接入打码平台 lis = self.slice(targetImage, bgImage) # 拼接参数 发送验证请求 params = { 'captchaId': captchaId, # 图片唯一id 'clickLocs': json.dumps(lis), # 图片坐标 't': str(int(datetime.now().timestamp() * 1000)), # 当前时间戳 } print(params, '+' * 10) # 验证成功 # dd = str(int(datetime.now().timestamp() * 1000)) # url = f'https://antirobot.tianyancha.com/captcha/checkCaptcha.json?captchaId={captchaId}&clickLocs={json.dumps(str(lis))}&t={str(int(datetime.now().timestamp() * 1000))}&_={str(int(datetime.now().timestamp() * 1000) - 100)}' resp = self.download( "http://antirobot.tianyancha.com/captcha/checkCaptcha.json", params=params) print(resp.json(), '*' * 10) return resp.json().get('state') def run(self): # 爬接口 如果是正常网页 title不会是 天眼查验证 resp = self.download(self.url) title = self.verify(resp.text) print(title, '++++++++++++++++++++++++++++++') html = etree.HTML(resp.text) user = html.xpath('//span[@class="ni-sp-name"]') print(user) if user: # if user and title != '天眼查校验': return 200 # 继续操作 elif title == '天眼查校验': # 如果是点触验证码 # 调用验证 接打码平台 返回坐标 [{"x":72,"y":66},{"x":97,"y":32}] 坐标类型list 里面每个字符组成一个字典x,y 依次顺序 if self.verify_image() == 'ok': # 可以继续爬这个接口 url response = self.download(self.url) # 验证成功后可以继续操作 html = etree.HTML(response.text) result = html.xpath('//span[@class="ni-sp-name"]') # //span[@class="ni-sp-name"] print(result, '=' * 10) if result: print(response.status_code) return response.status_code else: return 503 else: # 没验证成功 继续验证 # self.run() self.email.run( 'Login verification failed, such as continuous occurrence of the representative Super Eagle is not enough!' ) return 503 else: return 503
class Hermes(): def __init__(self, conf_file): self.pidfile = "/tmp/hermes.pid" self.conf_file = conf_file self.conf_data = self.__read_conf() # Initiate objects self.file_system = FileSystem(self.conf_data['archive_path']) self.mail = SendEmail(self.conf_data['mail']) def __exit__(self): os.unlink(self.pidfile) def __read_conf(self): with open(self.conf_file) as f: yaml_data = yaml.load(f) return yaml_data def __lock_pid(self): self.pid = str(os.getpid()) if os.path.isfile(self.pidfile): Logs.Print("%s already exists, exiting" % self.pidfile) sys.exit() with open(self.pidfile, 'w') as fwrie: fwrie.write(self.pid) def app(self): Logs.Print("Starting Hermes App..") Logs.Print("Paths to monitor:") for monitor_path in self.conf_data['monitor_paths']: Logs.Print("{0}: {1}".format(monitor_path['name'], monitor_path['path'])) Logs.Print("Archive path: {0}".format(self.conf_data['archive_path'])) while 1: try: for monitor_path in self.conf_data['monitor_paths']: # Check if there are any files in these paths files = self.file_system.list_files(monitor_path['path']) # check if the files are ok to be processed for file in files: if os.path.getsize( file) < self.conf_data['file_size_min']: current_time = time.time() creation_time = os.path.getctime(file) if ( current_time - creation_time ) < 60: # older than 1 minutes are ok to be processed Logs.Print( "File: {0} is too small to be processed.". format(file)) files.remove(file) # wait 2 seconds time.sleep(2) if files: time_now = datetime.datetime.utcnow() print("\n\n") Logs.Print( "======================================================" ) Logs.Print( str(time_now) + ": Found alarm on " + monitor_path['name']) # Create google_drive object google_drive = MyGoogleDrive( self.conf_data['gdrive_cred_path']) # Upload images into google drive for file in files: google_drive.push(file, monitor_path['gdrive_folder_id']) self.mail.sendMessage(file, monitor_path['name']) self.file_system.archive_files(files, monitor_path['name']) except Exception as e: Logs.Print("Exception: " + str(e)) def cleanup(self): Logs.Print("Starting Hermes Cleanup..") gdrive_folder_ids = [] retention = self.conf_data['retention'] for folder_id in self.conf_data['monitor_paths']: gdrive_folder_ids.append(folder_id) while 1: try: Logs.Print("Start cleaning process.") self.file_system.cleanup_archive(retention) google_drive = MyGoogleDrive( self.conf_data['gdrive_cred_path']) google_drive.cleanup(retention, gdrive_folder_ids) Logs.Print("Stop cleaning process.") time.sleep(86400) except Exception as e: Logs.Print("Exception: " + str(e))
def log_and_email(msg, title="提醒"): log(msg) SendEmail(title, msg)
from FlexCambio import FlexCambioCrawler from send_email import SendEmail import datetime from pytz import timezone from helpers.Html import Html txtEmail = Html.tag('h2', 'COTAÇÕES DO EURO') try: flexCrawler = FlexCambioCrawler() txtEmail += Html.table(flexCrawler.crawl(True), { 'border': 1, 'cellpadding': 5, 'cellspacing': 0, }) except Exception as e: txtEmail += Html.tag('p', 'FALHA AO RECUPERAR A TABELA DE COTAÇÕES') print(e) dt = datetime.datetime.now().astimezone(timezone('America/Sao_Paulo')).strftime("%d/%m/%Y %H:%M:%S") email = SendEmail() email.send('Cotação Euro '+dt, txtEmail)
from get_message import GetMessage from send_email import SendEmail from database import Database if __name__ == '__main__': # Define variables to connect to MySQL database user = '******' # Set username of MySQL server password = '' # Set password of MySQL server d = Database(user, password) n = int(input("Number of queries")) for query in range(n): email=input("Email address") series = input("TV Series").split(',') message = "\n" #Create an object for Database class #Connect to database and insert the data in the table. d.write(email,series) for i in series: #Create an object for GetMessage class which can determine the next episode date of the TV Series. m = GetMessage(i) #print(a.get_imdb_url()) message+="Tv series name: "+i+"\n" message+="Status: "+m.get_episode_date()+"\n" #print(message) message+="\n" #Send the result to user's email e = SendEmail(email,message) e.send()
import time from hello import Hello from send_email import SendEmail email = SendEmail() def send_email(msg): email.send('hello_goddess', msg, ['*****@*****.**']) def main(): hello = Hello(True, ['葛']) hello.inform(send_email) while True: hello.get_sport_rank() hello.add_friend() hello.get_friend() hello.save_to_mysql() time.sleep(3 * 60) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- from send_email import SendEmail mailto_list = ['*****@*****.**'] subject = 'Time to book dinner !!!!!!!' msg = 'Time to book dinner !!!!!!!' s = SendEmail(mailto_list, subject, msg) if s.send_mail(): print ("发送成功") else: print ("发送失败")
class JiraIssueHandler(): http_headers = None sendEmail = SendEmail() utils = GeneralUtils() def __init__(self): self.http_headers = {**JIRA_AUTH, **JIRA_CONTENT, **JIRA_ACCEPT} def createIssueFields(self, project, issuetype, summary, description, assignee, components=[], versions=[]): if (len(components) == 0): return Fields(project, issuetype, summary, description, assignee) else: return FieldsTestExec(project, issuetype, summary, description, assignee, components, versions) def createIssue(self, project, issuetype, summary, description, assignee, components=[], versions=[]): fields = self.createIssueFields(project, issuetype, summary, description, assignee, components, versions) issueData = IssueData(fields) post_url = JIRA_ISSUE_URL post_data = json.dumps(issueData.__dict__, default = obj_to_dict) print(post_data) response = requests.post(post_url, headers = self.http_headers, data = post_data) print("Status Code:", response.status_code) response_content = response.json() print("{} na criacao da issue: {}".format(self.utils.codeToStr(response.status_code, 201), response_content)) return Response( Response.STATUS_OK if response.status_code == 201 else Response.STATUS_ERROR, response_content['key'] if response.status_code == 201 else str(response.status_code), response_content) def createIssueWithRawData(self, projectKey, issuetypeName, summary, description, assigneeName, component="", version=""): project = Project(projectKey) issuetype = IssueType(issuetypeName) assignee = Assignee(assigneeName) components = list() versions = list() if (component): components.append(Component(component)) if (version): versions.append(Version(version)) return self.createIssue(project, issuetype, summary, description, assignee, components, versions) def createIssueLink(self, issueLinkType, inwardIssue, outwardIssue): issueLink = IssueLink(issueLinkType, inwardIssue, outwardIssue) post_url = JIRA_ISSUELINK_URL post_data = json.dumps(issueLink.__dict__, default = obj_to_dict) print(post_data) response = requests.post(post_url, headers = self.http_headers, data = post_data) print("Status Code:", response.status_code) print("{} na criacao do link {} entre {} e {}".format(self.utils.codeToStr(response.status_code, 201), issueLinkType, inwardIssue, outwardIssue)) def getIssueSummary(self, issueKey): get_url = JIRA_ISSUE_GET_SUMMARY_URL.format(issueKey) response = requests.get(get_url, headers = self.http_headers) print("Status Code:", response.status_code) issueSummary = "" if (response.status_code == 200): response_content = response.json() issueSummary = response_content['fields']['summary'] print("Summary da issue(%s): %s" % (issueKey, issueSummary)) return issueSummary def createIssueLinkWithRawData(self, typeName, inIssueKey, outIssueKey): issueLinkType = IssueLinkType(typeName) inwardIssue = WardIssue(inIssueKey) outwardIssue = WardIssue(outIssueKey) self.createIssueLink(issueLinkType, inwardIssue, outwardIssue) def changeIssueTransition(self, issueKey, transitionId, resolutionName=""): transition = Transition(transitionId) issueTransitionData = IssueTransition(transition) if (resolutionName): resolution = Resolution(resolutionName) fields = FieldResolution(resolution) issueTransitionData = IssueTransitionResolution(transition, fields) post_url = JIRA_ISSUE_TRANSITION_URL.format(issueKey) post_data = json.dumps(issueTransitionData.__dict__, default = obj_to_dict) print(post_data) response = requests.post(post_url, headers = self.http_headers, data = post_data) print("Status Code:", response.status_code) print("{} na alteracao do status da issue {} para {}".format(self.utils.codeToStr(response.status_code, 204), issueKey, transitionId)) def createIssueTestExec(self, projectKey, summaryPrefix, assigneeName): dateTime = datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S') summary ="{} - {}".format(summaryPrefix, dateTime) testExecIssue = self.createIssueWithRawData(projectKey, ISSUE_TESTEXEC_NAME, summary, summary, assigneeName, COMPONENT_APP_NAME, AFFECTED_VERSION_NAME) return testExecIssue.key def addTestToTestExec(self, testExecIssueKey, tests): testExecAddTest = TestExecAddTest(tests) post_url = JIRA_TESTEXEC_ADD_TEST_URL.format(testExecIssueKey) post_data = json.dumps(testExecAddTest.__dict__, default = obj_to_dict) print(post_data) response = requests.post(post_url, headers = self.http_headers, data = post_data) print("Status Code:", response.status_code) print("{} na adição dos Tests {} para o Test Exec {}".format(self.utils.codeToStr(response.status_code,200), str(tests), testExecIssueKey)) def initIssueTestExec(self, issueTestExecKey, casoDeTesteKeys): self.addTestToTestExec(issueTestExecKey, casoDeTesteKeys) self.changeIssueTransition(issueTestExecKey, TESTEXEC_STATUS_IN_PROGRESS) for key in casoDeTesteKeys: self.changeIssueTransition(key, TEST_STATUS_RETESTING_ID) testRunId = self.getTestRunId(issueTestExecKey, key) self.changeIssueTestRunStatus(testRunId, TESTRUN_STATUS_TODO) def finishIssueTestExec(self, issueTestExecKey, resolution=""): self.changeIssueTransition(issueTestExecKey, TESTEXEC_STATUS_DONE, resolution) def initIssueTestRun(self, issueTestExecKey, issueTestKey): self.changeIssueTransition(issueTestKey, TEST_STATUS_IN_PROGRESS_ID) testRunId = self.getTestRunId(issueTestExecKey, issueTestKey) self.changeIssueTestRunStatus(testRunId, TESTRUN_STATUS_EXECUTING) def addDefectToTestRun(self, testRunIssueId, issueBugKey): issueBugKeyArr = [issueBugKey] post_url = JIRA_TESTRUN_ADD_DEFECT_URL.format(testRunIssueId) post_data = json.dumps(issueBugKeyArr) print(post_data) response = requests.post(post_url, headers = self.http_headers, data = post_data) print("Status Code:", response.status_code) print("{} na adição do bug {} para o test run {}".format(self.utils.codeToStr(response.status_code, 200), issueBugKey, testRunIssueId)) def addAttachmentToTestRun(self, testRunIssueId, data, filename, contentType="image/png"): testRunAttachment = TestRunAttachment(filename, contentType, data) post_url = JIRA_TESTRUN_ADD_ATTACHMENT_URL.format(testRunIssueId) post_data = json.dumps(testRunAttachment.__dict__, default = obj_to_dict) print(post_data) response = requests.post(post_url, headers = self.http_headers, data = post_data) print("Status Code:", response.status_code) print("{} na adição da evidencia {} para o test run {}".format(self.utils.codeToStr(response.status_code, 200), filename, testRunIssueId)) def addAttachmentToTestExecAndTest(self, issueTestExecKey, issueTestKey, data, filename, contentType="image/png"): testRunId = self.getTestRunId(issueTestExecKey, issueTestKey) self.addAttachmentToTestRun(testRunId, data, filename, contentType) def getTestRunId(self, testExecIssueKey, testIssueKey): get_url = JIRA_TESTRUN_GET_ID_URL.format(testExecIssueKey, testIssueKey) response = requests.get(get_url, headers = self.http_headers) print("Status Code:", response.status_code) testRunId = 0 if (response.status_code == 200): response_content = response.json() testRunId = response_content['id'] print("Id da TestExecutionKey(%s) e TestIssueKey(%s): %s" % (testExecIssueKey, testIssueKey, str(testRunId))) return testRunId def changeIssueTestRunStatus(self, testRunIssueId, status): put_url = JIRA_TESTRUN_CHANGE_STATUS_URL.format(testRunIssueId, status) put_data = {} response = requests.put(put_url, headers = self.http_headers, data = put_data) print("Status Code:", response.status_code) print("{} na alteracao do status do Test Run {} para {}".format(self.utils.codeToStr(response.status_code, 200), testRunIssueId, status)) def addIssueWatcher(self, isseueBugKey, watcher): post_url = JIRA_ISSUE_ADD_WATCHER_URL.format(isseueBugKey) post_data = json.dumps(watcher) print(post_data) response = requests.post(post_url, headers = self.http_headers, data = post_data) print("Status Code:", response.status_code) print("{} na adição do usuario {} como wathcer para o bug {}".format(self.utils.codeToStr(response.status_code, 200), watcher, isseueBugKey)) def createBugAndAddToTestRun(self, projectKey, issueTestExecKey, issueTestKey, bugSummary, bugDescription, bugAssignee): response = self.createIssueWithRawData(projectKey, ISSUE_BUG_NAME, bugSummary, bugDescription, bugAssignee) if (response.status == Response.STATUS_OK): #jiraIssueHandler.createIssueLinkWithRawData(ISSUELINKTYPE_BLOCKS_BY, issueTestKey, response.key) #self.addIssueWatcher(response.key, bugAssignee) testRunId = self.getTestRunId(issueTestExecKey, issueTestKey) self.addDefectToTestRun(testRunId, response.key) return response def finishIssueTestRun(self, issueTestExecKey, issueTestKey, testRunStatus, testResolution=""): self.changeIssueTransition(issueTestKey, TEST_STATUS_DONE_ID, testResolution) testRunId = self.getTestRunId(issueTestExecKey, issueTestKey) self.changeIssueTestRunStatus(testRunId, testRunStatus) #Simula envio de email de notificação do bug pelo Jira #TODO: configurar JIRA para enviar assim que o Bug for criado def sendBugEmailNotification(self, testExecIssueKey, testIssueKey, bugIssueKey): testExecInfo = JiraIssueInfo(testExecIssueKey, self.getIssueSummary(ISSUE_TESTEXEC_KEY)) testIssueInfo = JiraIssueInfo(testIssueKey, self.getIssueSummary(testIssueKey)) bugIssueInfo = JiraIssueInfo(bugIssueKey, self.getIssueSummary(bugIssueKey)) subject = self.utils.getEmailSubject(testExecInfo, testIssueInfo, bugIssueInfo) messageText = self.utils.getTextlEmailMessage(testExecInfo, testIssueInfo, bugIssueInfo) messageHtml = self.utils.getHtmlEmailMessage(testExecInfo, testIssueInfo, bugIssueInfo) self.sendEmail.send(EMAIL_TO_NOTIFICATION, EMAIL_CC_NOTIFICATION, subject, messageText, messageHtml)