def confirmation(): if request.method == 'POST': # token = request.headers['Authorization'] # try: # data = jwt.decode(token, # key=current_app.config['SECRET_KEY'], # algorithm='HS256') # email = data.get('email') # except Exception as e: # return jsonify({'code': -1, 'message': 'token超时'}) email = request.get_json().get('email') user = User.query.filter_by(email=email).first() if user is None: return jsonify({'code': 0, 'message': '用户不存在'}) if user.confirmed is False: token = user.generate_confirmation_token() send_email(user.email, '确认账户', 'auth/email/confirm', user=user, email=user.email, token=token) return jsonify({'code': 1, 'message': '验证邮件已发送'}) else: return jsonify({'code': 2, 'message': '用户已完成验证'})
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User( first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data, password=form.password.data ) db.session.add(user) try: commit(db.session) except: send_error_email() flash('There has been an error') return render_template('auth/register.html', form=form) flash('You are now registered.') token = user.generate_confirmation_token() context = { 'first_name': user.first_name, 'last_name': user.last_name, 'token': token } print(url_for('auth.confirm', token=token, _external=True)) send_email( recipients=[user.email], subject='Confirm your email address', template_name='confirmation', context=context ) flash('We sent you a verification email.') login_user(user) return redirect(url_for('profile.index')) return render_template('auth/register.html', form=form)
def user_reset_password(): """ Starts the reset password process by sending a reset mail to the alternative_mail. You don't need to be logged in to do this. """ alternative_mail = request.json.get('alternative_mail') try: user = api.get_user_by_alternative_mail(alternative_mail) if user == None: # You can't let people guess mails! return "ok" password_reset_token = token_handler.create_password_reset_jwt_token( user.uid[0]).decode("utf-8") mail.send_email( alternative_mail, "Passwort-Reset", "emails/password_reset_email", { "name": user.uid[0], "link": join(config.FRONTEND_URL, "confirm/password?key=" + password_reset_token), }) return "ok" except LdapApiException as e: # You can't let people guess mails! return "ok"
def signup(): form = RegisterForm() if request.method == 'POST': if form.validate_on_submit(): # Ejercicio - juntar la dos partes!!! Coger del formulario y meter en base de datos! try: password_hashed = generate_password_hash(form.password.data, method="sha256") newuser = User(email=form.email.data, username=form.username.data, userhash=str(random.getrandbits(128)), password=password_hashed) db.session.add(newuser) db.session.commit() send_email( newuser.email, 'Please, confirm email / Por favor, confirmar correo.', 'mail/new_user', user=newuser, url=request.host, newpassword=password_hashed) flash( "Great, your user was created successfully please visit your email {} to confirm your email / Muy bien, ahora visite su correo electrónico {} para confirmar el correo." .format(newuser.email, newuser.email)) return redirect(url_for('login')) except: db.session.rollback() flash("Error creating user!") return render_template('signup.html', module="signup", form=form)
def register_user(): if mail_validation(user.email): pass else: quit() insert_user_into_table() token = auth.generate_token(user.password, user.email) # Send mail with veryficaton token (link from front-end) link = '\nhttps://pythonhosted.org/itsdangerous/#itsdangerous.TimestampSigner' body, subject = mail.template_veryfication(token, link) mail.send_email(user.email, body, subject) cursor.execute('''UPDATE users SET confirmation_sent = ? where email = ?''', (datetime.now(), user.email)) db.commit() # Artificial waiting for confirmation------- time.sleep(2) #------------------------------- (confirmed, token_email) = auth.confirm_token(token, expiration, user.password) if confirmed: user_confirmed(token_email) print("User registered") get_data_from_REGON(user.nip) else: print('User not registered')
def notify(event_id): event = storage.get_event(event_id) event_view = storage.load_event_view(event_id) attendees, extras = event_view num = len(attendees) gifts = [] for i in xrange(num): gifter = attendees[i] giftee = attendees[(i + 1) % num] mail.send_email( gifter['email'], 'You are a secret santa!', render_template( 'secret-santa-notify.eml', gifter=gifter['first'], event_name=event['name'], giftee='%s %s' % (giftee['first'], giftee['last']), ), ) event_view[1]['notified'] = True storage.save_event_view(event_id, event_view)
def query_order_result(self): retry_count = 0 while True: if retry_count > 10: print_s("重试次数达10次,系统退出...") return False print_s("查询订单处理结果...") order_result_url = "https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue" data = { "orderSequence_no": self.order_id, "_json_att": "", "REPEAT_SUBMIT_TOKEN": self.submit_token } response = self.session.post(order_result_url, data).json() print_s(response) if response["data"]["submitStatus"]: print_s("车票预订成功 订单号:{}".format(self.order_id)) if info.mail_notification: mail.send_email( '车票预订成功,订单号: {},车次: {} {}至{} 坐席: {},请尽快登录12306支付^_^'. format(self.order_id, self.select_train[3], self.select_train[6], self.select_train[7], self.select_seat)) return True elif response["status"]: print_s("车票预订失败") print_s(response) return False else: print_s("车票预订查询失败,开始重试...") print_s(response) retry_count += 1 continue
def changepassword(): form = RecoverPasswdForm() if request.method == 'POST': if form.validate_on_submit(): user = User.query.filter( or_(User.email == form.email.data)).first() if not user: flash("Wrong email!") elif user.confirmed: password_hashed = generate_password_hash(form.password.data, method="sha256") send_email( user.email, 'Please, confirm passwd change / Por favor, confirmar el cambio de contraseña.', 'mail/new_password', user=user, url=request.host, newpassword=password_hashed) flash("Email has been send") return redirect(url_for("login")) else: flash( "User not confirmed. Please visit your email to confirm your user." ) return render_template('changepasswd.html', module="login", form=form)
def _send_email(self, data_node_ip, text): try: subject = "[%s] %s" % (data_node_ip, text) body = "[%s] %s" % (data_node_ip, text) send_email(ADMIN_MAIL, subject, body) except Exception, e: raise e
def queue_send_email(recipients, subject, text_content=None, html_content=None, from_email=settings.DEFAULT_FROM_EMAIL, use_base_template=True, category=None, fail_silently=False, language=None, cc=None, bcc=None, attachments=None, headers=None, bypass_hijacking=False, attach_files=None): logger = queue_send_email.get_logger() logger.debug('Sending %s to %s' % (subject, ','.join(recipients), )) send_email(recipients=recipients, subject=subject, text_content=text_content, html_content=html_content, from_email=from_email, use_base_template=use_base_template, category=category, fail_silently=fail_silently, language=language, cc=cc, bcc=bcc, attachments=attachments, headers=headers, bypass_queue=True, bypass_hijacking=bypass_hijacking, attach_files=attach_files) return True
def mark_as_paid(): """Automatically mark every month as paid. Send email with notification.""" current_month_number = datetime.now().month models.FlatPayment.mark_as_paid_or_unpaid(current_month_number) current_month = datetime.now().strftime("%B") send_email( f'{current_month} отмечен как оплаченный.', 'Для отмены <b>Оплачено > выбрать месяц, который не оплачен </b>')
def index(): send_email('Hey there - ' + str(datetime.now()), sender='**************', recipients=['*****@*****.**'], text_body=render_template('email/text_.txt', url='google.com'), html_body=render_template('email/html_.html', url='google.com')) return 'index mail - ' + str(datetime.now())
def sendIpAddresses(self,): mail.send_email(self.ip_addresses) # if __name__ == '__main__': # pi = RaspberryPi() # pi() # print(pi.ip_addresses)
def fetch(credentials): session = requests.Session() baseurl = 'https://oma.muksunkirja.fi/' logger.debug(session.get('{0:s}perusmuxu/login'.format(baseurl))) credentials.update(dict(next='/perusmuxu/', submit='Login')) login = session.post('{0:s}perusmuxu/login/'.format(baseurl), credentials) logger.debug(login) soup = bs4.BeautifulSoup(login.text) # This is a hack, but this way we don't have to parse JavaScript kid_id = int(soup.find('div', attrs={'class': 'caption'}).attrs['id'].rsplit('_', 1)[1]) kid_data = json.loads(session.get('{1}json/kid/{0:d}'.format(kid_id, baseurl)).text) logger.debug(kid_data) dep_id = kid_data['department']['id'] logger.debug(dep_id) # Load the news feed feed_data = json.loads( session.get('{1}json/daycarefeed/{0}/?filter=all&idx=0'.format(dep_id, baseurl)).text) user = '******' # XXX for entry in feed_data['entries']: raw_html_message = entry['message'] sender = entry['user']['name'] # XXX: Process. filename = os.path.join(settings.DATAPATH, '{0}_{1}.json'.format(user, entry['id'])) try: with open(filename): continue # No need to overwrite except (OSError, IOError): with open(filename, 'w') as f: entry_as_json = json.dumps(entry) logger.info("Writing entry: {}".format(entry_as_json)) f.write(entry_as_json) send_mail = True # XXX parsed_message = bs4.BeautifulSoup(raw_html_message).text logger.debug(parsed_message) timestamp = parse(entry['time']) try: subject, message = parsed_message.split('\n', 1) except ValueError: # Just a single line message. message = parsed_message subject = parsed_message[:re.search(r'[.!?]', parsed_message).end()] # Split by punctuation body = '** {} - {} **\n\n{}'.format( user, timestamp.isoformat(), message) if send_mail: rcpt = settings.RECIPIENT send_email(body, rcpt, sender, subject, parse(entry['time']), user) else: logger.info("Not sending e-mail") # XXX: Fetch messages too logger.debug(session.get('{0:s}perusmuxu/logout/'.format(baseurl)))
def main(): """Main function for generating data and sending email.""" today = date.today() week_dates = get_last_week_dates(today) album_dict = generate_album_dictionary(week_dates) album_df = parse_album_dictionary(album_dict) send_email(album_df)
def send_email(to_email, to_name, subject, message, attachements=None): mail.send_email(to_email, to_name, subject, message, app.config['MAILGUN_USER'], app.config['MAILGUN_KEY'], app.config['MAILGUN_DOMAIN'], attachements=attachements)
def main(): print( 'SCHEDULE ALERTER!!\nEnter your email address and the list of tv series.\nWe use imdb to gather data so to get accurate data enter tv deries name in the format NAME (Year of release).' ) usersno = int(input('Enter no of users:-')) # connecting to user database and save each input in the database usercursor, userdb = createuserdbconnection() for i in range(usersno): mail = input('Email address:-') name = input("Enter name of tv series:-") sql = "INSERT INTO userinput (email, tvseries) VALUES (%s, %s)" val = (mail, name) usercursor.execute(sql, val) userdb.commit() # getting the last userno from database and looping over them and sending mail sql = "SELECT * FROM userinput;" usercursor.execute(sql) userresult = usercursor.fetchall() userresult = userresult[-usersno:] for user in userresult: name = user[1].split(',') print('Fetching data from imdb') # multithreading to make process faster with Pool(5) as p: ans = p.map(checkdb, name) print('Preparing a mail') sub = "Schedule of upcoming tv episodes" text = "Here are the details you requested\n\n" html = "Here are the details you requested<br><br>" mycursor, mydb = createscheduledbconnection() msg = MIMEMultipart('alternative') msg['Subject'] = sub msg['From'] = config.EMAIL msg['To'] = user[0] # prepare a bady for mail by iterating over user input for a in ans: if a[1] != '!': sql = "SELECT * FROM tvdata where title = %s;" val = (a[1], ) mycursor.execute(sql, val) myresult = mycursor.fetchall() text = text + "Tv Series Name: {} IMDB Name- {}\nStatus: {} {}\n\n".format( a[0], myresult[0][0], myresult[0][1], myresult[0][2]) html = html + "Tv Series Name: <b>{}</b> <small><i>IMDB Name</i>- {}</small><br>Status: {} {}<br><br>".format( a[0], myresult[0][0], myresult[0][1], myresult[0][2]) else: text = text + "Tv Series Name: {}\nStatus: {} \n\n".format( a[0], 'No such tv series exists') html = html + "Tv Series Name: <b>{}</b><br>Status: {} <br><br>".format( a[0], 'No such tv series exists') part1 = MIMEText(text, 'text') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) send_email(sub, msg, user[0])
def sendmail(email=None): email = email or request.json.get('email') # email = email or request.args.get('email') if email is not None: token = generate_validate_email(email) link = 'http://10.86.166.55:8080/validate/'+token send_email(email, 'jigsaw validate email', '<div><a href="'+link+'">'+link+'</a>链接有效时间为1小时</div>') return jsonify({'Success': 1}), 200 return jsonify({'Success': 0}), 200
def notify_email(message, attachment=None): recipient = conf['mail']['recipient'] client_name = conf['main']['client_name'] send_email( recipient, "Security Alert from %s" % client_name, message, attachment=attachment, )
def send_sub_email(email): data = json.loads(request.data) stu_id = data.get('id', None) room_id = data.get('room', None) if stu_id is None or room_id is None: return jsonify({'code': -1}) pool = Pools(stu_id=stu_id, room_id=room_id, email=email) db.session.add(pool) db.session.commit() send_email(email, u'添加监控成功', SUB_TEMPLATE) return jsonify({'code': 0})
def rpi_ip_addr(): # fetch local IP address hostname = socket.gethostname() ip_addr = socket.gethostbyname(hostname + '.local') with open('creds.json') as f: creds = json.load(f) to = creds['cell_email'] # create and send message msg = mail.create_email('RPi IP Address', ip_addr) mail.send_email(to, msg)
def dummy_mail(): mail.send_email( '*****@*****.**', 'HELLLLOOOO', render_template( 'secret-santa-notify.eml', gifter="Jay", event_name="Bob's Secret Santa", giftee="Eyal", ), ) return 'ok'
def family(name, reciever): score = test.test(name, reciever) if (score >= 6): mail.send_email(name, reciever) print("\nBotman : "+name + ", don't take too much stress. All you need to do is adjust "\ "your priorities. Don't take on unnecessary duties and "\ "responsibilities.\nTake advice from people whose opinion you "\ "trust, and get specific advice when issues arise.\nYou should "\ "use stress management techniques and always hope for the best. "\ "These situations arise in everyone's life and what matters the "\ "most is taking the right decision at such moments.") print(finisher)
def write_data(start, time_difference, number_of_bets): filename = (os.getcwd() + '\\gta_record ' + time.strftime("%Y-%m-%d %H_%M_%S", time.localtime()) + '.txt') outfile = open(filename, 'w') gta_data = ('Time of sequence start: ' + str(start) + '\nTime spent betting: ' + time_difference + '\nNumber of bets: ' + str(number_of_bets)) outfile.write(gta_data) outfile.close() msg = str('\nFile written to disk:\n' + str(filename) + '\nFile contents:\n' + str(gta_data)) mail.send_email(msg)
def qr_scanner(): # email = request.args.get('email') qr_code_scan.scan_code() ingredients = event_generator_calender.generate_ics() mail.send_email() data = { 'message': 'QR Scan successful. We have sent you the reminder and recipes on your email. Please check your inbox.' } json_data = json.dumps(data) return json_data
def changepassword(): form = RecoverPasswordForm() if request.method == 'POST': if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if not user: flash('Email does not exist') else: password_hashed=generate_password_hash(form.password.data,method="sha256") send_email(user.email, 'Please confirm password change/ porfavor confiarmar cambio','mail/new_password', user=user,url=request.host,newpassword=password_hashed) flash('Great, pleas visit your emial and confirm passowrd change') return redirect(url_for('login')) return render_template('changepassword.html',module="login", form=form)
def main(): subject = "%s_基信息" % time.strftime("%Y-%m-%d %H:%M", time.localtime()) content = [] for fund_info in FUND_NICK_LIST: time_str, rate = check_fund(fund_info) line = "%s -- %s : %s" % (fund_info['name'], time_str, rate) content.append(line) content.sort(key=lambda x: abs(float(x.split(":")[-1])), reverse=True) content = "\n".join(content) # print(content) send_email(subject, content)
def check_auto(): """checks available marks base on config""" config = read_config() if not config: sys.exit() siteConnection = login(config[c.FEE_USER], config[c.FEE_PW]) message = '' if siteConnection != False: notes = getNotes(siteConnection) notes = printNotes(notes, consoleprint=False) if os.path.isfile('notes.txt'): with open('notes.txt', 'r') as file: oldnotes = json.load(file) if oldnotes == notes: message = 'pas de nouvelles notes' else: for module in notes: if module in oldnotes: if notes[module] != oldnotes[module]: message = message + 'Dans le module {}\n'.format(module) for unit in notes[module]: if unit in oldnotes[module]: if notes[module][unit] != oldnotes[module][unit]: message = message + '\t dans l\'unité {}\n'.format(unit) if notes[module][unit]['year'] != oldnotes[module][unit]['year']: for item in range(len(notes[module][unit]['year'])): if notes[module][unit]['year'][item] != oldnotes[module][unit]['year'][item]: message = message + '\t\tnouvelle note: {}\n'.format(str(notes[module][unit]['year'][item])) if notes[module][unit]['exam'] != oldnotes[module][unit]['exam']: message = message + '\t\tnouvelle note examen: {}\n'.format(notes[module][unit]['exam']) else: message = message + 'nouvelle unité: {}\n'.format(unit) message = message + 'notes : {}\n'.format(str(notes[module][unit]['year'])) message = message + 'examen : {}\n'.format(str(notes[module][unit]['exam'])) message = message + 'moyenne : {}\n'.format(str(notes[module][unit]['average'])) else: message = 'nouveau module {}\n'.format(module) for unit in notes[module]: message = message + 'nouvelle unité: {}\n'.format(unit) message = message + '\tnotes : {}\n'.format(str(notes[module][unit]['year'])) message = message + '\texamen : {}\n'.format(notes[module][unit]['exam']) message = message + '\tmoyenne : {}\n'.format(notes[module][unit]['average']) if config[c.GMAIL_USE]: send_email(config[c.GMAIL_EMAIL], config[c.GMAIL_PW], config[c.GMAIL_EMAIL], [config[c.GMAIL_EMAIL]], 'nouvelle notes fee', message) else: message = 'pas de fichier pour comparer' with open('notes.txt', 'w') as file: json.dump(notes, file) else: message = 'Connection failed' print(message)
def post(self): try: result = utils.init_response_data() client = tornado.httpclient.AsyncHTTPClient() response = yield tornado.gen.Task( client.fetch, "http://120.26.226.63:20000/works") response_body = json.loads(response.body) data = response_body.get("data", {}) works = data.get("works", []) t_s = open( os.path.dirname(options.root_path) + "/var/mail/工作日报.xls", "r") t_s_data = t_s.read() t_s.close() to_email = ["*****@*****.**"] for work in works: filename = os.path.dirname(options.root_path) + "/var/mail/工作日报%s.xls"%( str(datetime.datetime.now()).\ replace(".","_").replace(":","_").replace(" ","_") ) w_d = open(filename, "w") w_d.write(t_s_data) w_d.close() copy_data = [ (4, 1, work.get("name", "")), (4, 2, work.get("hr_analytic_timesheet_id")[1]), ] curr_time = datetime.datetime.now() title = "东汇集团胜众科技有限公司征信项目组%s%s年%s月%s日工作日报" % ( work.get("user_id")[1], curr_time.year, curr_time.month, curr_time.day) reportlib.copy_xls(filename, title, data=copy_data) attachments = [] attachments.append(dict( filename=u"工作日报.xls", data=filename, )) from_email = "*****@*****.**" send_email(from_email, to_email, "工作日报", '', html='', attachments=attachments) result["data"] = works except Exception, e: result = utils.reset_response_data(0, str(e)) self.write(result) self.finish() return
def resend_confirmation(): context = { 'first_name': current_user.first_name, 'last_name': current_user.last_name, 'token': current_user.generate_confirmation_token() } send_email( recipients=[current_user.email], subject='Confirm your email address', template_name='confirmation', **context ) flash('A new confirmation email has been sent') return redirect(url_for('profile.index'))
def send_mail_coming_soon(): """ Get the results only if a spider has results """ global scrape_complete global scrape_in_progress if scrape_complete: data = coming_soon_data.copy() send_email('Coming Soon', render_mail('coming_soon.html', data=data[0])) scrape_in_progress = False scrape_complete = False return render_template('email.html', command='Coming Soon') return 'Scrape Still Progress'
def func_timer(): url = 'http://192.168.4.35/TaskSet/TaskSet.ashx?action=ExportExcel' response = requests.get(url) time.sleep(5) # html = response.read() excelpath = get_result_excel(r'D:\Razer\outRazer\Files\Excel') num = get_total_issues() if num > 0: mail.send_email(num, excelpath) else: print('NOT FOUND NEW DATA') global timer timer = threading.Timer(3 * 60 * 60, func_timer) timer.start()
def checkMess(self): bot = self.bot xpath = '//*[@id="answer_row_7023060867"]/td[3]/div/span/span' #Checking if the red circle appears try: element = WebDriverWait(bot, 10) element.until(EC.element_to_be_clickable((By.XPATH, xpath))) notify_circle = bot.find_element_by_xpath(xpath) mail.send_email() return notify_circle except: return 'NoSuchElement'
def execute_backup(): # Change the value in brackets to keep more/fewer files. time.time() returns seconds since 1970... # currently set to 2 days ago from when this script starts to run. x_days_ago = time.time() - ( 60 * 60 * 24 * 2 ) os.putenv('PGPASSWORD', PASS) con = psycopg2.connect(database='postgres', user=USER, host=HOST, password=PASS) cur = con.cursor() cur.execute("""SELECT datname from pg_database where datistemplate = false;""") database_list = cur.fetchall() # Delete old backup files first. for database_name in database_list : database_name = database_name[0] if database_name == '': continue glob_list = glob.glob(BACKUP_DIR + database_name + '*' + '.pgdump') for file in glob_list: file_info = os.stat(file) if file_info.st_ctime < x_days_ago: log("Unlink: %s" % file) os.unlink(file) else: log("Keeping : %s" % file) log("Backup files older than %s deleted." % time.strftime('%c', time.gmtime(x_days_ago))) # Now perform the backup. for database_name in database_list: database_name = database_name[0] if database_name == 'postgres': continue log("dump started for %s" % database_name) thetime = str(strftime("%Y-%m-%d-%H-%M")) file_name = database_name + '_' + thetime + ".sql.pgdump" #Run the pg_dump command to the right directory command = dumper % (USER, BACKUP_DIR + file_name, database_name) log(command) subprocess.call(command,shell = True) log("%s dump finished" % database_name) storage.upload_to_s3('secret', 'key', 'danimaribeiro_aws_backup', BACKUP_DIR + file_name) mail.send_email('@gmail.com', 'para', 'Backup completo', 'Alguns backups não puderam ser completados') log("Backup job complete.")
def routine(date): # 如果是节假日或周末,复制前一天的数据 if holiday.is_holiday_or_weekend(args.date): dest_date = datetime.date.today() - datetime.timedelta(days=1) src_date = dest_date - datetime.timedelta(days=1) db.copy(src_date, dest_date) sys.exit(0) # 获取当日的基金情况 today = fetchall(date) # 单日涨跌基金个数 # 上涨个数 count1 = range_for_date('1', date) # 下跌个数 count2 = range_for_date('-1', date) # 排名 topn(date) # 获取排名 mail_datas = {} period_datas = {} length = len(db.TABLES_LIST) - 1 for i in range(len(TABLES_LIST[1:length - 1])): tcount = db.get_list_count(TABLES_LIST[i + 1], date) if tcount == 0: logger.warning(TABLES_LIST[i + 1]) continue percent = int(tcount * config['percent']['percent']) ret = get(i + 1, date, percent) mail_datas[str(i + 1)] = ret # 周六计算本周各基金涨幅情况 if datetime.date.today().weekday() == 5: pre_friday, friday = holiday.get_current_week() logger.info("pre friday = %s, friday = %s", pre_friday, friday) for t in db.TABLES_LIST[1:length]: rise_by_all(t, pre_friday, friday, True) # 计算一段时间内的涨跌幅 from_date = holiday.get_before_month_date(config['period']['months']) period_datas[str(1)] = period.period_range(from_date, date) mail.send_email([0, len(period_datas[str(1)])], period_datas, date) # send email mail.send_email([count1, count2], mail_datas, date)
def contact(): form = ContactForm(request.form) if request.method == 'POST' and form.validate(): name = form.data['name'] email = form.data['email'] message = form.data['message'] contact = Contacts(name=name, email=email, comment=message) contact.save() send_email(name, email, message) time.sleep(5) return redirect('/') context = {'form': form} content = render_template('contact.html', **context) return content
def register(): form = RegisterForm() if form.validate_on_submit(): # args = (form.name.data, form.email.data, form.password.data, form.remember_me.data) # user = User(*args) # распаковка user = User(form.name.data, form.email.data, form.password.data, form.remember_me.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() text, html = render_email('/email/confirm', user=user, token=token) send_email(user.email, 'Confirm your account', html, text) flash('A confirmation email has been sent to you by email.') return redirect(url_for('index')) return render_template('register.html', form=form)
def send_error_email(): """ Catches exception and emails application administrator :return: None """ error = traceback.format_exc() send_email(recipients=[current_app.config['ADMIN_EMAIL']], subject='[{}] Application Error'.format( current_app.config['CONFIG_LVL']), template_name='error', context={ 'error': error, 'time': datetime.datetime.now() })
def contact_us(): form = ContactUsForm() if request.is_xhr: if form.validate_on_submit(): return json.dumps({}) else: return json.dumps(form.errors) if form.validate_on_submit(): comments = form.comments.data email = form.email.data _, html = render_email('/email/feedback', comments=comments, email=email) send_email('*****@*****.**', 'Feedback from site Green road', html) flash('Your massage was sent!') return redirect(url_for('index')) return render_template('contact_us.html', form=form)
def task_executor(): # creat work dir outDir = "%s/%s%s" % ('report', 'report', time.strftime('%Y%m%d-%H%M%S')) pwd = os.getcwd() os.makedirs(outDir) os.chdir(outDir) generate_report_head() fname = '%s/tasklist.xml' % pwd if os.path.exists(fname): with open(fname, "r") as f: soup = BeautifulSoup("\n".join(f.readlines())) l_node = soup.findAll('case') for node in l_node: d_attr = {} for key, val in node.attrs: d_attr[key] = val args = [] name = d_attr['name'] args.append(name) args.append('-t %s' % d_attr['time']) args.append('-r %s' % d_attr['repeat']) if d_attr['skip'] == 'true': args.append('-s') key = name[29:] task = " ".join(args) executor(key, task) else: print "%s not found in current folder" % fname sys.exit(1) generate_report_foot() # wipe off as " daemon not running" string ic.board() subject = "[Automatic Test Report][%s] - %s" % (ic.board(), ic.release()) mail.send_email(subject) os.chdir(pwd)
def main(): months = [1, 2, 3, 4, 5] start_time = datetime.now() try: # Start grab for m in months: grab(getfilename(2015, m, "awstats")) grab_end_time = datetime.now() grab_msg = "Grab duration: {}".format(grab_end_time - start_time) send_email("Grab IP down", grab_msg) # Start merge merge(2015, months) end_time = datetime.now() merge_msg = "Merge duration: {}".format(end_time - grab_end_time) merge_msg += "\nDuration: {}".format(end_time - start_time) send_email("IP handle down", merge_msg) except: errmsg = '\n'.join([traceback.format_exc(), "Duration: {}".format(datetime.now() - start_time)]) send_email("IP handle error", errmsg)
# -*- coding: utf-8 -*- import boto3, json, time from mail import send_email from uuid import uuid4 from creator import create s3 = boto3.resource('s3') def upload_s3(source_file, filename): bucket_name = '167985-last' destination_filename = "albums/%s/%s" % (uuid4().hex, filename) print destination_filename bucket = s3.Bucket(bucket_name) bucket.put_object(Key=destination_filename, Body=source_file, ACL='public-read') return destination_filename sqs = boto3.resource('sqs') albumRequests = sqs.get_queue_by_name(QueueName='last-album') bucket_address = 'https://s3.eu-central-1.amazonaws.com/167985-last' while True: for albumRequest in albumRequests.receive_messages(): print('processing request ..........') albumData = json.loads(albumRequest.body) pdf = create(albumData) dest = upload_s3(pdf.getvalue(), 'album.pdf') send_email(albumData['sent_to'], 'Twój Album', 'Twój album został wygenerowany i jest gotowy do pobrania. <a href="%s/%s">Kliknij, aby pobrać pdf</a>' % ( bucket_address, dest)) albumRequest.delete() print('request processing finished [X]') time.sleep(1)
def send_report(valid_recipents_address, content, subject, filename, project): fromaddress = settings.SMTP_CONF["USERNAME"] mail.send_email(fromaddress, valid_recipents_address, content, filename, subject, project)
try: grade = get_grade() if "userinit" in grade: print 'Not login.' login() continue data = parse_grade(grade) print time.strftime('%Y-%m-%d %X', time.localtime(time.time())), 'Count :', len(data) test_mail = False if first_run: ans = raw_input('Send test email? (y/n)') if ans.lower() in ['', 'y', 'yes']: test_mail = True if len(data) != len(olddata) and not first_run or test_mail: text = ' , '.join(row[2] + ' ' + row[3] for row in data if row not in olddata) if test_mail: text = 'Test email. ' + text print 'Sending mail...' print 'Text:', text.encode('utf8') if enable_mail: send_email(text, text.encode('utf-8')) print 'Mail sent.' olddata = data first_run = False except Exception as e: if not isinstance(e, KeyboardInterrupt): print time.strftime('%Y-%m-%d %X', time.localtime(time.time())), 'Error:', str(e) else: break time.sleep(interval)
num = instance.find(",") new = instance[0:num] teacher_list.append(new) teacher = input("What is the teacher's last name?: ") user_email = input("What is your email?: ") user_pass = input("What is your password?: ") message = input("What is the message you wish to send?: ") for link in soup.find_all("a"): if teacher in str(link.get("href")): teacher_email = link.get("href") col = teacher_email.find(":") + 1 teacher_email = teacher_email[col : len(teacher_email)] print(link.get("href")) print(teacher_email) # mail_list.append(link.get('@dist113')) if teacher in teacher_list: print("Y") else: print("N") mail.send_email(user_email, user_pass, teacher_email, message) print("Done")
def sending_email(sender, instance, created, **kwargs): if created: send_email(subject="Bem vindo a Assosiação PythonBrasil", template_name='members/email.html', context=instance.user.first_name, recipient_list=[instance.user.email])
import boto3, json, time from mail import send_email from uuid import uuid4 from creator import create s3 = boto3.resource('s3') def upload_s3(source_file, filename): bucket_name = '168569-robert' destination_filename = "albums/%s/%s" % (uuid4().hex, filename) print destination_filename bucket = s3.Bucket(bucket_name) bucket.put_object(Key=destination_filename, Body=source_file, ACL='public-read') return destination_filename sqs = boto3.resource('sqs') albumRequests = sqs.get_queue_by_name(QueueName='robert-album') bucket_address = 'https://s3.eu-central-1.amazonaws.com/168569-robert' while True: for albumRequest in albumRequests.receive_messages(): print('przetwarzanie ...') albumData = json.loads(albumRequest.body) pdf = create(albumData) dest = upload_s3(pdf.getvalue(), 'album.pdf') send_email(albumData['sent_to'], 'Oto twoj album', 'Pobierz tutaj: %s/%s' % ( bucket_address, dest)) albumRequest.delete() print('proces zakonczono pomyslnie [X]') time.sleep(1)
import boto3, json, time from mail import send_email from uuid import uuid4 from creator import create s3 = boto3.resource('s3') def upload_s3(source_file, filename): bucket_name = '168840-ziebol' destination_filename = "albums/%s/%s" % (uuid4().hex, filename) print destination_filename bucket = s3.Bucket(bucket_name) bucket.put_object(Key=destination_filename, Body=source_file, ACL='public-read') return destination_filename sqs = boto3.resource('sqs') albumRequests = sqs.get_queue_by_name(QueueName='zieba-album') bucket_address = 'https://s3.eu-central-1.amazonaws.com/168840-ziebol' while True: for albumRequest in albumRequests.receive_messages(): print('Trwa przetwarzanie rzadania...') albumData = json.loads(albumRequest.body) pdf = create(albumData) dest = upload_s3(pdf.getvalue(), 'album.pdf') send_email(albumData['sent_to'], 'Twoj album jest juz gotowy', 'Twoj album PDF jest juz gotowy. Mozesz go pobraz tutaj: %s/%s' % ( bucket_address, dest)) albumRequest.delete() print('Przetwarzanie rzadania zakonczone. [X]') time.sleep(1)
def checkFemaleEmployees(): global hr_email,leaving_time print "info :: Timed event triggered!" startJob(hr_email,leaving_time) mail.send_email([hr_email],'Female Employees Still in office!',generateMailMessage())
print('------------------%s ------------------' % branch) print 'Loading parameters ...' # get config information parameters = read_para.read_conf(path, branch) print 'Updating chart ...' # update data in chart chart.update_chart(path, branch, parameters, unstable) print 'Reading chart ...' # get data for graph datelist, datadict = chart.read_chart(path, branch) print 'Drawing graphs ...' # draw graph for ci result pic1, pic2 = graph.draw_graph(path, branch, datelist, datadict, parameters['graph']['day_num']) # get_labels(path, branch, parameters) sources = {'s1': pic1, 's2': pic2} print 'Creating email content ...' # create the html of email sources = mail.create_email(path, branch, datelist[0], sources, parameters) if r == 'a': rec = parameters['to'] cop = parameters['cc'] elif r == 'm': rec = [parameters['from']] cop = [parameters['from']] mail.send_email(path, branch, datelist[0], parameters['from'], rec, cop, sources) print 'Email('+str(datelist[0])+') sent to:\n\t\t'+'\n\t\t'.join(rec) print ' copied to:\n\t\t'+'\n\t\t'.join(cop) stop = time.clock() print('---------%s completed!--Time: %.0f sec----------' % (branch, (stop-start)))
def doQALaunchTime(qaArgs): uiobject_name = qaArgs.get("uiobject_name") bounds = d(text=uiobject_name).info.get("bounds") x = (bounds.get("left") + bounds.get("right")) / 2 y = (bounds.get("top") + bounds.get("bottom")) / 2 x = x * get_coordinate_precision().get('x') y = y * get_coordinate_precision().get('y') layer = qaArgs.get("layer") duration = qaArgs.get("sleep_time") packageName = qaArgs.get("packageName") repeatCount = qaArgs.get("repeat") outputName = qaArgs.get("outName") systrace = qaArgs.get("systrace") global SYSTRACE_FLAG, TAGS if systrace != "": SYSTRACE_FLAG = True if systrace not in ("", "1"): TAGS = " ".join(systrace) touchscreen = getTouchNode() outfd = open(outputName, "w") getLaunchTime(x, y, layer, touchscreen, duration) #removeFromLRU() amstop(packageName) resList = [] index = 0 content = "layer: %s" % layer print content init_dir() while (index < repeatCount): adb.cmd("shell dumpsys SurfaceFlinger --latency-clear") clear_logcat() start_tracing(TAGS) dbinfo = ic.collect(packageName) dbinfo['name'] = packageName.split(".")[-1] # i.e com.android.settings name: settings res = getLaunchTime(x, y, layer, touchscreen, duration) dbinfo["value"] = res content = "index %d: %d ms" % (index, res) print content index += 1 resList.append(res) #removeFromLRU() amstop(packageName) url = "%s/%s(%d)_%d.html" % (os.getcwd(), outputName, res, index) if SYSTRACE_FLAG is True: dbinfo["url"] = url sw.insert("launch", dbinfo) stop_tracing("%s\(%d\)_%d.html" % (outputName, res, index)) dump_logcat("%s\(%d\)_%d.logcat" % (outputName, res, index)) dump_dmesg("%s\(%d\)_%d.dmesg" % (outputName, res, index)) outfd.write(content) outfd.write("\n") mailmsg = [] sum = 0 average = 0 for i in range(len(resList)): sum += resList[i] content = "index %d: %d ms" % (i, resList[i]) mailmsg.append(content) outfd.write(content) outfd.write("\n") average = sum / len(resList) content = "average: %d ms" % (average) mailmsg.append(content) print content outfd.write(content) outfd.write("\n") resList.sort() content = "median = %d ms" % (resList[(len(resList) + 1) / 2]) mailmsg.append(content) print content outfd.write(content) outfd.write("\n") outfd.close() rsd = RSD(resList) mailmsg = ("<br/>").join(mailmsg) mailargs = {} mailargs["msg"] = mailmsg mailargs["subject"] = "%s(%s_%s - %s) : %d ms - %d " % (packageName, ic.board(), ic.release(), ic.pversion(packageName), average, rsd) send_email(mailargs) return rsd
def send_email(to_email, to_name, subject, message): mail.send_email(to_email, to_name, subject, message, app.config['MAILGUN_USER'], app.config['MAILGUN_KEY'], app.config['MAILGUN_DOMAIN'])
import boto3, json, time from mail import send_email from uuid import uuid4 from creator import create s3 = boto3.resource('s3') def upload_s3(source_file, filename): bucket_name = '191621' destination_filename = "albums/%s/%s" % (uuid4().hex, filename) print destination_filename bucket = s3.Bucket(bucket_name) bucket.put_object(Key=destination_filename, Body=source_file, ACL='public-read') return destination_filename sqs = boto3.resource('sqs') albumRequests = sqs.get_queue_by_name(QueueName='tomek-album') bucket_address = 'https://s3.eu-central-1.amazonaws.com/191621' while True: for albumRequest in albumRequests.receive_messages(): print('processing request ..........') albumData = json.loads(albumRequest.body) pdf = create(albumData) dest = upload_s3(pdf.getvalue(), 'album.pdf') send_email(albumData['sent_to'], 'Your album', 'download here: %s/%s' % ( bucket_address, dest)) albumRequest.delete() print('request processing finished [X]') time.sleep(1)
files = glob.glob("/mnt/ebs/solr-4.10.2/example/logs/*") # files = glob.glob("*.log") data = [] data.append(["Title","Region"]) for file in files: print file fdata = open(file,"r") lines = fdata.readlines() i = 0 for line in lines: try: i = i+1 if len(line.split("hits=0"))>1: match = re.search(regx,line) data.append([match.groups()[0].split("&",1)[0].replace("+"," "),regions.get(int(line.split("fq=region:")[1].split('&',1)[0]),"None")]) except: pass print data result = '' for row in data: result += "\n" col = "" for data in row: col += data+"," result += col print result if len(result) > 0: send_email(title="Zero result data" , data=result) # if len(data) > 0: # send_email(sub="Zero result data" , text=",".join(data))
def mail(): send_email('*****@*****.**','徐子悠') return '<p>test mail</p>'
def invite(request): project = request.context session = DBSession() user = get_user(request) redirect_uri = request.resource_url(project) iframe_url = 'https://www.facebook.com/dialog/apprequests?access_token=%(access_token)s&api_key=%(api_key)s&app_id=%(app_id)s&display=iframe&frictionless=false&locale=en_US&message=%(message)s&next=%(next)s' % { 'access_token' : request.session['access_token'] if 'access_token' in request.session else None, 'api_key' : request.registry.settings['facebook.app_id'], 'app_id' : request.registry.settings['facebook.app_id'], 'message' : "WEE ARE THE CHAMPIONS", 'next' : redirect_uri } # Parse the request params: emails = [] message = None response_params = {} if 'email_0' in request.params: i = 0 while 'email_' + str(i) in request.params: email = request.params['email_'+str(i)] if email: emails += [email] i += 1 message = request.params['message'] try: logging.info('Sending invite message for project ' + str(project.id)) send_email(user.email, emails, "You've been invited!", message) response_params['invited'] = True response_params['invitee_count'] = len(emails) except socket.error: pass else: if request.referrer == request.resource_url(project, 'new'): response_params['created'] = True if emails: # Add the emails to the participants list for that project. existing = session.query(Participation).filter(Participation.user_email.in_(emails)).filter(Participation.project==project).all() existing = [participation.user_email for participation in existing] for email in emails: if email in existing: continue session.add(Participation(project_id=project.id, user_email=email)) # Get friends list from serverside facebook api. friends = '' if 'access_token' in request.session: logging.info('Invite: access_token present in session, populating friends list') graph = fb.GraphAPI(request.session['access_token']) friends = graph.get_connections("me", "friends", fields='id,name') friends = json.dumps(friends) else: logging.info('Invite: no access_token in session, not facebook?') response_params.update({'user' : user_dict(request, user), 'project' : {'key':project.key,'title':project.title, 'url': request.resource_url(project)}, 'creator' : user_dict(request, project.creator), 'fb_app_id' : request.registry.settings['facebook.app_id'], 'iframe_url' : iframe_url, 'fb_access_token' : request.session['access_token'] if 'access_token' in request.session else None, 'friend_data' : friends, 'fb_login_url' : fb_login_url(request) }) return template_permissions(request, response_params)
def fetch(conf, send_mail=True): credentials = settings.WILMA_CREDENTIALS session = requests.Session() baseurl = credentials['url'] req = session.get(baseurl) logger.info('{0} - {1}'.format(req.url, req.status_code)) frontpage = bs4.BeautifulSoup(req.text) session_id = frontpage.find('input', attrs=dict(name='SESSIONID')).attrs[ 'value'] logger.debug("session id: {0}".format(session_id)) logindata = dict(SESSIONID=session_id, Login=credentials['username'], Password=credentials['password']) req = session.post(baseurl + '/login', logindata) logger.info('{0} - {1}'.format(req.url, req.status_code)) role_selection_page = bs4.BeautifulSoup(req.text) logger.debug(role_selection_page.find('div', attrs={'class': 'sidebar-related'}).find_all('a')) pupils = dict((a.text, a.attrs['href']) for a in role_selection_page.find('div', attrs={'class': 'sidebar-related'}).find_all('a') if a.attrs['href'].startswith('/!')) if not pupils: pupil_link = "/" + req.url.split("/")[-2] name = role_selection_page.find('span', attrs={'class': 'inner'}).text pupils = dict({name: pupil_link}) print(pupils) for name, pupil_link in pupils.items(): req = session.get('{}{}/messages'.format(baseurl, pupil_link)) logger.info('{0} - {1}'.format(req.url, req.status_code)) messages = bs4.BeautifulSoup(req.text) for message_link in messages.find_all('a', attrs={'class': 'fitt'}): message_id = message_link.attrs['href'].rsplit('/', 1)[-1] filename = os.path.join(settings.DATAPATH, '{0}_{1}.txt'.format(name, message_id)) try: with open(filename): pass except (OSError, IOError): with open(filename, 'wb') as f: req = session.get('{}{}/messages/{}'.format(baseurl, pupil_link, message_id)) logger.info('{0} - {1}'.format(req.url, req.status_code)) if req.status_code > 399: logger.error("{} failed with {}".format(req.url, req.status_code)) logger.debug(req.text) continue soup = bs4.BeautifulSoup(req.text) msg = soup.find('div', attrs={'class': 'columns-left-inner'}) subject = soup.find('h1', attrs={'class': 'safeflow'}).text try: sender, recipient, timestamp = (x.text for x in msg.find_all('td')[:3]) except ValueError: logger.warning(msg.find_all('td')) else: timestamp = parse( timestamp.replace(' klo ', ' at ')) message_body = '\n\n'.join( x.text for x in msg.find_all('p')) message = '** {} - {} **\n\n{}'.format( name, timestamp.isoformat(), message_body) f.write(subject.encode('utf-8') + b'\n') f.write(sender.encode('utf-8') + b'\n') f.write(recipient.encode('utf-8') + b'\n') f.write(timestamp.isoformat().encode('utf-8') + b'\n') f.write(message.encode('utf-8') + b'\n') # Mail if send_mail: rcpt = conf.RECIPIENT send_email(message, rcpt, sender, subject, timestamp, name) else: logger.info("Not sending e-mail") # Log out session.post(baseurl + '/logout', dict(loginbtn="Kirjaudu ulos"))
def send_email_task(subject, sender, recipients, body): recipients = [x for x in recipients if x is not None] send_email(subject, sender, recipients, body)
if not u.email: print("MISSING {un}".format(**locals())) continue #print("SENDING MAIL TO {un} at {u.email}".format(**locals())) #send_email(GMAIL_USER, GMAIL_PWD, u.email, "De kooklessen van Mieke op kookboot.com", mail) except User.DoesNotExist: if not row['Email']: print("SKIPPING {un}, no email".format(**locals())) continue pwd = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8)) extra = {'first_name': row['Voornaam'], 'last_name': row['Achternaam']} extra = {k:v for (k,v) in extra.items() if v and v.strip()} u = User.objects.create_user(un, row['Email'], password=pwd, **extra) print("CREATED USER {un} WITH PWD {pwd}".format(**locals())) new[un] = pwd for un, pwd in new.items(): u = User.objects.get(username=un) if not u.email: print("DELETING USER {un}".format(**locals())) u.delete() continue aanhef = u.first_name.strip() or un mail = MAIL_NEW.format(**locals()) print("SENDING MAIL TO {un} at {u.email}".format(**locals())) send_email(GMAIL_USER, GMAIL_PWD, u.email, "De kooklessen van Mieke op kookboot.com", mail) #print(mail) #{'Achternaam': 'Olthuis', 'Aantal_lessen': '35', 'Opmerkingen': '', 'Account bestaat?': 'Ja', 'Email': '', 'Username': '******', 'Voornaam': 'Kees'}