def mailer(): try: message = build_message() send_email(message['user'], message['pwd'], message['recipient'], message['subject'], message['body']) return "Thank you, your RSVP has been sent!" except: return error500
def _email_crash_report(self, dest_file_name): email_config = load_yaml_config("crash-mail-config.yaml") smtp_server = email_config.get('smtp-server') sender = email_config.get('sender') recipients = email_config.get('recipients') subject = email_config.get('subject', "Testsuite crash detected") max_bt_len = email_config.get('truncate-backtrace', 0) debug_level = email_config.get('debug', 0) if not sender or len(recipients) == 0: print "--email-on-crash requires sender and 1+ recipients" return with open(dest_file_name, 'r') as bt_file: backtrace_text = bt_file.read() if max_bt_len > 0 and backtrace_text > max_bt_len: truncated_text = "\n--truncated to {0} chars--".format(max_bt_len) backtrace_text = backtrace_text[0:max_bt_len] + truncated_text email_text = "{0}\n\n{1}".format(dest_file_name, backtrace_text) message = {'body': email_text, 'subject': subject} try: send_email(smtp_server, sender, recipients, message, debug=debug_level) except Exception as exception: print "Failed to send email\nError: {0}".format(exception)
def forgotpassword(request): form = account_forms.ForgetPasswordForm() if request.method == 'POST': form = account_forms.ForgetPasswordForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = get_object_or_404(User, username=cd['username']) if user.email == cd['email']: reset_password_code = tools.get_reset_password_code(user) reset_expires = timezone.localtime(timezone.now()) + timezone.timedelta(1) code, _ = ResetPasswordCode.objects.get_or_create(user=user) code.reset_password_code = reset_password_code code.reset_expires = reset_expires code.save() info = u'点击链接 %s/account/resetpassword/%s 重置您的密码。【Reminds】' % (DOMAIN, reset_password_code) send_email(user.email, u'Reminds重置密码', info) email_url = tools.get_email_url(user.email) messages.add_message( request, messages.INFO, u'重置密码链接已发送至你的<a href="http://%s" target="_blank">邮箱</a>,\ 请注意查收!' % email_url) else: messages.add_message( request, messages.INFO, u'邮箱错误!') return render_to_response( 'account/forgotpassword.html', {'form': form, }, context_instance=RequestContext(request))
def register(): if current_user.is_authenticated: return redirect('/') form = RegisterForm(request.form) if form.validate_on_submit(): user = User(email=form.email.data, password=form.password.data, confirmed=False) db.session.add(user) db.session.commit() token = generate_confirmation_token(user.email) confirm_url = url_for('user.confirm_email', token=token, _external=True) html = render_template('user/activate.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(user.email, subject, html) login_user(user) flash('A confirmation email has been sent via email.', 'success') return redirect(url_for("user.unconfirmed")) return render_template('user/register.html', form=form)
def _email_crash_report(self, dest_file_name): email_config = load_yaml_config("crash-mail-config.yaml") smtp_server = email_config.get('smtp-server') sender = email_config.get('sender') recipients = email_config.get('recipients') subject = email_config.get('subject', "Testsuite crash detected") max_bt_len = email_config.get('truncate-backtrace', 0) debug_level = email_config.get('debug', 0) if not sender or len(recipients) == 0: print("--email-on-crash requires sender and 1+ recipients") return with open(dest_file_name, 'r') as bt_file: backtrace_text = bt_file.read() if max_bt_len > 0 and backtrace_text > max_bt_len: truncated_text = "\n--truncated to {0} chars--".format(max_bt_len) backtrace_text = backtrace_text[0:max_bt_len] + truncated_text email_text = "{0}\n\n{1}".format(dest_file_name, backtrace_text) message = {'body': email_text, 'subject': subject} try: send_email(smtp_server, sender, recipients, message, debug=debug_level) except Exception as exception: print("Failed to send email\nError: {0}".format(exception))
def main(): emails = get_emails() forecast = weather.get_weather_forecast() self_email = input('Please input your email address:') password = input('Please input your password:') for email,name in emails.items(): mailer.send_email(self_email, password, email, name, forecast)
def resend_confirmation(): token = generate_confirmation_token(current_user.email) confirm_url = url_for('user.confirm_email', token=token, _external=True) html = render_template('user/activate.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(current_user.email, subject, html) flash('A new confirmation email has been sent.', 'success') return redirect(url_for('user.unconfirmed'))
def mail_shop_dict(self, shopping_dict): email_text = mailer.shop_dict_to_string(shopping_dict) detailed_send = input('send email (y/n): ') if detailed_send == 'y': email_text = email_text + mailer.book_content_to_string( self.get_book()) reciever_email = input('send shopping list to: ') mailer.send_email(email_text, reciever_email)
def check_organization_referral_upgrade(): profiles = models.EntityProfile.objects.filter(entity_type='org', entity_active=True) for profile in profiles: if not profile.plan.unlimited_referrals: if profile.referrals_made > (profile.plan.max_referrals_allowed - settings.REFERRALS_UPGRADE): subject = 'Upgrading your Nationwide Finance Plan' t = get_template('organization_plan_upgrade.html') c = Context(dict(referrals_made=profile.referrals_made, business_name=profile.business_name, max_referrals=profile.plan.max_referrals_allowed)) body = t.render(c) send_email(subject=subject, body=body, to_email=[profile.entity_contact.email,])
def close_fund(model, action_name): model.perform_close(action_name) fund = model.entity users = model.lookup_users_with_role(RoleType.FUND_ADMIN) to_addresses = map(lambda u: u.email, users) entity_ref = renderers.render_link( fund.name, urls.url_for_entity(fund, external=True)) content = renderers.render_div('Fund closed ', entity_ref, ' code=%s' % fund.code) mailer.send_email('Workbench Fund Closed', content, to_addresses)
def send_emails(self): self.subject = 'You Have Earned A Gift' self.template_name = 'gifts_notification' for entity in self.email_list: params = dict( merge_first_name = entity.first_name, merge_last_name = entity.last_name, merge_org_name = self.profile.business_name ) send_email(template=self.template_name, subject=self.subject, to_email=[entity.email,], params=params)
def send_emails(self): self.subject = 'You Have Earned A Gift' self.template_name = 'gifts_notification' for entity in self.email_list: params = dict(merge_first_name=entity.first_name, merge_last_name=entity.last_name, merge_org_name=self.profile.business_name) send_email(template=self.template_name, subject=self.subject, to_email=[ entity.email, ], params=params)
def check_date_for_emailer(flowermap, todays_date): """Use flowermap to figure out if today is the day to send the email.""" email_sent = False # if today's date matches this month's generated date, run emailer if flowermap['flowerday'] <= todays_date.day and \ flowermap['current_month'] == todays_date.month and \ not flowermap['email_sent']: email_sent = True send_email() write_flowermap(todays_date.day, todays_date.month, email_sent) return email_sent
async def check_blocks(): await client.wait_until_ready() while True: faulty_nodes = blockchecker.get_faulty_nodes() if any(faulty_nodes): for pool in faulty_nodes: # Id, such as z-pool.com245204 - i.e. pool name + block where the pool is stuck id = pool+str(faulty_nodes[pool]) if id in alerts: continue alerts.append(id) # Handler for when the pool is behind in block height if faulty_nodes[pool]['error'] == '5blocksbehind': await client.send_message(client.get_channel(allowed_channel), "**"+pool+"**" + " is 5 blocks behind the network!") if pool not in claims.keys(): continue for user in claims[pool]: await client.send_message(user,"**"+pool+"**" + " is 5 blocks behind the network!") if user in email_addresses: print("Sending email to " + email_addresses[user]) print(mailer.send_email(email_addresses[user],pool + " is having issues!","Hello! " + pool + " is 5 blocks behind the network!")) # Handler for disconnected pools if faulty_nodes[pool]['error'] == 'unresponsive': await client.send_message(client.get_channel(allowed_channel), "**"+pool+"**" + " is not responsive!") if pool not in claims.keys(): continue for user in claims[pool]: await client.send_message(user,"**"+pool+"**" + " is not responsive!") if user in email_addresses: print("Sending email to " + email_addresses[user]) print(mailer.send_email(email_addresses[user],pool + " is not responding!","Hello!" + pool + " has stopped responding.")) await asyncio.sleep(60)
def generateForgotPasswordEmail(): email = request.form.get("email") user = models.Users.query.filter_by(email=email).first() if user is not None: message = Template(getPasswordResetMessage()); send_email(["*****@*****.**"], "News That Moves: Password Reset Link", message.substitute({ "port": app.config.get("port"), "token": getattr(user, "reset_password_token"), "email": email, "url": app.config.get("url") })); else: return "fuk" return email
def check_date_for_emailer(flowermap, todays_date): """Use flowermap to figure out if today is the day to send the email.""" email_sent = False # if today's date matches this month's generated date, run emailer if flowermap['flowerday'] <= todays_date.day and \ flowermap['current_month'] <= todays_date.month and \ not flowermap['email_sent']: email_sent = True send_email() write_flowermap(todays_date.day, todays_date.month, email_sent) return email_sent
def email_entity_creator(entity, user, message): if not hasattr(entity, 'creator'): return if user.key == entity.creator: logging.info('not sending email same user %s', user.name) return creator = entity.creator.get() entity_type = entity.key.kind() entity_ref = renderers.render_link( entity.name, urls.url_for_entity(entity, external=True)) content = renderers.render_single_column( (entity_type, entity_ref, message, user.name), ('EntityType', 'Entity', 'Message', 'User')) mailer.send_email('Workbench Entity State Change', content, [creator.email])
def forgot_password(): token = request.args.get('token', None) form = ResetPassword(request.form) #form if form.validate_on_submit(): email = form.email.data user = User.query.filter_by(email=email).first() if user: token = generate_confirmation_token(user.email) confirm_url = url_for('user.reset_password', token=token, _external=True) html = render_template('user/forgetPw.html', confirm_url=confirm_url) subject = "Change Password" send_email(user.email, subject, html) flash('A mail to change Password has been sent.', 'success') return render_template('user/reset.html', form=form)
def run(self, **kwargs): # [ONLY IF STORAGE IS ENABLE] save the previous count of results. if self.storage: previous_count = self.storage.count_articles(self.date) # collect articles response = super(CollectArticlesAndSendEmail, self).run(**kwargs) # add email to the report self.report.meta['email'] = self.email # [ONLY IF STORAGE IS ENABLE] if there are more results since the last collect, send an email if self.storage: if self.storage.count_articles(self.date)> previous_count: link = settings.URL_TO_CLIENT date = brokenpromises.utils.date_to_string(*self.date) send_email(self.email, subject = CollectArticlesAndSendEmail.EMAIL_SUBJECT.format(date=date), body = CollectArticlesAndSendEmail.EMAIL_BODY.format(date=date, link=link) ) return response
def main(source, recipients): config = ConfigParser.ConfigParser() config.readfp(open('config.cfg')) aws_credentials = (config.get('default', 'aws_access_key_id'), config.get('default', 'aws_access_key_secret')) google_credentials = authenticator.get_credentials() # Create an httplib2.Http object and authorize it with our google_credentials http = httplib2.Http() http = google_credentials.authorize(http) service = build('drive', 'v2', http=http) today = get_year_month_day() print "Today is %d.%d.%d" % (today[2], today[1], today[0]) pictures_folder_file_id = config.get('default', 'pictures_folder_id') pictures_folder = get_file(service, pictures_folder_file_id) public_folder_id = config.get('default', 'public_folder_id') public_folder = get_file(service, public_folder_id) yearly_selected_files = [] for i in range(1, 10): target_day = (today[0] - i, today[1], today[2]) print "Looking for photos taken on %d.%d.%d" % (target_day[2], target_day[1], target_day[0]) files = find_files(service, pictures_folder, target_day) if files: i = random.randint(0, len(files) - 1) yearly_selected_files.append((target_day, files[i])) if len(yearly_selected_files) > 0: i = random.randint(0, len(yearly_selected_files) - 1) selected_date = yearly_selected_files[i][0] selected_file = yearly_selected_files[i][1] print "Selected image %s from %d.%d.%d" % (selected_file['title'], selected_date[2], selected_date[1], selected_date[0]) public_selected_file = copy_to_public_folder(service, selected_file['id'], public_folder_id) print "Copied selected image to public folder, id: %s" % public_selected_file['id'] url = public_folder['webViewLink'] + public_selected_file['title'] print url mailer.send_email(today, source, recipients, [(selected_date, url)], aws_credentials) print "Mail sent" else: print "No images for today"
def main(): """ Entry point for the application :return: """ global num_days logging.debug('Mailer script invoked.') if num_days <= 0: print('Event has lapsed') logging.warning('The event has lapsed. Num days is %s' % num_days) return logging.debug('Sending email') try: send_email(get_content()) except Exception as xcpt: logging.error(str(xcpt)) print('Done!')
def check_organization_referral_upgrade(): profiles = models.EntityProfile.objects.filter(entity_type='org', entity_active=True) for profile in profiles: if not profile.plan.unlimited_referrals: if profile.referrals_made > (profile.plan.max_referrals_allowed - settings.REFERRALS_UPGRADE): subject = 'Upgrading your Nationwide Finance Plan' t = get_template('organization_plan_upgrade.html') c = Context( dict(referrals_made=profile.referrals_made, business_name=profile.business_name, max_referrals=profile.plan.max_referrals_allowed)) body = t.render(c) send_email(subject=subject, body=body, to_email=[ profile.entity_contact.email, ])
def execute(nb_name, nb_path, mail_to=None, only_errors=False, pdf=False, truncate=False): """Execute a notebook and send an email if asked""" output_folder = config.get_nb_config()['output_folder'] suffix = datetime.now().strftime('%Y%m%d-%H%M%S') out_filename = '%s_%s' % (nb_name, suffix) out_path = Path(output_folder) / nb_name out_path.mkdir(parents=True, exist_ok=True) out_path = out_path / out_filename os.environ['WORKING_DIR'] = str(nb_path.parent) is_error = False try: out_html = '%s.html' % out_path run_notebook(str(nb_path), save_html=True, suffix=suffix, out_path_ipynb='%s.ipynb' % out_path, out_path_html=out_html) if pdf: import pdfkit pdfkit.from_file(out_html, '%s.pdf' % out_path) except Exception as e: # noqa print(e) is_error = True finally: if is_error or not only_errors: send_email(nb_name, out_path, pdf, email=mail_to, is_error=is_error) if os.getenv('WORKING_DIR'): del os.environ['WORKING_DIR'] # remove history if needed if truncate: do_truncate(nb_name, truncate)
def run(self, **kwargs): # [ONLY IF STORAGE IS ENABLE] save the previous count of results. if self.storage: previous_count = self.storage.count_articles(self.date) # collect articles response = super(CollectArticlesAndSendEmail, self).run(**kwargs) # add email to the report self.report.meta['email'] = self.email # [ONLY IF STORAGE IS ENABLE] if there are more results since the last collect, send an email if self.storage: if self.storage.count_articles(self.date) > previous_count: link = settings.URL_TO_CLIENT date = brokenpromises.utils.date_to_string(*self.date) send_email( self.email, subject=CollectArticlesAndSendEmail.EMAIL_SUBJECT.format( date=date), body=CollectArticlesAndSendEmail.EMAIL_BODY.format( date=date, link=link)) return response
def calcHealth(self, status): event_time = datetime.now() if status != self.lastStatus: self.healthCount = 0 self.unhealthyCount = 0 self.lastStatus = status if status == Utils.UP: self.healthCount += 1 event = "UPTIME" else: self.unhealthyCount += 1 event = "DOWNTIME" if (status == Utils.UP and self.healthCount == self.threshold.health ) or (status == Utils.DOWN and self.unhealthyCount == self.threshold.unhealthy): send_email(self.email, f"{event} {self.host.host}", build_html(f"{event}", event_time, self)) log = f"{event_time};{event};{self.host.host};{self.host.port}" self.writeLog(event_time, log)
def run_report(config, email=False): trello = TrelloClient(os.getenv("TRELLO_KEY"), os.getenv("TRELLO_TOKEN")) report_text = build_report(config, trello) if report_text is None: print("(nothing to report)") return if email: result = send_email(config["emailAddress"], config["subject"], report_text) pprint(result) else: print(report_text)
def send_warning(self, selector, dev_key, body_txt): dt_now = datetime.datetime.now() try: device = self.eq3.devices[dev_key] except KeyError: device = [1, "KeyError", "Key Error", 99, 0, datetime.datetime(2016, 01, 01, 12, 00, 00), 18, 56, 7] device_name = device[2] room_name = "Error room" logmsg.update("Key error: " + str(dev_key), 'E') else: device_name = device[2] room = device[3] room_name = self.eq3.rooms[str(room)] sil = self.silence(dev_key, selector == "window") if not sil == 1: mute_str = "http://" + self.setup.my_ip + ":" + str(self.setup.ext_port) + "/data/put/command/mute:" + \ str(dev_key) msg = None if selector == "window": oww = int((dt_now - self.eq3.windows[dev_key][0]).total_seconds()) owd = dt_now - self.eq3.devices[dev_key][5] if sil == 0 and oww < self.setup.intervals["oww"][1]: return msg = mailer.new_compose(selector, room_name[0], device_name, room_name[0], str(owd).split('.')[0], (self.setup.intervals["oww"][0] * self.eq3.windows[dev_key][3]) / 60, mute_str, self.setup.intervals["oww"][2] / 60) else: if sil == 0 and not self.isrt("wrn"): return if selector == "battery" or selector == "error": msg = mailer.new_compose(selector, device_name, device_name, room_name[0], mute_str, self.setup.intervals["wrn"][1] / 60) elif selector == "openmax" or selector == "upgrade": msg = mailer.new_compose(selector, "", body_txt) if mailer.send_email(self.setup, msg.as_string()) and selector == "window": # original code # self.eq3.windows[dev_key][0] = dt_now # dev code # extend warning period by incrementing multiplicand * oww time self.eq3.windows[dev_key][3] += 1 self.eq3.windows[dev_key][0] = dt_now + datetime.timedelta( seconds=(self.setup.intervals["oww"][0] * self.eq3.windows[dev_key][3])) logmsg.update("Multiplicand for " + str(dev_key) + " updated to " + str(self.eq3.windows[dev_key][3]), 'D') else: logmsg.update("Warning for device " + str(dev_key) + " is muted!")
def run_email(event, context): student = event['key'] if 'key' in event else 'Lehman, Hayes' case = event[ 'case'] if 'case' in event else '0a608d99-9484-4333-a735-29179e1e1ef5' student_parsed = student.split(', ') student_name = student_parsed[1] + ' ' + student_parsed[0] print(student_name) recipients = ['*****@*****.**', '*****@*****.**'] if 'queryStringParameters' in event and 'recipients' in event[ 'queryStringParameters']: recipients = ast.literal_eval( event['queryStringParameters']['recipients']) datetime_object = get_date(event) current_date = '{d.month}/{d.day}/{d.year}'.format(d=datetime_object) cb = ChromeBrowser(datetime_object) cb.log_in() cb.select_student(case) tantrum_graph = cb.get_tantrum_graph(case) rm_list = cb.get_recently_mastered(student_name) tc_list = cb.get_trial_count(student_name) attachment_list = cb.get_attachments() if attachment_list: send_email(current_date, recipients, attachment_list, rm_list, tc_list, tantrum_graph, student_name) response = {"statusCode": 200} return response
if len(response.json()[key]) != 0 and key != 'queryEndTime': if len(response.json()[key]) == 1: dict = response.json()[key][0] message += '********************Alert********************\n' message += 'Status: ' + key + '\n' message += 'Recipient: ' + json.dumps(dict['recipient']) message += '\nSender: ' + json.dumps(dict['sender']) message += '\nSenderIP: ' + json.dumps(dict['senderIP']) message += '\nSubject: ' + json.dumps(dict['subject']) message += '\nthreatsInfoMap: ' + json.dumps( dict['threatsInfoMap']) message += '\n**********************************************\n\n' #mailer.send_email('Proofpoint Alert: ' + key, message) #pprint(message) else: for i in range(len(response.json()[key]) - 1): dict = response.json()[key][i] message += '********************Alert********************\n' message += 'Status: ' + key + '\n' message += 'Recipient: ' + json.dumps(dict['recipient']) message += '\nSender: ' + json.dumps(dict['sender']) message += '\nSenderIP: ' + json.dumps(dict['senderIP']) message += '\nSubject: ' + json.dumps(dict['subject']) message += '\nthreatsInfoMap: ' + json.dumps( dict['threatsInfoMap']) message += '\n**********************************************\n\n' #mailer.send_email('Proofpoint Alert: ' + key, message) #pprint(message) if message != '': mailer.send_email('Proofpoint Alerts', message)
('This Friday', constants.FRIDAY), ('This Saturday', constants.SATURDAY), ('This Sunday', constants.SUNDAY), ('This month', monthly_url(0)), ('Next month', monthly_url(1)), ]: logging.debug('Processing ' + section) content += extract_content_from_timeout_url(section, url) template = template_env.get_template(constants.EMAIL_TEMPLATE) email_content = template.render(content=content) try: if SEND_EMAIL: logging.info('Sending email to {}'.format(RECIPIENT)) mailer.send_email( user=SENDER_EMAIL, pwd=SENDER_PASSWORD, recipient=RECIPIENT, subject='Timout Events - {}'.format(time.strftime('%d/%m/%Y')), body=email_content, ) logging.debug('Email sent') finally: with open(OUTPUT_FILE, 'w') as f: f.write(email_content.encode('utf-8')) logging.debug('Wrote output to {}'.format(OUTPUT_FILE))
#coding=utf-8 #Author: Jiangtian #Create Date:2018/08/06 #Last Edited:2018/08/06 #在进程意外结束之后发送提示邮件至指定的邮箱。需要和shell脚本配合食用 import mailer mailer.send_email('*****@*****.**', '主进程意外结束', "主进程意外结束")
print(child_name, child_birthdate) def body_builder_catch(this_week_bdays): bday_catch = [] this_week_bdays = { child_name: child_birthdate for child_name, child_birthdate in sorted(this_week_bdays.items(), key=lambda item: item[1]) } for child_name, child_birthdate in this_week_bdays.items(): birthday = datetime.strftime(child_birthdate, '%B %d') bday_catch.append(f"{child_name}'s birthday is {birthday}\n") bday_str = "".join(bday_catch) return bday_str def body_assemble(): if len(this_week_bdays) > 0: body = f'Hi {cred.receiver_name},\n\nHere\'s your list of kiddos with a birthday in the next week:\n\n{formattedBirthdays}\n\nHope you have an amazing day!' else: body = f'Hi {cred.receiver_name},\n\nNo birthday reminders this week :)' return body main() formattedBirthdays = body_builder_catch(this_week_bdays) body = body_assemble() subject = f'Weekly Birthday Report ({today})' mailer.send_email(subject, body)
def main(): #初始化webdriver chrome_options = Options() chrome_options.add_argument('window-size=1366x768') #指定浏览器分辨率 chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug chrome_options.add_argument('--hide-scrollbars') #隐藏滚动条, 应对一些特殊页面 chrome_options.add_argument( '--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败 chrome_options.add_argument('--no-sandbox') #root用户需要在此属性下运行 driver = webdriver.Chrome(chrome_options=chrome_options) driver = loginer.login(driver) #这里是需要编辑的帖子URL。 bantou = 'http://bbs.ngacn.cc/post.php?action=modify&_newui&fid=321&tid=13537753&pid=0&article=0' #http://bbs.ngacn.cc/post.php?action=modify&_newui&fid=321&tid=13537753&pid=0&article=0 #zhuanti = 'https://bbs.ngacn.cc/post.php?action=modify&_newui&fid=321&tid=14599412&pid=0&article=0' bantou = 'https://bbs.nga.cn/post.php?action=modify&_newui&fid=-10323371&tid=15206099&pid=0&article=0' while True: #主循环 ##################################### # 以下内容为通用部分 # #记录本次循环开始的时间戳 isposter = False #初始化发帖开关 unixtime = time.time() if poster.hasLogined(driver) == False: #如果登录失效的话重新登录,并发送提醒邮件 mailer.send_email('*****@*****.**', '登录已失效,请重新登录', ("登录失效于:{}".format(shijian()))) input('登录已失效,请重新登录。按任意键继续...') #等待确认后再进行登录操作,以免验证码过期 driver = loginer.login(driver) # ##################################### oldtext = poster.viewer(driver, bantou) #获取原先的帖子内容。 if True: #每小时读取一次精品区 essencejudgment = essence.watchdog(driver) #读精品区帖子内容 if essencejudgment != 0: #如果精品区帖子改变了就处理新的精品区。 [newtext2, newtext3, newtext4] = essencejudgment if newtext2 != '': oldtext = poster.replace_content(oldtext, newtext2, 2) if newtext3 != '': oldtext = poster.replace_content(oldtext, newtext3, 3) if newtext4 != '': oldtext = poster.replace_content(oldtext, newtext4, 4) #oldtext = poster.replace_content(oldtext, newtext4, 6) #TI特供版 #并且每小时更新一次倒计时 #oldtext = poster.replace_content(oldtext, '[size=200%][color=red]{}[/color][/size]天[size=200%][color=red]{}[/color][/size]小时'.format(countdown.run()[0], countdown.run()[1]), 5) isposter = True print('every hour update essence and countdown') #if False:#(time.localtime().tm_min % 5) == 1: #每分钟读取一次赛事信息,以及奖金 # print ('start to update gameplay') # gameplay_mainevent.catch() # gametext = gameplay_mainevent.writeformat(0) # #ranktext = gameplay.writeformat(2) # oldtext = poster.replace_content(oldtext, gametext, 7) # #oldtext = poster.replace_content(oldtext, ranktext, 0) # prizetext = prizepool.run() # oldtext = poster.replace_content(oldtext, str(prizetext), 8) # isposter = True # print ('updated gameplay') if time.localtime().tm_hour == 4: #每天凌晨4时抓取新的heropick数据。 newtext = heropick.run() print(newtext) oldtext = poster.replace_content(oldtext, newtext, 1) isposter = True print('update heropick') if time.localtime().tm_hour == 12: #每天中午12点更新本日奖励英雄。 newtext = bonus.run() print(newtext) oldtext = poster.replace_content(oldtext, newtext, 8) isposter = True print('update bonus hero') #if essence.judgment(): # poster.poster(driver, essence.run) if isposter == True: timestr = str(time.time()) with open('post-' + timestr, 'w') as f: f.write(oldtext) poster.poster(driver, oldtext, bantou) #if isposter == True: #如果发帖开关被打开了就保存一份修改记录到本地。###不保存了,都搞出MemoryError了 # with open ('logger.txt', 'r+', encoding='utf-8') as f: # f.write(f.read() + '\n\n\n\n###################################\n\n {}\n\n{}\n'.format(shijian(), oldtext)) #编辑专题贴 不编辑了,手动啦 #oldtext = poster.viewer(driver, zhuanti) #获取原先的帖子内容。 #newtext = gameplay_mainevent.writeformat(1) #oldtext = poster.replace_content(oldtext, newtext, 9) #poster.poster(driver, oldtext, zhuanti) print("last check:{}".format(shijian())) time.sleep( 3600 - (time.time() - unixtime)) #睡眠时间为3600秒减去本次循环耗费的时间,以保证每个循环用时为1h整
def send_confirmation_email(cls, email): confirmation_link = "https://shameonfeinstein.org/sign?token={}".format(cls.token_for_email(email)) confirmation_html = "Please click this link to confirm your signature on the Shame on Feinstein letter. If you do not click this link, your signature will not be counted: <a href='{}'> sign letter</a>.".format(confirmation_link) confirmation_text = "Please click this link to confirm your signature on the Shame on Feinstein letter. If you do not click this link, your signature will not be counted: {}".format(confirmation_link) send_email(to=email, subject="Confirm signature for Shame on Feinstein letter", text=confirmation_link,html=confirmation_html)
SENDER_EMAIL = "*****@*****.**" SENDER_PASSWORD = "******" # Scrape product cards product_cards = run_search(SEARCH_URL) # Find recent items recent_items = [] for card in product_cards: difference = get_days(card) if difference <= DAYS: card_values = get_attributes(card) recent_items.append(card_values) else: break # Print summary summary = f'Found {len(recent_items)} items posted in the last {DAYS} days' print(summary) # Export processed data pickle.dump(recent_items, open("naked_and_famous.p", "wb")) # Generate markup email_markup = generate_markup("Naked and Famous Jeans", recent_items) # Send email send_email(email_markup, USER_EMAIL, SENDER_EMAIL, SENDER_PASSWORD)
def render_form(request, form, appstruct=colander.null, submitted='submit', success=None, readonly=False): captured = None if submitted in request.POST: # the request represents a form submission try: # try to validate the submitted values controls = request.POST.items() captured = form.validate(controls) print captured if success: try: # call validate user = model.User(name = captured['personal_information']['name'], surname = captured['personal_information']['Surname'], email = captured['personal_information']['email'], institution = captured['personal_information']['Institution'], arrival_datetime = datetime.datetime.combine(captured['arrival_information']['Expected_Arrival_date'], captured['arrival_information']['Expected_arrival_time']), arrival_busoption = captured['arrival_information']['Arrival_BUS_option'], arrival_bus_morning = captured['arrival_information']['BUS_option_arrival_morning'], departure_datetime = datetime.datetime.combine(captured['departure_information']['Expected_departure_date'], captured['departure_information']['Expected_departure_time']), departure_busoption = captured['departure_information']['Departure_BUS_option'], departure_bus = captured['departure_information']['BUS_option_departure'], vegeterian = captured['personal_information']['Vegetarian'], student = captured['personal_information']['Student'], hotel = 1, Occupancy = captured['hotel_information']['Occupancy'], Double_use = captured['hotel_information']['Double_use'], Gender_double_use = captured['hotel_information']['Gender_double_use'], Proposed_name = captured['hotel_information']['Proposed_name']) model.session.add(user) model.session.commit() id_reg = user.id except sqlalchemy.exc.IntegrityError, exc: reason = exc.message if reason.endswith('is not unique'): err_msg = "%s already exists" % exc.params[0] model.session.rollback() return {'form' : err_msg} except sqlalchemy.exc.SQLAlchemyError: err_msg = "DB connection problems, plase try again or contact with administrator" model.session.rollback() return {'form' : err_msg} response = success() if response is not None: import mailer mailer.send_email("smtp.gmail.com",587,"*****@*****.**","XXXXXXX",captured['personal_information']['email'], form , "DES-BCN ID registration "+str(id_reg)) if captured['personal_information']['Student'] == True: msg = '<h3> Thanks! your registration number is '+str(id_reg)+' <br> As you registered as student you do not have to pay the registration fee </h3>' else : msg = '<h3> Thanks! your registration number is '+str(id_reg)+' <br> Please take note of this registration ID because it is required for the payment process</h3> <br> <a href= "https://tp.ifae.es/cgi-bin/des.cgi" button class="btn-large btn-primary"> Proceed to payment</a>' return {'form' : msg } html = form.render(captured)
def send_warning(self, selector, dev_key, body_txt): subject = "" body = "" d = self.eq3.devices[dev_key] dn = d[2] r = d[3] rn = self.eq3.rooms[str(r)] sil = self.silence(dev_key, selector == "window") if sil == 1: logmsg.update("Warning for device " + str(dev_key) + " is muted!") return mutestr = "http://" + self.setup.myip + ":" + str(self.setup.extport) + "/data/put/command/mute" + str(dev_key) if selector == "window": owd = int((datetime.datetime.now() - self.eq3.devices[dev_key][5]).total_seconds()) oww = int((datetime.datetime.now() - self.eq3.windows[dev_key][0]).total_seconds()) if sil == 0 and oww < self.setup.intervals["oww"][1]: return subject = "Open window in room " + str(rn[0]) + ". Warning from thermeq3 device" body = """<h1>Device %(a0)s warning.</h1> <p>Hello, I'm your thermostat and I have a warning for you.<br/> Please take a care of window <b>%(a0)s</b> in room <b>%(a1)s</b>. Window in this room is now opened more than <b>%(a2)d</b> mins.<br/> Threshold for warning is <b>%(a3)d</b> mins.<br/> </p><p>You can <a href="%(a4)s">mute this warning</a> for %(a5)s mins.""" % \ {'a0': str(dn), 'a1': str(rn[0]), 'a2': int(owd / 60), 'a3': int(self.setup.intervals["oww"][0] / 60), 'a4': str(mutestr), 'a5': int(self.setup.intervals["oww"][2] / 60)} else: if sil == 0 and not self._is("wrn"): return if selector == "battery": subject = "Battery status for device " + str(dn) + ". Warning from thermeq3 device" body = """<h1>Device %(a0)s battery status warning.</h1> <p>Hello, I'm your thermostat and I have a warning for you.<br/> Please take a care of device <b>%(a0)s</b> in room <b>%(a1)s</b>. This device have low batteries, please replace batteries.<br/> </p><p>You can <a href="%(a2)s">mute this warning</a> for %(a3)s mins.""" % \ {'a0': str(dn), 'a1': str(rn[0]), 'a2': str(mutestr), 'a3': int(self.setup.intervals["wrn"][1] / 60)} elif selector == "error": subject = "Error report for device " + str(dn) + ". Warning from thermeq3 device" body = """<h1>Device %(a0)s radio error.</h1> <p>Hello, I'm your thermostat and I have a warning for you.<br/> Please take a care of device <b>%(a0)s</b> in room <b>%(a1)s</b>. This device reports error.<br/> </p><p>You can <a href="%(a2)s">mute this warning</a> for %(a3)s mins.""" % \ {'a0': str(dn), 'a1': str(rn[0]), 'a2': str(mutestr), 'a3': int(self.setup.intervals["wrn"][1] / 60)} elif selector == "openmax": subject = "Can't connect to MAX! Cube! Warning from thermeq3 device" body = body_txt elif selector == "upgrade": subject = "thermeq3 device is going to be upgraded" body = body_txt m_id = self.setup.get_mail_data() m_id.update({"s": subject}) msg = mailer.compose(m_id, body) if mailer.send_email(m_id, msg.as_string()) == 0 and selector == "window": self.eq3.windows[dev_key][0] = datetime.datetime.now()
def main(to, text, id): send_email(to, 'Date Remind', text)
from book_shelf import BookShelf from book import Book from ingredient import Ingredient from confirm import confirm from recipe import Recipe import random import datetime import mailer message = 'hello ben' rec = input('send list to what email? ') mailer.send_email(message, rec)
def main(): emails = get_emails() schedule = get_schedule() forecast = weather.get_weather_forecast() mailer.send_email(emails, schedule, forecast)
def send_warning(self, selector, dev_key, body_txt): dt_now = datetime.datetime.now() try: device = self.eq3.devices[dev_key] except KeyError: device = [ 1, "KeyError", "Key Error", 99, 0, datetime.datetime(2016, 01, 01, 12, 00, 00), 18, 56, 7 ] device_name = device[2] room_name = "Error room" logmsg.update("Key error: " + str(dev_key), 'E') else: device_name = device[2] room = device[3] room_name = self.eq3.rooms[str(room)] sil = self.silence(dev_key, selector == "window") if not sil == 1: mute_str = "http://" + self.setup.my_ip + ":" + str(self.setup.ext_port) + "/data/put/command/mute:" + \ str(dev_key) msg = None if selector == "window": oww = int( (dt_now - self.eq3.windows[dev_key][0]).total_seconds()) owd = dt_now - self.eq3.devices[dev_key][5] if sil == 0 and oww < self.setup.intervals["oww"][1]: return msg = mailer.new_compose(selector, room_name[0], device_name, room_name[0], str(owd).split('.')[0], (self.setup.intervals["oww"][0] * self.eq3.windows[dev_key][3]) / 60, mute_str, self.setup.intervals["oww"][2] / 60) else: if sil == 0 and not self.isrt("wrn"): return if selector == "battery" or selector == "error": msg = mailer.new_compose( selector, device_name, device_name, room_name[0], mute_str, self.setup.intervals["wrn"][1] / 60) elif selector == "openmax" or selector == "upgrade": msg = mailer.new_compose(selector, "", body_txt) if mailer.send_email(self.setup, msg.as_string()) and selector == "window": # original code # self.eq3.windows[dev_key][0] = dt_now # dev code # extend warning period by incrementing multiplicand * oww time self.eq3.windows[dev_key][3] += 1 self.eq3.windows[dev_key][0] = dt_now + datetime.timedelta( seconds=(self.setup.intervals["oww"][0] * self.eq3.windows[dev_key][3])) logmsg.update( "Multiplicand for " + str(dev_key) + " updated to " + str(self.eq3.windows[dev_key][3]), 'D') else: logmsg.update("Warning for device " + str(dev_key) + " is muted!")