def report(self, text, job, verbose=False, catalog=False, error=False): '''Report to console and send email notifications if jobs are configured to do so''' assert job in self.cf.sections() cf = getattr(self.cf, job) text += "Job name:\t\t%s \n" % job mail_text = text if catalog: text += "Catalog id:\t\t%s\nStatus Code:\t\t%s \n" % (catalog.id, catalog.status) mail_text = text + "Transcript:\n\n%s\n" % reindent(catalog.log, 4) if verbose: text += "Transcript:\n\n%s\n" % reindent(catalog.log, 4) try: if error: if cf.send_email: send_email(cf, mail_text, error=True) else: if cf.send_email and cf.report_success: send_email(cf, mail_text) except socket.error, e: self.stdout.write( "ERROR, could not contact to the smtp server: \n") self.stdout.write(reindent(e.message, 4) + "\n")
def company_signup(): payload = json.loads(request.data) payload['password'] = hash_password(payload['password']) status_code, data = backend_api.signup_company(payload) response_data = {"data": data} if status_code == 200: access_token = create_access_token(identity={ 'id': data.get('id'), 'email': data.get('email'), 'is_company': True }) refresh_token = create_refresh_token(identity={ 'id': data.get('id'), 'email': data.get('email'), 'is_company': True }) response_data["access_token"] = access_token response_data["refresh_token"] = refresh_token # skip email confirmation for test environment if os.environ.get('TEST') is None: token = generate_confirmation_token(payload['email']) verification_url = url_for('company_login_api.confirm_email', token=token, _external=True) html = render_template('verification_email.html', verification_url=verification_url) subject = "Please confirm your email" send_email(data.get('email'), subject, html) return jsonify(response_data), status_code
def write_to_pic(name, email): # 执行完这个方法后生成一个 result.png 图片 可加入email参数 number = get_number(email) # 用这个方法获取到编号 date_str = datetime.datetime.strftime(datetime.datetime.now(), '%Y年%m月%d日') #获取日期 update_status(email) # use 参数 变为1 生成了证书 im = Image.open("pic.jpg") draw = ImageDraw.Draw(im) font_name = ImageFont.truetype('font/1.ttf', size=55) # 名字的字体和字号 font_number = ImageFont.truetype('font/2.ttf', size=35) # 编号的字体和字号 setFontdate = ImageFont.truetype('font/DENG.TTF', size=28) # date字体路径 imwidth, imheight = im.size font_width, font_height = draw.textsize(name, font_name) # 获取名字的大小 draw.text(((imwidth - font_width - font_name.getoffset(name)[0]) / 2, 470), text=name, font=font_name, fill=(0, 0, 0)) # 写上名字 x使用了居中 draw.text(xy=(310, 285), text=number, font=font_number) # 写上编号 draw.text((434, 900), date_str, font=setFontdate, fill=(0, 0, 0)) # 写上日期 image_file = 'result.png' im.save(image_file) update_status(email, 3) send_email( to_email=email, subject='请领取您的志愿者证书', content= '您好,附件中有您的证书\n\n\nwuhan2020 开源社区\n\n\n社区网址:<a href="https://community.wuhan2020.org.cn/">https://community.wuhan2020.org.cn/</a>', attachment=[image_file]) update_status(email, 4)
def show_state_page(state_code): try: state = State.get(State.code**state_code) positions = state.positions.order_by(StatePosition.role.desc())[1:] events = state.events.order_by(Event.date.desc()) return render_template("states/state_base.html", state=state, positions=positions, events=events) except State.DoesNotExist: form = ApplyStateForm(request.form) if not form.validate_on_submit(): flash_errors(form) return render_template("states/apply.html", form=form) message = render_template("states/apply_email.html", form=form) send_email( current_app.config["EMAIL_FROM"], '*****@*****.**', 'State Director Application - {}'.format( current_app.config.get("APP_NAME", "Unified Democracy")), message) send_email( current_app.config["EMAIL_FROM"], '*****@*****.**', 'State Director Application - {}'.format( current_app.config.get("APP_NAME", "Unified Democracy")), message) flash("Application Successful", "success") return redirect(url_for("staticpages.show_staticpage", page="index"))
def wizard_send_email(): # add new request to database router_db = current_app.config['ROUTER_DB'] r = IPRequest(session['hostname'], session['email'], session['router_id']) db.session.add(r) db.session.commit() # allocate mesh IPs router = router_db_get_entry(router_db, session['router_id']) ip_mesh_num = 2 if router['dualband'] else 1 get_api().allocate_ips(current_app.config['API_POOL_MESH'], r.id, r.email, r.hostname, ip_mesh_num) # allocate HNA network get_api().allocate_ips(current_app.config['API_POOL_HNA'], r.id, r.email, r.hostname, prefix_len = session['prefix_len']) url = url_for(".wizard_activate", request_id=r.id, signed_token=r.gen_signed_token(), _external=True) send_email(session['email'], r.hostname, router, url) for k in ('email', 'router_id'): del session[k] return render_template('waiting_for_confirmation.html')
def removeSwitch(switch): """Remove the switch details from the database""" db = dbase.connect_mongodb() switches = db.switches sw = switches.find_one({'switch_name': switch}) if sw == None: print "Switch %s does not exist in Database" % switch return from_list = '*****@*****.**' to_list = str(sw['user']) mailer = email.ICEmail(from_list, to_list) subject = 'iLab - %s switch deleted from db' % switch body = "%s has been deleted from iLab database." % switch mailer.add_line(body) body = "Sorry if we have caused any inconvenience. We would be delighted to help resolve the issue and get the switch back in iLab." mailer.add_line(body) body = "Please feel free to contact/give feedback via the mailer [email protected]" mailer.add_line(body) body = '' mailer.add_line(body) body = "Wiki - http://wikicentral.cisco.com/display/PROJECT/iLab+-+Green+Lab" mailer.add_line(body) util.send_email(mailer=mailer, subject=subject) switches.remove({'switch_name': switch}) print "Switch %s has been removed from database" % switch return
def run(): """ Change the password for a user and set up a cron job to change it again based on the frequency """ # Since this is mostly a fire and forget script it needs # broad exception handling so whatever traceback gets generated # is sent out in the email msg = 'General Failure' success = 'Failure' db_info = get_cfg()['config'] reciever, sender = get_addresses(db_info) try: username, freq = arg_parser() old_pass = current_pass(db_info) new_pass = change_pass(old_pass) update_db(new_pass, db_info) update_cron(username, freq) msg = 'User: {0} password has been updated'.format(username) success = 'Successful' except Exception: msg = str(traceback.format_exc()) finally: send_email(sender, reciever, EMAIL_SUBJECT.format(success), msg)
def sweep(): to_check = [] bioguide = utils.flags().get('bioguide', None) if bioguide: possibles = [bioguide] else: possibles = current_bioguide.keys() for bioguide in possibles: if media_bioguide.get(bioguide, None) is None: to_check.append(bioguide) elif media_bioguide[bioguide]["social"].get(service, None) is None: to_check.append(bioguide) else: pass utils.mkdir_p("cache/social_media") writer = csv.writer(open("cache/social_media/%s_candidates.csv" % service, 'w')) writer.writerow(["bioguide", "official_full", "website", "service", "candidate", "candidate_url"]) if len(to_check) > 0: email_body = "Social media leads found:\n\n" for bioguide in to_check: candidate = candidate_for(bioguide) if candidate: url = current_bioguide[bioguide]["terms"][-1].get("url", None) candidate_url = "https://%s.com/%s" % (service, candidate) row = [bioguide, current_bioguide[bioguide]['name']['official_full'].encode('utf-8'), url, service, candidate, candidate_url] writer.writerow(row) print "\tWrote: %s" % candidate email_body += ("%s\n" % row) if email_enabled: utils.send_email(email_body)
def register(db): try: email = request.forms.email.strip() if db.query(model.User).filter_by(email=email).first(): return HTTPError(409, 'Conflict') user = model.User() user.email = email user.password = request.forms.password.strip() user.name = request.forms.name.strip() user.city = request.forms.city.strip() db.add(user) # create hmac verification token token = hmac.new(config.site_secret, user.email).hexdigest() subject = config.verification_email_subject body = template( 'mail_verification', email=user.email, site_name=config.site_name, site_url=config.site_url, token=token ) send_email(email, subject, body) except AssertionError: return HTTPError(400, 'Bad request')
def Handle(change, files): is_migration = False for filename in files: if filename.find('nova/db/sqlalchemy/migrate_repo/versions') != -1: is_migration = True if is_migration: print 'Sending email' utils.send_email('[CI] Patchset %s #%s' %(change['id'], change['number']), '*****@*****.**', NEW_PATCH_EMAIL % {'change_id': change['id'], 'number': change['number'], 'subject': change['subject'], 'name': change['owner_name'], 'url': change['url'], 'is_migration': is_migration, 'files_list': '\n '.join(files)}) cursor = utils.get_cursor() for dataset in ['nova_trivial_500', 'nova_trivial_6000', 'nova_user_001']: for constraint in ['mysql', 'percona']: w = workunit.WorkUnit(change['id'], change['number'], 'sqlalchemy_migration_%s' % dataset, 0, constraint) w.enqueue(cursor)
def register(db): try: email = request.forms.email.strip() if db.query(model.User).filter_by(email=email).first(): return HTTPError(409, 'Conflict') user = model.User() user.email = email user.password = request.forms.password.strip() user.name = request.forms.name.strip() user.city = request.forms.city.strip() db.add(user) # create hmac verification token token = hmac.new(config.site_secret, user.email).hexdigest() subject = config.verification_email_subject body = template('mail_verification', email=user.email, site_name=config.site_name, site_url=config.site_url, token=token) send_email(email, subject, body) except AssertionError: return HTTPError(400, 'Bad request')
def test_send_mail(mocker): # We monkeypatch smtplib.SMTP class mocksmtpcls = mocker.patch("smtplib.SMTP") # Expected result from_addr = "*****@*****.**" to_addr = "*****@*****.**" subject = "coucou" body = "comment ça va ?\nbisous" msg = 'To: %s\nFrom: %s\nSubject: %s\n\n%s' % ( to_addr, from_addr, subject, body) # noqa: E501 # Test happens here : send_email(from_addr, to_addr, subject, body) # noqa: E501 # Asserts: # As mocksmtpcls is a class, mockstpcls.return_value is the result # of creating an instance of this class, eg. the object smtp # We can assert the methode sendmail of this instance has been called once # assert_called without arguments : mocksmtpcls.return_value.sendmail.assert_called_once() # assert_called with arguments : mocksmtpcls.return_value.sendmail.assert_called_once_with( from_addr, [to_addr], msg)
def backup(**kwargs): # Avoid multiple instances of backup program me = singleton.SingleInstance(flavor_id=u'esxi-backup') # Obtain profile configuration if not u'profile_name' in kwargs: raise RuntimeError(u'Missing profile_name argument') profile_name = kwargs[u'profile_name'] if not profile_name in settings.ESXI_BACKUP_PROFILES: raise RuntimeError(u'No such profile "%s"' % profile_name) profile = settings.ESXI_BACKUP_PROFILES[profile_name] logger.info(u'Running backup profile "%s"' % (profile_name)) # Check if profile is currently active t = get_current_time() if not is_time_in_window(t, profile['backup_times']): logger.debug(u'Out of time range. Skipping backup run for profile.') return True with BackupProfile(profile) as bp: next_vm = bp.get_next_vm_to_backup() if next_vm: logger.info(u'Running backup for VM "%s"' % (next_vm)) bp.backup_vm(next_vm) bp.trim_backup_archives() if bp.email_report: utils.send_email( bp.gmail_user, bp.gmail_pwd, bp.from_field, bp.recipients, u'BACKUP OK %s' % (next_vm), log_stream.getvalue()) else: logger.info(u'No next VM to backup - Nothing to do.') return True
def change_password(request): user = User.objects.get(username=request.user) img = gravatar(user.email) if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! subject = "Master Faster Changed Password" message = "You recently changed your password." from_email = settings.EMAIL_HOST_USER to_email = User.objects.get(username=request.user).email send_email(subject, message, from_email, to_email) return HttpResponse( render(request, 'masterfaster/editconfirmation.html', { 'update': 'Password', 'img': img })) else: errors = [v[0] for k, v in form.errors.items()] context = { 'form': PasswordChangeForm(request.user), 'img': img, 'errors': errors } print(form.errors) return HttpResponse( render(request, 'registration/password_change_form.html', context)) else: form = PasswordChangeForm(request.user) context = {'form': form, 'img': img} return HttpResponse( render(request, 'registration/password_change_form.html', context))
def create(db, user): try: item = model.Restriction() item.title = request.forms.title.strip().capitalize() item.body = request.forms.body.strip() item.state = 'NEW' item.user = user item.user_name = request.forms.name.strip() item.user_city = request.forms.city.strip() item.voters.append(user) db.add(item) db.flush() if not user.admin: subject = config.restriction_created_email_subject body = template('mail_restriction_created', site_name=config.site_name, site_url=config.site_url, id=item.id, slug=slug(item.title)) send_email(config.site_email, subject, body) return {'id': item.id, 'slug': slug(item.title)} except AssertionError: return HTTPError(400, 'Bad request')
def check_email(message: Message): """ Обрабатывает введенный пользователем адрес электронной почты при регистрации :param message: сообщение пользователя с адресом электронной почты """ chat_id = message.chat.id if message.text in COMMANDS: return handle_cancel(message, 'регистрации') if not is_text(message) or not is_email_correct(message): instruction = bot.send_message(chat_id, INCORRECT_DATA_MSG) return bot.register_next_step_handler(instruction, check_email) state = get_state(chat_id) state.registering_user.code = str(int.from_bytes(os.urandom(2), 'little')) state.registering_user.email = message.text # ставим статус боту, пока письмо отправляется bot.send_chat_action(chat_id, 'typing') send_email(state.registering_user.email, 'Регистрация в боте BaumanLib', state.registering_user.code) state.last_email_date = datetime.now() state.email_attempt += 1 save_state(chat_id, state) instruction = bot.send_message(chat_id, REG_CODE_MSG) bot.register_next_step_handler(instruction, check_code)
def create(db, user): try: item = model.Restriction() item.title = request.forms.title.strip().capitalize() item.body = request.forms.body.strip() item.state = 'NEW' item.user = user item.user_name = request.forms.name.strip() item.user_city = request.forms.city.strip() item.voters.append(user) db.add(item) db.flush() if not user.admin: subject = config.restriction_created_email_subject body = template( 'mail_restriction_created', site_name=config.site_name, site_url=config.site_url, id=item.id, slug=slug(item.title) ) send_email(config.site_email, subject, body) return {'id': item.id, 'slug': slug(item.title)} except AssertionError: return HTTPError(400, 'Bad request')
def post(self): data = json.loads(request.data) print(data) name = data.get("name") email = data.get("email") subject = data.get("subject") phone = data.get("phone") message = data.get("message") # network = check_telco(phone[1:]) contact_instance = Contact(phone=phone, email=email, name=name, subject=subject, message=message) contact = contact_instance.save_to_db() if contact: # sending sms # sms_message = "Thank you for registering for the event. We will send you a reminder on the day, so you don't miss out. Love Hive" # sms_res = send_sms(phone, sms_message, network, STATUS_URL) # print("sms response to user", sms_res) # print("successfully saved") # sending email print("sending email...") destination = "*****@*****.**" email_message = f"{message}\n\nName: {name}\nEmail: {email}\nPhone Number: {phone}" subject = subject.upper() send_email(subject, destination, email_message) return jsonify(status="ok", data=data, error=False) else: print("an error occured....") return jsonify(status="ok", data=data, error=True)
def reject(db, user, id): try: item = db.query(model.Restriction).filter_by(id=id).one() item.state = 'REJECTED' item.approver = user db.flush() # email user the restriction was rejected reason = request.forms.reason.strip() if reason: tpl = 'mail_restriction_rejected_reason' else: tpl = 'mail_restriction_rejected' subject = config.restriction_rejected_email_subject body = template(tpl, site_name=config.site_name, site_url=config.site_url, id=item.id, slug=slug(item.title), reason=reason) send_email(item.user.email, subject, body) except NoResultFound: return HTTPError(404, 'Not found')
def proc_prevmonth(cfg): """ Put together metrics for the previous month then email the results out :param cfg: database connection info :type cfg: dict """ msg = '' emails = get_addresses(cfg) rng = date_range() subject = EMAIL_SUBJECT.format(rng[0], rng[1]) try: infodict = calc_dlinfo(LOG_FILE) msg = download_boiler(infodict) for source in ORDER_SOURCES: infodict = db_orderstats(source, rng[0], rng[1], cfg) infodict.update(db_scenestats(source, rng[0], rng[1], cfg)) infodict['tot_unique'] = db_uniquestats(source, rng[0], rng[1], cfg) infodict['who'] = source.upper() msg += ondemand_boiler(infodict) infodict = db_prodinfo(cfg, rng[0], rng[1]) msg += prod_boiler(infodict) except Exception: exc_msg = str(traceback.format_exc()) + '\n\n' + msg send_email(emails[1], emails[2], subject, exc_msg) msg = 'There was an error with statistics processing.\n' \ 'The following has been notified of the error: {0}.'.format(', '.join(emails[2])) finally: send_email(emails[1], emails[0], subject, msg)
def crawl_achatusag(request): if request.method == "POST": print("[achatusag] Started crawling website") item_links = [] for category_link in CATEGORIES: item_links.extend(_crawl_achatusag_category_2(category_link)) item_links_subcategory = [] for category_link in item_links: item_links_subcategory.extend( _crawl_achatusag_category(category_link)) print(f"[achatusag] Got {len(item_links_subcategory)} item links") if not item_links: send_warning_email(SENDGRID_API_KEY, SENDER_EMAIL, RECEIVER_EMAILS, "achatusag") return "No links were found on achatusag website" db = firestore.Client() comparison_result = add_and_compare_new_items(db, "achatusag", item_links) added_items, deleted_items = comparison_result[ "added"], comparison_result["deleted"] email_text = "" if added_items: _process_added_items(added_items) email_text += format_links_modified("Added", added_items) if email_text != "": send_email(SENDGRID_API_KEY, SENDER_EMAIL, RECEIVER_EMAILS, "Comparison results for achatusag", email_text) return email_text else: return "No new added or new deleted items found" else: return "This method is not supported"
def signup(): form = SignUpForm() if form.validate_on_submit(): acct = Account(company_name=form.company_name.data) db.session.add(acct) db.session.commit() user = User(acct_id=acct.id, first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_token() print_debug(url_for('auth.confirm', token=token, _external=True)) log_message(f'acct_id: {acct.id} just signed up') send_email(user.email, 'Confirm Your Account', 'confirm', '*****@*****.**', user=user, token=token) flash( 'You have been registered. A confirmation email is sent to your email address. \ You have 24 hours to verify your account.') login_user(user) return redirect(url_for('dash.index')) return render_template('auth/signup.html.j2', form=form)
def error(e): errors = { 400: 'Missing a required parameter.', 401: 'Credentials are invalid.', 403: 'Forbidden', 404: 'Page Not Found', 500: 'Something has gone wrong, please contact ' + SUPPORT_EMAIL, } error = traceback.format_exc() try: code = e.code current_app.logger.error(error) except Exception as e: current_app.logger.error(e) code = 500 if code == 500: utils.send_email( subject="Internal Server Error", message=error, from_email=SUPPORT_EMAIL, to_email=SUPPORT_EMAIL, ) error_message = errors.get(code, 'Unknown Error') if code == 404: if 'www' in request.url: url = request.url.lstrip('http://www.') url = 'http://' + url return redirect(url) return dumps_response(dict(message=error_message)), code
def main(ctx, **kwargs): import pdb pdb.set_trace() # pdb.set_trace() site_name = kwargs['site_name'] task_type = kwargs['task_type'] thread_number = kwargs['thread_number'] server_ip = kwargs['server_ip'] server_port = kwargs['server_port'] proxy_type = kwargs['proxy_type'] log_level = log_dict.get(kwargs['log_level'], logging.INFO) register = kwargs['register'] login = kwargs['login'] import pdb pdb.set_trace() if site_name is None or task_type is None: click.echo(ctx.get_help()) sys.exit(-1) # 初始化logger log_dir = '%s/%s_%s.log' % (settings.logs_dir_home, site_name, task_type) logger = utils.initLogger(log_dir, log_level) # 开始执行爬虫程序 mainCrawler = MainCrawler(logger, site_name, task_type, thread_number, server_ip, server_port, proxy_type, register, login) import pdb pdb.set_trace() try: mainCrawler.run() except: traceback.print_exc() utils.send_email(traceback.format_exc())
def send_email_to_owner(self, owner, nodes): preview, report = self.generate_report(owner, nodes) recipients = owner.split(",") cc = self.smtp["cc"].split(",") subject = self.generate_subject(owner, nodes, preview, report) content = self.generate_content(owner, nodes, preview, report) send_email(self.smtp, recipients, cc, subject, content, [report])
def post(self): data = json.loads(request.data) print(data) email = data.get("email") if Subscription.query.filter_by(email=email).first(): print("already subscribed.") return jsonify(status="ok", data="Already subscribed", error=True) subscription_instance = Subscription(email=email) subscription = subscription_instance.save_to_db() if subscription: # sending sms # sms_message = "Thank you for registering for the event. We will send you a reminder on the day, so you don't miss out. Love Hive" # sms_res = send_sms(phone, sms_message, network, STATUS_URL) # print("sms response to user", sms_res) # print("successfully saved") # sending email print("sending email...") destination = "*****@*****.**" email_message = f"Email: {email}" subject = "SUBSCRIPTION" send_email(subject, destination, email_message) return jsonify(status="ok", data=data, error=False) else: print("an error occured....") return jsonify(status="ok", data=data, error=True)
def crawl_southeastforklifts(request): if request.method == "POST": print("[southeastforklifts] Started crawling website") item_links = crawl_southeastforklifts_pages() db = firestore.Client() if not item_links: send_warning_email(SENDGRID_API_KEY, SENDER_EMAIL, RECEIVER_EMAILS, "southeastforklifts") return "No links were found on southeastforklifts website" comparison_result = add_and_compare_new_items(db, "southeastforklifts", item_links) added_items, deleted_items = comparison_result[ "added"], comparison_result["deleted"] email_text = "" if added_items: _process_added_items(added_items) email_text += format_links_modified("Added", added_items) if email_text != "": send_email(SENDGRID_API_KEY, SENDER_EMAIL, RECEIVER_EMAILS, "Comparison results for southeastforklifts", email_text) return email_text else: return "No new added or new deleted items found" else: return "This method is not supported"
def crawl_ceqinc(request): if request.method == "POST": print("[ceqinc] Started crawling website") items = _crawl_ceqinc() print(f"[ceqinc] Got {len(items)} items") if not items: send_warning_email(SENDGRID_API_KEY, SENDER_EMAIL, RECEIVER_EMAILS, "ceqinc") return "No links were found on ceqinc website" db = firestore.Client() comparison_result = add_and_compare_new_items(db, "ceqinc", items) added_items, deleted_items = comparison_result["added"], comparison_result["deleted"] email_text = "" if added_items: _process_added_items(items) email_text += format_links_modified("Added", added_items) if email_text != "": send_email(SENDGRID_API_KEY, SENDER_EMAIL, RECEIVER_EMAILS, "Comparison results for ceqinc", email_text) return email_text else: return "No new added or new deleted items found" else: return "This method is not supported"
def post(self, request): """ Function is used to create new object or value in table and return status. :param request: request header with user info for creating new object. :return: user info """ serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() context = { 'username': serializer.data['username'], 'site_url': constants.SITE_URL + constants.LOGIN } # render email html email_html_message = render_to_string( 'email_templates/register_success.html', context) utils.send_email(subject="WELCOME!", recipient=[serializer.data['email']], body=email_html_message) api_response = ApiResponse(status=1, data=serializer.data, message=constants.CREATE_USER_SUCCESS, http_status=status.HTTP_201_CREATED) return api_response.create_response() api_response = ApiResponse(status=0, message=get_error_message(serializer), http_status=status.HTTP_400_BAD_REQUEST) return api_response.create_response()
def send_trustees_email(election, subject, body): trustees = election.get_keyshares() footer_template = """ Your Trustee homepage for election "%s" is: %s Your password is: %s -- The Helios Voting System """ for trustee in trustees: footer = footer_template % ( election.name, reverse(trustee_home, args=[election.election_id, trustee.email ]), trustee.password) full_body = body + footer # send out the emails for the shares utils.send_email("%s <%s>" % ("Helios", "*****@*****.**"), ["%s <%s>" % (trustee.email, trustee.email)], subject, full_body)
def reject(db, user, id): try: item = db.query(model.Restriction).filter_by(id=id).one() item.state = 'REJECTED' item.approver = user db.flush() # email user the restriction was rejected reason = request.forms.reason.strip() if reason: tpl = 'mail_restriction_rejected_reason' else: tpl = 'mail_restriction_rejected' subject = config.restriction_rejected_email_subject body = template( tpl, site_name=config.site_name, site_url=config.site_url, id=item.id, slug=slug(item.title), reason=reason ) send_email(item.user.email, subject, body) except NoResultFound: return HTTPError(404, 'Not found')
def crawl_manuvic(request): if request.method == "POST": print("[manuvic] Started crawling website") response_text = request_( "GET", "https://www.manuvic.com/produits/chariots-elevateurs.html?cat=116&product_list_limit=100" ).text soup = BeautifulSoup(response_text, "html.parser") item_links = [ el.get("href") for el in soup.find_all("a", class_="product photo product-item-photo") ] db = firestore.Client() storage_client = storage.Client() if not item_links: send_warning_email(SENDGRID_API_KEY, SENDER_EMAIL, RECEIVER_EMAILS, "manuvic") return "No links were found on manuvic website" comparison_result = add_and_compare_new_items(db, "manuvic", item_links) added_items, deleted_items = comparison_result["added"], comparison_result["deleted"] email_text = "" if added_items: _process_added_items(storage_client, added_items) email_text += format_links_modified("Added", added_items) if email_text != "": send_email(SENDGRID_API_KEY, SENDER_EMAIL, RECEIVER_EMAILS, "Comparison results for manuvic", email_text) return email_text else: return "No new added or new deleted items found" else: return "This method is not supported"
def register(): if not current_user.is_anonymous: return redirect(url_for('main.index')) form = form_class.RegistrationForm() if form.validate_on_submit(): ki = gpg.import_keys(form.pgp.data) if not ki.fingerprints: fingerp = "--- NO VALID PGP ---" else: fingerp = ki.fingerprints[0] user = models.User(email=escape(form.email.data), name=escape(form.name.data), affiliation=escape(form.affiliation.data), pgp=escape(form.pgp.data), password=form.password.data, fingerprint=fingerp) models.db.session.add(user) models.db.session.commit() syslog.syslog(syslog.LOG_NOTICE, "New user registered: " + form.email.data) token = user.generate_confirmation_token() send_email(user.email, 'CVE-PORTAL -- Account Confirmation', '/emails/confirm', user=user, token=token) flash('A confirmation email has been sent to you by email.', 'info') return redirect('/login') else: if form.email.data is not None: pass # syslog.syslog(syslog.LOG_ERR, "Registering Failed: Email: " + form.email.data + " Name: " + form.name.data + " Affiliation: " + form.affiliation.data) return render_template("auth/register.html", form=form)
def ua_validated(db, world_socket, user, ups_acks, world_acks, email_socket, email_sender): # Check if result # If True, purchase pkg_id = user.shipId if user.result: pkg_info = q_pkg_id(db, pkg_id) # IF pkg is related to ups account, then turn to validate item_str = pkg_info[4] whnum = find_near_wh(db, pkg_info[2], pkg_info[3]) add_wh_info(db, pkg_id, whnum) # update_pkg_whinfo() ''' 1. Split item_str into purchase list (utils) 2. Assign warehouse info 3. Send world_buy ''' purchase_list = getListfromStr(item_str) update_pkg_status(db, 1, (pkg_id,)) world_buy(world_socket, whnum, purchase_list, world_acks) else: # If False, update status to cancel update_pkg_status(db, 9, (user.shipId,)) receiver = q_email_by_sid(db, pkg_id) pkg_status = 'CANCELLED since validation failed.' send_email(receiver, pkg_id, pkg_status, email_socket, email_sender)
def listen_ups(ups_socket, world_socket, db, world_acks, world_seqs, ups_acks, ups_seqs, email_socket, email_sender): print("=============== Start to listen UPS ===========\n") while True: try: response = my_recv(ups_socket) except Exception as e: print("---------------- UPS Recv Failure -------------\n") break if response is not None: command = UA_pb2.UtoACommand() command.ParseFromString(response) print("---------------- Receive from UPS -------------\n") print(command) print("-----------------------------------------------\n") for _ in command.ack: ups_acks.add(_) for user in command.usrVlid: # avoid repeated handle ack_back_ups(ups_socket, user.seqNum) if user.seqNum in ups_seqs: continue ups_seqs.add(user.seqNum) ua_validated(db, world_socket, user, ups_acks, world_acks, email_socket, email_sender) for to_load in command.loadReq: # avoid repeated handle ack_back_ups(ups_socket, to_load.seqNum) if to_load.seqNum in ups_seqs: continue ups_seqs.add(to_load.seqNum) threading.Thread(target=world_load, args=(db, world_socket, to_load.warehouseId, to_load.truckId, to_load.shipId, world_acks)).start() sid_plain_list = () for sid in to_load.shipId: sid_plain_list += (sid, ) update_truck_id(db, to_load.truckId, sid_plain_list) for delivered in command.delivery: # avoid repeated handle ack_back_ups(ups_socket, delivered.seqNum) if delivered.seqNum in ups_seqs: continue ups_seqs.add(delivered.seqNum) update_pkg_status(db, 8, delivered.shipId) receiver = q_email_by_sid(db, delivered.shipId) pkg_status = 'DELIVERED.' send_email(receiver, delivered.shipId, pkg_status, email_socket, email_sender) if command.disconnection: world_disconnect(world_socket) email_socket.quit() break
def send_email(self, email_template): self.save() send_email( "Alert confirmation", email_template, { 'object': self.content_object, 'id': int_to_base32(self.id), 'token': self.make_token(random.randint(0, 32767)), }, self.content_object.email)
def main(): engine = utils.get_db_engine() results = engine.execute( 'select * from results order by dateof desc limit 1').fetchone() prediction = results.prediction if prediction >= .6: utils.send_email('Take Action', 'Preemptive action may be necessary')
def send_account_update_email(account_id, url, token, email=None): account = models.Account.get(id=account_id) utils.send_email( account, 'Update your account', 'Visit <a href="%s">this link</a> to apply the pending changes to your account<br/><small>(If you are using our API, your account id is %i and your token is %s)</small>' % (url, account_id, token), to=email)
def send_resetpass_email(verifystring, email): subject = "Anwen 密码找回" verify_link = "%s/setpass?e=%s&k=%s" % (options.site_url, email, verifystring) verify_a = '<a href="%s">%s</a>' % (verify_link, verify_link) msg_body = "".join( ["<html>", "<p>Hi,</p>", "<p>请点击下面链接进行密码重设:</p>", verify_a.encode("utf-8"), options.msg_footer, "</html>"] ) utils.send_email(email, subject, msg_body)
def charge(request, amount): if request.method == 'POST': if amount == '0': return redirect('sales:checkout') u = User.objects.get(username=request.user) sale = Sale() #stripe charge success, instance = sale.charge(amount, request.POST['stripeToken'], u.email) if not success: print(instance) return HttpResponse("Error reading card.") else: try: billing = Billing.objects.get(user=u) except Billing.DoesNotExist: billing = Billing(user=u) billing.address = request.POST['args[billing_address_line1]'] billing.city = request.POST['args[billing_address_city]'] billing.state = request.POST['args[billing_address_state]'] billing.zipcode = request.POST['args[billing_address_zip]'] billing.country = request.POST['args[billing_address_country]'] billing.save() try: shipping = Shipping.objects.get(user=u) except Shipping.DoesNotExist: shipping = Shipping(user=u) shipping.address = request.POST['args[shipping_address_line1]'] shipping.city = request.POST['args[shipping_address_city]'] shipping.state = request.POST['args[shipping_address_state]'] shipping.zipcode = request.POST['args[shipping_address_zip]'] shipping.country = request.POST['args[shipping_address_country]'] shipping.save() sale.date = timezone.now() sale.amount = amount sale.user = u sale.save() request.session['sale_id'] = sale.id #Send Confirmation email. subject = "Master Faster Confirmation Email." message = "Thank you for shopping with Master Faster. \ Your payment successfully went through.\n\nConfirmation number: %s\n\n\ Shipping Address is:\n\n%s\n%s, %s\n%s %s\n\nBilling Address:\n\n%s\n%s, %s\n%s %s\n\n\ You will be receiving your receipt shortly.\n\n\ Please email us at %s to correct any order detail errors." % ( sale.charge_id, shipping.address, shipping.city, shipping.state, shipping.zipcode, shipping.country, billing.address, billing.city, billing.state, billing.zipcode, billing.country, settings.EMAIL_HOST_USER) from_email = settings.EMAIL_HOST_USER to_email = request.POST.get('emailAddress', '') send_email(subject, message, from_email, to_email) return HttpResponse('Successful Charge.') return HttpResponse("Invalid match.")
def main(): FILE_NAME = 'rates_to_watch.pkl' EMAIL = '' PASSWORD = '' arg_count = len(sys.argv) # Load trackers and record new rates to them. if arg_count == 1: # Check if tracking file exists. if os.path.isfile(FILE_NAME): rates_to_watch = utils.read_file(FILE_NAME) for rate in rates_to_watch: rate.add_rate(grab_rate(rate.get_currencies())) utils.write_file(FILE_NAME, rates_to_watch) report = generate_report(rates_to_watch) utils.send_email('Exchange Rate Report', report, EMAIL, EMAIL, PASSWORD) # Tracking file doesn't exist, tell user to add trackers. else: print("Error: No currencies are being tracked.") print("Please run the following command:") print("python currency_report.py CURRENCY1 CURRENCY2") print("eg. python currency_report.py GBP JPY") # Create new currency tracker. elif arg_count == 3: __, currency_1, currency_2 = sys.argv with open('currencies.txt') as file: valid_currencies = file.read() # Check if currencies are valid. if currency_1 in valid_currencies and currency_1 in valid_currencies: currencies = (currency_1, currency_2) new_tracker = trackers.CurrencyTracker(currencies, grab_rate(currencies)) # Edit existing tracker file. if os.path.isfile(FILE_NAME): rates_to_watch = utils.read_file(FILE_NAME) rates_to_watch.append(new_tracker) utils.write_file(FILE_NAME, rates_to_watch) # Create new tracker file. else: rates_to_watch = [new_tracker] utils.write_file(FILE_NAME, rates_to_watch) else: print("Error: Invalid currency codes.") else: print("Error: Invalid number of arguments. {count}" "argument(s).".format(count=arg_count))
def resend_confirmation(): token = current_user.generate_confirmation_token() send_email(current_user.email, 'CVE-PORTAL -- Account Confirmation', '/emails/confirm', user=current_user, token=token) syslog.syslog(syslog.LOG_WARNING, "User Resend a Confirmation Email to: " + current_user.email) flash('A new confirmation email has been sent to you by email.', 'info') return redirect(url_for('main.index'))
def send_email(self, request, email_template): self.save() send_email(request, "Alert confirmation", email_template, { 'object': self.content_object, 'id': int_to_base32(self.id), 'token': self.make_token(random.randint(0,32767)), }, self.content_object.email )
def check_board(board): global MIN_READ_VALUE global can_actuate_ao0 global can_actuate_ao1 while True: try: readings = board.read_all() readings_ai0 = readings['ai0'] readings_ai1 = readings['ai1'] readings_ai0 = readings_ai0[0] readings_ai1 = readings_ai1[0] print "Read " + str(readings_ai0) + " and " + str(readings_ai1) + " Current Number of Failures: " +\ str(board.sensor_down_count) if can_actuate_ao0 and readings_ai0 <= MIN_READ_VALUE: # Cannot actuate anymore in ai0 print "Cannot actuate anymore in ai0" can_actuate_ao0 = False # Send 0 to ao0 board.actuator.execute_task("ao0", 1, 0) elif (not can_actuate_ao0) and readings_ai0 >= MAX_READ_VALUE: # Can actuate back in ai0 print "Can actuate back in ai0" can_actuate_ao0 = True if can_actuate_ao1 and readings_ai1 <= MIN_READ_VALUE: # Cannot actuate anymore in ai1 print "Cannot actuate anymore in ai1" can_actuate_ao1 = False # Send 0 to ao1 board.actuator.execute_task("ao1", 1, 0) elif (not can_actuate_ao1) and readings_ai1 >= MAX_READ_VALUE: # Can actuate back in ai1 print "Can actuate back in ai1" can_actuate_ao1 = True # Reached the end of the loop without major problems board.sensor_down_count = 0 except Exception, e: print "Board is not connected!\n" + str(e) # sensor_down_count will only be -1 when a failure occurs with no correct behaviour after if board.sensor_down_count != -1: board.sensor_down_count += 1 if board.sensor_down_count == LIMIT_FAILS: utils.send_email("NI-USB Board", "The Board has been down for " + str(board.sensor_down_count) + " seconds!\nPlease check the connection as soon as possible") board.sensor_down_count = -1 print "Sended email" print board.sensor_down_count time.sleep(TIMER_STEP)
def send_joinus_email(email, name): subject = '欢迎来到 安问' msg_body = ''.join([ '<html>', '<p>Hi ', str(name), '</p>', '<p>欢迎注册 安问</p>', '<p>安问是一个创造和分享的社区,你将可以在这里分享打动你的东西,展示你的奇思妙想,交到志同道合的朋友,发现更多精彩</p>', options.msg_footer, '</html>', ]) utils.send_email(email, subject, msg_body)
def POST(self): i = web.input(email="") person = Person.find(email=i.email) if person: token = person.generate_reset_token() msg = render_template("email_password_reset", token=token) utils.send_email(to_addr=person.email, message=msg) #TODO: send email return render.reset_password(email=i.email, success=True) else: return render.reset_password(email=i.email, error=True)
def mail2project(self, message) : """relays an email message to a project""" # keep copy of original message for error handling original_message = email.message_from_string(message) #keep trac email : trac_mail = self.env.config.get('notification', 'smtp_replyto') # whether or not to email back on error email_errors = self.env.config.getbool('mail', 'email_errors', True) # lookup the message message = self.lookup(message) # get the handlers handlers = ExtensionPoint(IEmailHandler).extensions(self.env) _handlers = self.env.config.getlist('mail', 'handlers') if not _handlers: # default value _handlers = [ 'RemoveQuotes', 'ReplyToTicket', 'EmailToTicket' ] handler_dict = dict([(h.__class__.__name__, h) for h in handlers]) handlers = [handler_dict[h] for h in _handlers if h in handler_dict ] # handle the message warnings = [] #is this email treated ? email_treated = False for handler in handlers: if not handler.match(message) : continue try: email_treated = True message = handler.invoke(message, warnings) except Exception, e: # handle the error print "Exception in user code:" print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60 raise except EmailException, e: if email_errors and original_message['from']: subject = reply_subject(original_message['subject']) response = 'Subject: %s\n\n%s' % (subject, reply_body(str(e), original_message)) send_email(self.env, trac_mail, [ original_message['from'] ], response ) warnings = [] # clear warnings return else: raise
def send_joinus_email(email, name): subject = '欢迎来到『安问』' msg_body = ''.join([ '<html>', '<p>Hi ', name.encode('utf-8'), '</p>', '<p>欢迎注册『安问』</p>', '<p>『安问』是一个创造和分享的社区,你将可以在这里分享打动你的东西,展示你的奇思妙想,结交志同道合的朋友,发现更多精彩</p>', options.msg_footer, '</html>', ]) utils.send_email(email, subject, msg_body)
def send_confirm_email(first_name, email): if not current_app.config['SEND_EMAIL']: return None confirm_key = generate_confirmation_key() confirm_email_link = url_for('account.confirm_email', key=confirm_key, _external=True) message = confirm_email_template.format(first_name=first_name, application=current_app.config['APP_NAME'], confirm_email_link=confirm_email_link) send_email(current_app.config['EMAIL_FROM'], email, "Please confirm your {} account".format(current_app.config['APP_NAME']), message) return confirm_key
def send_reset_email(account): reset_key = generate_confirmation_key(n=128) PasswordReset.create(account=account, key=reset_key, created_at=datetime.now(), used=False) reset_link = url_for('account.reset_password', key=reset_key, _external=True) message = reset_password_template.format(first_name=account.first_name, application=current_app.config['APP_NAME'], reset_password_link=reset_link) if current_app.config['SEND_EMAIL']: send_email(current_app.config['EMAIL_FROM'], account.email, "Password reset requested for your {} account".format(current_app.config['APP_NAME']), message)
def external_signup(): if request.method == 'GET': user = request.args.get('user') if user: return render_template('signup.html', user=user) else: return render_template('signup.html') elif request.method == 'POST': try: start_time = time.time() if request.form['account_type'] == 'Residential': utils.send_email(['*****@*****.**'], request.form['first_name'] + ' ' + request.form['last_name'], utils.print_html(request.form.to_dict())) logger.info('New residential signup submitted: ' + request.form['first_name'] + ' '\ + request.form['last_name']) else: logger.info('New business signup submitted: ' + request.form['account_name']) db['web_signups'].insert(request.form.to_dict()) r = requests.post( 'http://www.bravoweb.ca/receive_signup', data=request.form.to_dict()) body = "Thanks for signing up with Empties to Winn. \ We will send a confirmation of your Dropoff date within a few business \ days. We can be reached at 1-888-YOU-WINN" requests.post( 'https://api.mailgun.net/v3/' + MAILGUN_DOMAIN + '/messages', auth=('api', MAILGUN_API_KEY), data={ 'from': FROM_EMAIL, 'to': [request.form['email']], 'subject': 'Empties to Winn Signup Confirmation', 'html': body } ) #elapsed = str(round(time.time() - start_time,1)) #logger.info('Time elapsed: ' + elapsed + 's') return body except Exception as e: logger.info(str(e), exc_info=True) return str(e)
def send_confirm_email(email): if not current_app.config["SEND_EMAIL"]: return None confirm_key = generate_confirmation_key() confirm_email_link = url_for("email_list.confirm_email", key=confirm_key, _external=True) message = confirm_email_template.format(application=current_app.config["APP_NAME"], confirm_email_link=confirm_email_link) send_email(current_app.config["EMAIL_FROM"], email, "Please confirm your mailing list subscription".format(current_app.config["APP_NAME"]), message) return confirm_key
def SendEmailToCommitor(build_info, commit_id): try: title = "Please review your commits" author = build_info["build"]["parameters"]["author"] mail_to = ["@".join([author,"microstrategy.com"])] content = render.render_email_for_commitor(commit_id, build_info["build"]["parameters"]) utils.send_email(content, title, mail_to) log.debug("author: %s\nmail_to: %s\n" % (author, mail_to)) return True except Exception, e: log.error(e) log.error("Failed to send email to commitor") return False
def send_client_ticket_reopening_email(request, ticket): send_email( request, _("Your ticket #%s was reopen") % (ticket.pk), ticket.agent.email, settings.DEFAULT_FROM_EMAIL, { 'ticket': ticket, 'submitter': ticket.submitter }, 'support_tickets/email/reopen_ticket_submitter.txt', 'support_tickets/email/reopen_ticket_submitter.html' )
def send_agent_comment_creation_email(request, ticket): send_email( request, _("New comment created"), ticket.agent.email, settings.DEFAULT_FROM_EMAIL, { 'ticket': ticket, 'submitter': ticket.submitter }, 'support_tickets/email/new_comment_submitter.txt', 'support_tickets/email/new_comment_submitter.html' )
def send_resetpass_email(verifystring, email): subject = 'Anwen 密码找回' verify_link = '%s/setpass?e=%s&k=%s' % ( options.site_url, email, verifystring) verify_a = '<a href="%s">%s</a>' % (verify_link, verify_link) msg_body = ''.join([ '<html>', '<p>Hi,</p>', '<p>请点击下面链接进行密码重设:</p>', verify_a.encode('utf-8'), options.msg_footer, '</html>', ]) utils.send_email(email, subject, msg_body)
def send_agent_ticket_creation_email(request, ticket): if ticket.agent != request.user: send_email( request, _("New ticket created"), ticket.agent.email, settings.DEFAULT_FROM_EMAIL, { 'ticket': ticket, 'agent': ticket.agent }, 'support_tickets/email/new_ticket_agent.txt', 'support_tickets/email/new_ticket_agent.html' )
def send(self): context = { 'user':self.email_address.user, 'domain': get_setting('DOMAIN'), 'site_name': get_setting('SITE_NAME'), 'username': self.email_address.user.username, 'token': self.key, 'protocol': get_setting('DEFAULT_PROTOCOL') } context['url'] = get_setting('ACTIVATION_URL').format(**context) from_email = get_setting('FROM_EMAIL') utils.send_email(self.email_address.email,from_email,context,'activation_email_subject.txt' ,'activation_email_body.txt') self.time_sent = timezone.now() self.save()