def run(self): msg = '''Viimeisin %s merkintä otettu %s päivää sitten. %s''' measurements = get_table('measurements') for setting in get_notification_intervals(): entry_type = setting['type'] interval = setting['interval_days'] print("Checking " + entry_type) entries = measurements.find(type=entry_type, order_by='-date') try: last_entry = entries.next() except: print("Cannot read records.") continue last_time = read_date_str(last_entry['date']) today = date.today() diff = today - last_time if diff.days > interval: print("No measurements in last %s days, notifying user." % interval) for address in mail_addresses: if address is not None: send_mail(address, msg % (entry_model[entry_type]['finnish'].lower(), str(diff.days), server_address)) else: print('OK')
def send_email(self, users, records): result = xbmcgui.Dialog().yesno( "Send email?", "Do you want to send {0} records to:".format(len(records)), ", ".join(['{0} <{1}>'.format(user[0], user[1]) for user in users]) ) if result: utils.send_mail(utils.construct_html_payload(records), utils.construct_plain_payload(records), users)
def __emailto(emails, bill_id, subj): if (emails): utils.send_mail( emails, '%s: %d' % (subj, bill_id), request.build_absolute_uri(reverse('bills.views.bill_view', kwargs={'id': bill_id})), )
def reset_code(): username = request.form.get("username") user = db.get_user(username) if not user: flash(messages.INVALID_USERNAME, "error") return redirect(url_for("index")) code = accounts.create_reset_code(username) url = "http://{0}{1}".format(request.headers.get("HOST"), url_for("reset", code=code)) tmpl = """ Greetings... Please click the following link to reset your password. {0} If you did not request this reset, please ignore this email and the code will automatically expire. Thanks! {1}""".format( url, config.APP_NAME ) utils.send_mail("Keymaker Password Reset", tmpl, [user.get("email")]) flash(messages.RESET_CODE_SENT, "success") return redirect(url_for("index"))
def login_forgotten_password(): if request.method == "POST": form = EmailForm(request.form) if form.validate(): email = form.data.get('email') if not resolve_user_by_email(email): flash(u'Nejprve si svůj e-mail zaregistrujte', 'warning') redirect(url_for('login_create_account')) raw_email = email email = base64.b64encode(email) token = md5("%s|%s" % (app.secret_key, email)).hexdigest() url = url_for( 'login_click_from_email_password', token=token, email=email, _external=True) if app.debug: flash(url, "debug") send_mail( u'Obnovení hesla', raw_email, "data/reset-password.md", url) return redirect(url_for('login_forgotten_verify')) else: form = EmailForm(request.args) return render_template('login_forgotten.html', form=form)
def daily_notifications(): """ sent notifications to user if 1 : ticket is open for more than 24 hrs 2 : ticket is assigned but not Closed in 24 hrs """ tickets = frappe.db.get_all("Ticket Escalation History", filters=[["status", "!=", "Closed"], ["status", "!=", "Deleted"]], fields=["*"]) for ticket in tickets: # ticket is raised but not yet assigned issue_doc = frappe.get_doc("Issue", ticket.ticket_id) args = { "user": get_fullname(issue_doc.raised_by) or "User", "email": issue_doc.raised_by, "action": "user_issue_notification", "issue": issue_doc } if ticket.raised_email_notification and not ticket.assigned_email_notification: raised_time = ticket.raised_email_notification_datetime if time_diff_in_hours(get_datetime().now(), raised_time) >= 24: # send user notification mail msg = "Your support ticket {ticket_id} is pending our representative will \ check the issue as soon as possible".format(ticket_id=ticket.ticket_id) args.update({"msg":msg}) send_mail(args, "[HelpDesk] Daily Notifications") elif ticket.assigned_email_notification and not ticket.status_closed_email_notification: assigned_time = ticket.assigned_email_notification_datetime if time_diff_in_hours(get_datetime().now(), assigned_time) >= 24: # send the user notification mail msg = "Your support ticket {ticket_id} is assigned to our support representative \ and issue will be solved as soon as possble".format(ticket_id=ticket.ticket_id) args.update({"msg":msg}) send_mail(args, "[HelpDesk] Daily Notifications")
def internal_error(error): '''Catch 500 errors and send custom message + alert email''' error_msg = {"msg": "Internal error - We are working on it!"} resp = app.make_response(jsonify(error_msg)) resp.status_code = 500 send_mail("Internal Error", "Internal generated for url %s" % request.url) return resp
def login_create_account(): if request.method == "POST": form = EmailForm(request.form) if form.validate(): email = form.data.get('email').lower() user_hash = resolve_user_by_email(email) if user_hash: flash( u'Účet s tímto e-mailem již existuje, ' u'chcete obnovit zapomenuté heslo?', 'warning') return redirect(url_for( 'login_forgotten_password', email=email)) raw_email = email email = base64.b64encode(email) token = md5("%s|%s" % (app.secret_key, email)).hexdigest() url = url_for( 'login_click_from_email', token=token, email=email, _external=True) if app.debug: flash(url, "debug") send_mail( u'Vytvoření účtu', raw_email, "data/verify-account.md", url) return redirect(url_for('login_email_verify')) else: form = EmailForm() return render_template('login_create_account.html', form=form)
def register_user(username, full_name, email, password): """Register new user Return value: User object Specific exceptions: DuplicateObjectError(objectclass = <class User>, field = 'username') - username already taken DuplicateObjectError(objectclass = <class User>, field = 'email') - e-mail already registered """ if User.objects.filter(email = email): raise exceptions.DuplicateObjectError(User, 'email') try: user = User.objects.create_user(username=username, email=email, password=password) except IntegrityError: raise exceptions.DuplicateObjectError(User, 'username') user.is_active = False user.save() user.userprofile.full_name = full_name user.userprofile.act_code = User.objects.make_random_password(length = 8) user.userprofile.save() send_mail([email], '[Koala] account activation', 'mail_activate.txt', { 'username': username, 'full_name': full_name, 'act_code': user.userprofile.act_code, 'activation_url': settings.ACTIVATION_URL, }) return user
def upload(): """ Uploads a file to the upload folder from the upload.html page """ if request.method == 'POST': ticket_number = request.args.get('ticket_number') if 'file' not in request.files: flash('No file part') return redirect(request.url) requested_file = request.files['file'] if requested_file.filename == '': flash('No selected file') return redirect(request.url) if requested_file and allowed_file(requested_file.filename): file_ext = requested_file.filename.rsplit('.', 1)[1] file_save_name = 'signedform_ticket_{}.{}'.format( ticket_number, file_ext ) file_save_path = os.path.join( APP.config['UPLOAD_FOLDER'], file_save_name ) requested_file.save(file_save_path) send_mail( APP, MAIL, "*****@*****.**", "[form upload] Creative Commons Consent Form | MeldeyDB Manager", " ", attachment=file_save_path ) return redirect(url_for('thankyou'))
def ticket_escallation(): """ Escalate Pending Support Tickets to higher authority """ query = """ SELECT * FROM `tabTicket Escalation History` WHERE status NOT IN ('Closed','Deleted') ORDER BY name""" records = frappe.db.sql(query, as_dict=True) if not records: return else: open_tickets = [] # get escalation settings records doctype = "Ticket Escalation Settings" docname = frappe.db.get_value("Ticket Escalation Settings",{"is_default":1}, "name") if not docname: frappe.throw("Default Escalation settings not found") esc_setting = frappe.get_doc(doctype, docname) assigned_tickets = [record for record in records if record.get("is_assigned")] not_assigned_tickets = [record for record in records if not record.get("is_assigned")] open_tickets = check_for_open_support_tickets(not_assigned_tickets, esc_setting) if open_tickets: args = get_open_tickets_details("Administrator", open_tickets) send_mail(args, "[HelpDesk][Open Tickets] HelpDesk Notifications") check_and_escalate_assigned_tickets(assigned_tickets, esc_setting)
def check_override(self): """ Checks override entries for validity. Mails "Override disparity" warnings, if that feature is enabled. Abandons the check if - override disparity checks are disabled - mail sending is disabled """ cnf = Config() # Abandon the check if override disparity checks have been disabled if not cnf.find_b("Dinstall::OverrideDisparityCheck"): return summary = self.pkg.check_override() if summary == "": return overridetemplate = os.path.join(cnf["Dir::Templates"], 'process-unchecked.override-disparity') self.update_subst() self.Subst["__SUMMARY__"] = summary mail_message = utils.TemplateSubst(self.Subst, overridetemplate) utils.send_mail(mail_message) del self.Subst["__SUMMARY__"]
def test_newsletteru(): send_mail( u'Barcamp Brno 2016 je již zítra', '*****@*****.**', 'data/newsletter-before.md') return 'done'
def _send_fail_mail(self, commands_result): config = self.project.config subject = ('Synthese deploy failure on {hostname} ' '(project: {project})'.format( hostname=socket.gethostname(), project=config.project_name)) body = commands_result.summary() utils.send_mail(config, config.mail_admins, subject, body)
def prod_maintainer(notes, upload): cnf = Config() changes = upload.changes whitelists = [ upload.target_suite.mail_whitelist ] # Here we prepare an editor and get them ready to prod... (fd, temp_filename) = utils.temp_filename() temp_file = os.fdopen(fd, 'w') temp_file.write("\n\n=====\n\n".join([note.comment for note in notes])) temp_file.close() editor = os.environ.get("EDITOR","vi") answer = 'E' while answer == 'E': os.system("%s %s" % (editor, temp_filename)) temp_fh = utils.open_file(temp_filename) prod_message = "".join(temp_fh.readlines()) temp_fh.close() print "Prod message:" print utils.prefix_multi_line_string(prod_message," ",include_blank_lines=1) prompt = "[P]rod, Edit, Abandon, Quit ?" answer = "XXX" while prompt.find(answer) == -1: answer = utils.our_raw_input(prompt) m = re_default_answer.search(prompt) if answer == "": answer = m.group(1) answer = answer[:1].upper() os.unlink(temp_filename) if answer == 'A': return elif answer == 'Q': return 0 # Otherwise, do the proding... user_email_address = utils.whoami() + " <%s>" % ( cnf["Dinstall::MyAdminAddress"]) changed_by = changes.changedby or changes.maintainer maintainer = changes.maintainer maintainer_to = utils.mail_addresses_for_upload(maintainer, changed_by, changes.fingerprint) Subst = { '__SOURCE__': upload.changes.source, '__CHANGES_FILENAME__': upload.changes.changesname, '__MAINTAINER_TO__': ", ".join(maintainer_to), } Subst["__FROM_ADDRESS__"] = user_email_address Subst["__PROD_MESSAGE__"] = prod_message Subst["__CC__"] = "Cc: " + cnf["Dinstall::MyEmailAddress"] prod_mail_message = utils.TemplateSubst( Subst,cnf["Dir::Templates"]+"/process-new.prod") # Send the prod mail utils.send_mail(prod_mail_message, whitelists=whitelists) print "Sent prodding message"
def __judge(self, rate): title = u"[{}%] {} {} {}".format( str(rate)[:5], self.price_single_list[self.current_stock][-1], self.current_status, STOCK[self.current_stock], ) logging.error(title) if abs(rate) > self.judge_line: send_mail(title.encode("utf-8"))
def send_stats(delta_days = 31): daily_stats = db.session.query(Stat).filter(Stat.date >= (datetime.today() - timedelta(days=delta_days))) msg = 'Date\t\tTotal\tVenant de l\'application\n' for stat in daily_stats: msg += "%s\t%s\t%s\n" % (stat.date, stat.total_counts, stat.counts_app) send_mail("OVC - Statistiques API", msg) sg = sendgrid.SendGridClient(app.config['EMAIL_CREDENTIALS'][0], app.config['EMAIL_CREDENTIALS'][1]) message = sendgrid.Mail()
def start_ex(self): self.sleep_time = 1 self.check_group = False while True: try: self.__search_in_group_topics(self.__get_latest_topic_list()) # self.__search_in_group_topics(self.__get_group_list('516876')) except Exception, e: logging.error(e) send_mail(str(e))
def mailto(request, id): ''' @param id: bill id ''' bill = models.Bill.objects.get(pk=int(id)) utils.send_mail( ['*****@*****.**'], 'Новый счет на подпись: %s' % id, 'Вам на подпись поступил новый счет: %s' % request.build_absolute_uri(reverse('bills.views.bill_view', kwargs={'id': bill.pk})), ) return redirect('bills.views.bill_view', bill.pk)
def test_send_mail(self): """Ensure the send_mail function works""" send_mail("Template 1", context=self.context, recipient_list=['*****@*****.**']) # Test that one message has been sent. self.assertEqual(len(mail.outbox), 1) # Verify that the subject of the first message is correct. self.assertEqual(mail.outbox[0].subject, 'Test 1 Subject *HELLO*') self.assertEqual(mail.outbox[0].body, "Test 1 body *WORLD*") self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
def __emailto(request, emails, bill_id, subj): ''' Send email to recipients @param emails:list - list of emails:str @param bill_id:int @param subj:str - email's Subj ''' if (emails): utils.send_mail( emails, '%s: %d' % (subj, bill_id), request.build_absolute_uri(reverse('bills.views.bill_view', kwargs={'id': bill_id})), )
def poslani_newsletteru(): i = 0 for mail in app.redis.smembers('newsletter'): i += 1 print mail app.redis.srem('newsletter', mail) send_mail( u'Barcamp Brno 2016 je již zítra', '', #mail, 'data/newsletter-before.md') return 'newsletter done {} emails'.format(i)
def post(self): ea = self.request.get("ea") existing_email = model.EarlyAdopter.query(model.EarlyAdopter.ea == ea).get() if not existing_email: ea = model.EarlyAdopter(ea = ea) ea.put() ea_id = ea.key.id() t = jinja_env.get_template("mailer.html") html = t.render(ea_id=ea_id) utils.send_mail(ea.ea, ea_id, html)
def recolor(): uploaded_files = request.files.getlist("files") colors = set(request.form.getlist("color")) email = request.form.get("email") greiged_files = [] for u_file in uploaded_files: f_name, f_extension = u_file.filename.split(".") for color in colors: if color: new_filename = f_name + "_%s." % color[1:] + f_extension greiged_files.append({"name": new_filename, "file": greige(u_file, color)}) send_mail(email, greiged_files) return ""
def notify(self, sender=None, body=None, recipient_name=None): if settings.DEBUG: return if not sender: sender = self.authmodif if not recipient_name and self.responsable_employe_id: recipient = self.responsable_employe.user recipient_name = "[%s %s]" % ( recipient.first_name, recipient.last_name) else: recipient_name = "[Tous]" recipients = User.objects.filter(id__in=self.workgroup_ids()) subject = u"%s %s" % (recipient_name, self.resume) send_mail(sender, recipients, subject, body)
def create_pago(sender, instance, created, *args, **kwargs): curso = instance.curso if created and instance.method == 'deposit': send_mail('curso_info', { 'curso': curso }, 'Informacion para realizar pago al %s de Mejorando.la INC' % curso.nombre, instance.email) if instance.charged and not instance.sent: vs = calculate(int(instance.quantity), curso.precio) vs['curso'] = curso vs['pago'] = instance send_mail('curso_pago', vs, 'Gracias por tu pago al %s de Mejorando.la INC' % curso.nombre, instance.email) instance.sent = True instance.save()
def broadcast_email(kind, status=None): if not hasattr(env, 'mail_class'): env.mail_class = send_mail() if kind == 'start': env.mail_class.send_start(status) elif kind == 'end': env.mail_class.send_end(status)
def escalate_ticket_to_higher_authority(esc_setting, record): """ TODO Escalate ticket to higher authority """ from utils import get_users_email_ids prev_role = record.get("current_role") prev_owner = record.get("current_owner") query = """ SELECT idx, role, time, parent FROM `tabTicket Escalation Settings Record` WHERE idx=(SELECT idx FROM `tabTicket Escalation Settings Record` WHERE parent='{parent}' AND role='{role}')-1 and parent='{parent}'""".format( parent=esc_setting.name, role=record.get("current_role") ) higher_auth = frappe.db.sql(query, as_dict=True)[0] if not higher_auth: frappe.throw("could not find higher role in escalation settings") else: user = None next_role = higher_auth.get("role") time = higher_auth.get("time") idx = higher_auth.get("idx") # check if department wise escalation is enabled is_dept_escalation = True if esc_setting.escalation_hierarchy[idx-1].is_dept_escalation else False result = select_user_to_escalate_ticket(next_role, is_dept_escalation, record) user = result.get("user") next_role = result.get("role") if result.get("role") else next_role # check if todo is created for the user if yes then update else create new create_update_todo_for_user(user, next_role, time, record.get("ticket_id"), prev_owner) # notify user regarding ticket escalation args = { "user": "******", "email": get_users_email_ids([prev_owner, user]), "action": "escalate_ticket", "issue": frappe.get_doc("Issue", record.get("ticket_id")), "esc": { "prev_owner": prev_owner, "prev_role": prev_role, "current_owner": user, "current_role": next_role } } send_mail(args, "[HelpDesk][Ticket Escalation] HelpDesk Notifications")
def register(): """ Registers a new user. """ username = request.args.get('username') email = request.args.get('email') password = request.args.get('password') if not all([username, email, password]): msg = 'You must provide a username, email, and password to register.' return jsonify(success=False, message=msg) existing_accounts = db.session.query(User)\ .filter(or_(User.username == username, User.email == email)).all() if existing_accounts: usernames = [u.username for u in existing_accounts] msg = 'There is already an account with this ' if username in usernames: msg += 'username' else: msg += 'email address' return jsonify(success=False, message=msg) new_user = User(username=username, email=email, active=False, password=sha256_crypt.encrypt(password)) new_user.insert() site_url = CONFIG.get('app', 'url') verify_link = '{0}/verify?id={1}'.format(site_url, new_user.id) subject = "Welcome to {0}!".format(CONFIG.get('app', 'name')) email_msg = '\n'.join([ 'Welcome! Your account has been created!', 'Please click the link below to verify your email address.', verify_link, '', '', 'Thank you for joining. We hope you enjoy your account.' ]) send_mail(new_user.email, subject, email_msg) return jsonify(success=True, message='Please check your email to verify your account.')
def action_handler(config=None): if not config: return "No config ; skipping" email_notify_users = config.get('notifications', {}).get('email') msg = '' # run commands msg += 'Commands: \n\n' for cmd in config.get('commands'): p = Popen(cmd, env=config.get('environment'), shell=True, bufsize=4096, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (stdin, stdout) = (p.stdin, p.stdout) msg += '{0}: \n{1}'.format(cmd, p.stdout.read()) msg += '----------\n' if email_notify_users: utils.send_mail('Launchpad Action: {0}'.format(config.get('name')), \ msg, email_notify_users) return 'Done'
def send_alert(self, indicator_id: int, indicator_name: str, session_id: int, distribution_list: List[str], alert_operator: str, alert_threshold: str, nb_records_alert: str, result_data: pandas.DataFrame): """Build the alert e-mail to be sent for the session.""" # Create csv file to send in attachment file_name = f'indicator_{indicator_id}_session_{session_id}.csv' file_path = os.path.dirname(__file__) + "/" + file_name result_data.to_csv(file_path, header=True, index=False) # Prepare e-mail body body = {} body['indicator_name'] = indicator_name body['alert_threshold'] = alert_operator + alert_threshold body['nb_records_alert'] = nb_records_alert body['log_url'] = 'http://' # To be updated # Send e-mail log.info('Send e-mail alert.') utils.send_mail(session_id, distribution_list, 'indicator', file_path, **body) os.remove(file_path) return True
def closed_ticket_notifications(): date = add_days(getdate(), -1) query = """select name, question, resolution_date from tabIssue where resolution_date between '{from_date}' and '{to_date}'""".format(from_date="%s 00:00:00" % date, to_date="%s 23:59:59" % date) names = frappe.db.sql(query, as_dict=True) tickets = {} if names: tickets = { "head": ["SR", "Ticket ID", "Question", "Resolution Date"], "total": len(names) } idx = 1 for tkt in names: tickets.update({ idx: [ idx, tkt.get("name"), tkt.get("question"), tkt.get("resolution_date") ] }) idx += 1 args = { "email": frappe.db.get_value("User", "Administrator", "name"), "user": "******", "action": "aggr_ticket_closed", "date": date, "ticket_detail": build_table(tickets) } send_mail(args, "[HelpDesk][Tickets Closed] HelpDesk Notifications")
def reset_code(): username = request.form.get('username') user = db.get_user(username) if not user: flash(messages.INVALID_USERNAME, 'error') return redirect(url_for('index')) code = accounts.create_reset_code(username) url = 'http://{0}{1}'.format(request.headers.get('HOST'), url_for('reset', code=code)) tmpl = """ Greetings... Please click the following link to reset your password. {0} If you did not request this reset, please ignore this email and the code will automatically expire. Thanks! {1}""".format(url, config.APP_NAME) utils.send_mail('Keymaker Password Reset', tmpl, [user.get('email')]) flash(messages.RESET_CODE_SENT, 'success') return redirect(url_for('index'))
def update_user_info(self, username: str, data: dict) -> dict: redis = Redis().r valid_fields = ["email"] valid_data = {} for field in valid_fields: if data.get(field): valid_data[field] = data[field] if valid_data.get("email") and not re.findall(r"\S@\S", valid_data.get("email")): return {"status_code": HTTPStatus.BAD_REQUEST, "status": False, "message": "email format error "} elif valid_data.get("email"): # rate limit user_email = valid_data.get("email") timeout_key = f"timeout-{user_email}" if redis.get(timeout_key): return {"status_code": HTTPStatus.TOO_MANY_REQUESTS, "status": False, "message": f"try again in {redis.ttl(timeout_key)}s"} verify_code = random.randint(10000, 99999) valid_data["email"] = {"verified": False, "address": user_email} # send email confirm subject = "[人人影视下载分享站] 请验证你的邮箱" body = f"{username} 您好,<br>请输入如下验证码完成你的邮箱认证。验证码有效期为24小时。<br>" \ f"如果您未有此请求,请忽略此邮件。<br><br>验证码: {verify_code}" redis.set(timeout_key, username, ex=1800) redis.hset(user_email, mapping={"code": verify_code, "wrong": 0}) redis.expire(user_email, 24 * 3600) send_mail(user_email, subject, body) self.db["users"].update_one( {"username": username}, {"$set": valid_data} ) return {"status_code": HTTPStatus.CREATED, "status": True, "message": "success"}
def test_app_dynamics_job(self): driver = self.driver driver.get("https://ais.usvisa-info.com/en-am/niv/users/sign_in") driver.find_element_by_id("user_email").clear() driver.find_element_by_id("user_email").send_keys(config.USER_EMAIL) driver.find_element_by_id("user_password").clear() driver.find_element_by_id("user_password").send_keys(config.PASSWORD) driver.find_element_by_xpath( "//form[@id='new_user']/div[3]/label/div").click() driver.find_element_by_name("commit").click() driver.get("https://ais.usvisa-info.com/en-am/niv/users/sign_in") driver.find_element_by_link_text("Continue").click() href = driver.find_element_by_xpath( "//a[contains(text(),'Pay Visa Fee')]").get_property('href') driver.get(href) try: self.assertEqual( "No Appointments Available", driver.find_element_by_xpath( "//div[@id='paymentOptions']/div[2]/table/tbody/tr/td[2]"). text) print('No Appointments Available in Armenia') except: send_mail(country='Armenia')
def process_queue(request): mails = Mail.objects.filter(approved=True, sent=None)\ .order_by('created')[:10] done = [] for mail in mails: mfrom = "%s %s <%s>" % (mail.mfrom.first_name, mail.mfrom.last_name, mail.mfrom.proxy_email) output = send_mail(mail=mail, message=mail.message, subject=mail.subject, mfrom=mfrom, mto=mail.mto.email, message_id=mail.message_id) mail.sent = datetime.now() mail.save() done.append((mail.subject, output)) return locals()
station_stored_infos['Latitude'] ]) slot["cars"].append({ "Name": station_name, "distance": distance, "description": car_desc }) new_slots[id_slot] = slot flag_new, new_slots = utils.compare_results(new_slots, old_slots) # save the new json file containing most recent slots locally or in Gdrive if "gdrive_results" in os.environ.keys(): gdrive_conn.save_byte_file(new_slots, results_fileid) else: json.dump(new_slots, json_file, indent=4, separators=(',', ': ')) # send mail if something new happened if flag_new: pprint.pprint(new_slots) # if we pass a list (stringyfied), convert it to list again to_email = os.environ["communauto_mailto"] if '[' in to_email: to_email = ast.literal_eval(to_email) utils.send_mail(new_slots, to_email) print("Mail sent") else: print("No changes occurs") print("End on script")
def update_profile(): """ 更新个人信息 { "uid":"用户ID", "data":{ "username":"******", "email":"电子邮件", "description":"个人简介", "changePassword":"******", "newPassword":"******", "banned":"是否已封禁", "rawAdmin":"是否是原始管理员", "permissions":[新的权限列表], "permission_group":"新的权限组" } } { "code":0,"message":"qwq" } """ import re if not session.get("uid"): return make_response(-1, message="请先登录") operator: User = User.by_id(session.get("uid")) user: User = User.by_id(request.form["uid"]) if user.id != operator.id and not permission_manager.has_permission( operator.id, "user.manage"): return make_response(-1, message="你无权进行此操作") data: dict = decode_json(request.form["data"]) regex = re.compile(config.USERNAME_REGEX) if not regex.search(data["username"]): return make_response(-1, message="用户名必须符合以下正则表达式: {}".format( config.USERNAME_REGEX)) if not re.compile(r"(.+)@(.+)").search(data["email"]): return make_response(-1, message="请输入合法的邮箱") if not permission_manager.has_permission(operator.id, "permission.manage"): if data["permission_group"] != user.permission_group: return make_response(-1, message="你没有权限更改用户所属权限组") if set(data["permissions"]) != set(user.permissions): return make_response(-1, message="你没有权限更改用户权限") user.permission_group = data["permission_group"] if db.session.query(PermissionGroup.id).filter( PermissionGroup.id == user.permission_group).one_or_none() is None: return make_response(-1, message="非法权限组ID") user.permissions = data["permissions"] # 移除缓存 from main import redis_connection_pool from redis import Redis client = Redis(connection_pool=redis_connection_pool) client.delete(f"hj2-perm-{user.id}") user.username = data["username"] user.description = data["description"] if data["changePassword"]: user.password = data["newPassword"] import time user.force_logout_before = int(time.time()) if data["banned"] != user.banned and not permission_manager.has_permission( operator.id, "user.manage"): return make_response(-1, message="你没有权限封禁/解封此用户") user.banned = data["banned"] if user.email != data["email"]: # 注册不需要邮箱验证的话,改邮箱也不需要 if config.REQUIRE_REGISTER_AUTH and not permission_manager.has_permission( session.get("uid"), "user.manage"): db.session.commit() from common.aes import encrypt from config import AUTH_PASSWORD, AUTH_TOKEN, CHANGE_EMAIL_EXPIRE_SECONDS from urllib.parse import quote_plus from common.datatypes import EmailChangeToken import time data = EmailChangeToken(uid=user.id, new_email=data["email"], token=AUTH_TOKEN, expire_after=int(time.time()) + CHANGE_EMAIL_EXPIRE_SECONDS) print("raw", encrypt(AUTH_PASSWORD, data.as_json())) encoded_data = quote_plus( quote_plus(encrypt(AUTH_PASSWORD, data.as_json()))) send_mail( config.CHANGE_EMAIL_AUTH_EMAIL.format( change_token=encoded_data), "更改邮箱", data.new_email) print("encoded", encoded_data) return make_response(0, message="数据已经更改成功。请前往新邮箱中点击确认。") else: user.email = data["email"] db.session.commit() # 检查邮箱相关 return make_response(0, message="操作完成")
def register(): """ 注册账号 参数: username:str 用户名 email:str 邮箱 password:str 密码 返回: { "code":0,//非0表示调用成功 "message":"qwq"//code非0的时候表示错误信息 } """ if session.get("uid") is not None: return make_response(-1, message="你已经登录了!") import re import utils if re.match(config.USERNAME_REGEX, request.form["username"]) is None: return make_response(-1, message="用户名必须满足以下正则表达式:" + config.USERNAME_REGEX) # if config.REQUIRE_REGISTER_AUTH: # user = db.session.query(User).filter( # User.username == request.form["username"]) # if user.count(): # user: User = user.one() # next_query = db.session.query(User).filter( # User.email == request.form["email"]) # if next_query.count() != 0 and next_query.one().username != request.form["username"]: # return make_response(-1, message="此邮箱已被使用") # if user.auth_token != "": # import uuid # user.auth_token = str(uuid.uuid1()) # send_mail(config.REGISTER_AUTH_EMAIL.format( # auth_token=user.auth_token), "验证邮件", request.form["email"]) # user.email = request.form["email"] # db.session.commit() # return make_response(-1, message=f"验证邮件已经发送到您的新邮箱{request.form['email']}") query = db.session.query(User).filter( or_(User.email == request.form["email"], User.username == request.form["username"])) if query.count(): return make_response(-1, message="此用户名或邮箱已被用于注册账号") from datetime import datetime # import uuid if config.REQUIRE_REGISTER_AUTH: # 需要邮箱验证 from config import AUTH_PASSWORD, AUTH_TOKEN, REGISTER_EMAIL_AUTH_EXPIRE_SECONDS from common.aes import encrypt, decrypt from common.datatypes import load_from_json, RegisterToken from urllib.parse import quote_plus import time data = RegisterToken(username=request.form["username"], email=request.form["email"], password=request.form["password"], expire_after=int(time.time()) + REGISTER_EMAIL_AUTH_EXPIRE_SECONDS, token=AUTH_TOKEN) encoded_token = encrypt(AUTH_PASSWORD, data.as_json()) # user.auth_token = str(uuid.uuid1()) print("token", encoded_token) send_mail(config.REGISTER_AUTH_EMAIL.format(auth_token=encoded_token), "验证邮件", request.form["email"]) # db.session.add(user) # db.session.commit() return make_response(-1, message="验证邮件已经发送到您邮箱的垃圾箱,请注意查收") else: # 不需要验证 user = User(username=request.form["username"], email=request.form["email"], password=request.form["password"], register_time=datetime.now()) db.session.add(user) db.session.commit() session.permanment = True session["uid"] = user.id import time session["login_time"] = str(int(time.time())) return make_response(0)
def send_email_2_shop(shop_id,order_no): try: order_sql=''' SELECT o.OrderNo, o.SubmitTime, o.SendTime, o.ConfirmTime, o.Freight, o.Receiver, o.SendAddress, o.Phone, o.Remark, (o.SaleMoney + o.Freight) AS SaleMoney, o.ShopID, b.Account, b.NickName, s.ShopName, s.ShopPhone, s.LinkMan, s.Mobile, s.ShopAddress, s.Email, c.ItemName AS Status FROM tb_order_s o LEFT JOIN tb_shopinfo_s s on o.ShopID = s.ShopID LEFT JOIN TB_BUYER b on b.BuyerID = o.BuyerID LEFT JOIN TB_CONSTENT_M c on c.TypeID = '009' and o.Status = c.ItemID WHERE o.OrderNo = %s ''' order_row=db.engine.execute(order_sql,order_no).fetchone() order=row_map_converter(order_row) detail_sql=''' SELECT o.OrderNo, o.SalePrice, o.DiscountPrice, SUM(o.Quantity) AS Quantity, o.GoodsID, g.GoodsName, g.ShopID, p.ThumbnailPath AS PhotoPath FROM TB_GOODSINFO_S g, TB_ORDERDETAIL_S o INNER JOIN TB_PHOTO p ON p.LinkID = o.GoodsID AND p.IsVisable = 1 AND p.IsChecked = 1 WHERE o.OrderNo = %s AND o.GoodsID = g.GoodsID GROUP BY o.OrderNo, o.SalePrice, o.DiscountPrice, o.GoodsID, g.GoodsName, PhotoPath ''' order_details= db.engine.execute(detail_sql,order_no) arr=[] goodIds=[] for row in order_details: temp_order=row_map_converter(row) if goodIds.index(temp_order['goods_id'])>0: continue else: goodIds.append(temp_order['goods_id']) arr.append(temp_order) order['order_detail']=arr temp_template=string.Template(''' 尊敬的${shop_name}店主:<br /> 您的店铺有新的订单,订单编号为:${order_no} <table width='100%' border='1' cellspacing='0' cellpadding='5' style='margin-bottom:5px;' bgcolor='#FFFFFF'> <tbody> <tr> <td width='80' class='biaoti' >收货人: ${reciever} </td> <td width='80' class='biaoti' >联系电话: ${phone} </td> <td width='80' class='biaoti' >配送地址: ${send_address} </td> </tr> </tbody> </table> <table width='100%' border='1' cellspacing='0' cellpadding='5' class='ordergl ordersearch'> <tbody> <tr> <td width='280' class='biaoti' align='center' colspan='2'>商品</td> <td width='70' class='biaoti'>单价(元)</td> <td width='50' height='26' class='biaoti'>数量</td> <td width='120' class='biaoti'>合计(元)</td> </tr> ''') mail_body=temp_template.substitute(shop_name=order['shop_name'],order_no=order['order_no'],reciever=order['receiver'],phone=order['phone'],send_address=order['send_address']) temp_template='' i=0 for order_detail in order['order_detail']: temp_template=string.Template('''<tr> <td width='80' class='orderpic hang'><a href='${base_url}/Display/ShopGoodsInfoPage?ShopID=${shop_id}&GoodsID=${goods_id}'><img src='${base_url}/${photo_path}' width='80px' height='80px' /></a></td> <td width='200' class='hang' style='text-align: left'><a href='${base_url}/Display/ShopGoodsInfoPage?ShopID=${shop_id}&GoodsID=${goods_id}'>${goods_name}</a></td> <td width='70' class='hang'><s>${sale_price}</s><br/>${discount_price}</td> <td width='50' class='hang'>${quantity}</td>" ''') mail_body+=temp_template.substitute(base_url='http://www.yuanbangshop.com',shop_id=order['shop_id'],goods_id=order_detail['goods_id'],photo_path=order_detail['photo_path'],goods_name=order_detail['goods_name'],sale_price=order_detail['sale_price'],discount_price=order_detail['discount_price'],quantity=order_detail['quantity']) if i==0: temp_template=string.Template(''' <td width='120' class='rowspan' rowspan='${count}'>${sale_money}<br/>(含运费:${freight})</td>''') mail_body+=temp_template.substitute(count=len(order['order_detail']),sale_money=order['sale_money'],freight=order['freight']) i=i+1 mail_body+='</tr>' mail_body+='''</tbody> </table><table width='100%' border='1' cellspacing='0' cellpadding='5' style='margin-bottom:5px;' bgcolor='#FFFFFF'><tbody> <tr><td width='80' class='biaoti' >备注:''' if order['remark']: mail_body+=order['remark'] else: mail_body+="无" param=base64.encodestring(order['email']+order['shop_name']) temp_template=string.Template('''</td></tr></tbody></table> 请点击下列链接进行操作。<a href='${base_url}/ShopCenterManage/OrderListPage?p=${param}'>${base_url}/ShopCenterManage/OrderListPage?p=${param}</a> <br>(如果上面不是链接形式,请将地址手工粘贴到浏览器地址栏再访问)<br><br>此邮件为系统邮件,请勿直接回复''') mail_body+=temp_template.substitute(base_url='http://www.yuanbangshop.com',param=param) send_mail([order['email']], '[远邦邻里网] 订单提醒邮件', mail_body) except Exception,e: current_app.logger.exception(e)
def run(self): """ Runs every X seconds, the main run loop """ last_run = self.find_last_run_ingest("ReportNotifier") last_personcourse = self.find_last_run_ingest("PersonCourse") if self.finished_ingestion("PersonCourse") and \ last_run < last_personcourse: reports = self.get_report_schedule() for report in reports: report_files = [] # run the conditional reports - they don't have dates if report['trigger'] == 'CONDITIONAL': print("Running Conditional Report: " + report['report_name']) # get queries queries = self.get_query(report_code=report['report_code']) for dbquery in queries: # its conditional so run it if dbquery['type'] == report['trigger']: # execute the conditional query and get data data = self.get_results(query=dbquery['query']) if len(data) > 0: # export the file report_file = self.report2csv( report['report_code'], data) report_files.append(report_file) else: print("No Data (report not sent): " + dbquery['description']) # send the email and file if we have files if len(report_files) > 0: print("Sending Email: " + dbquery['description']) email_data = json.loads(report['email']) for path in report_files: file_list = """<blockquote><blockquote>{0}</blockquote></blockquote>""".format( os.path.basename(path)) html = "{0} <br/><br/>" \ "The following report (attached) was generated by AdX Analytics on {1}: <br/> " \ "<blockquote><strong>{2}</strong></blockquote> " \ "<blockquote>Attached files:</blockquote> " \ "{3}<br/><br/>" \ "{4}".format(email_data['msg_leader'], str(datetime.now().strftime("%d/%m/%Y")), dbquery['description'], file_list, email_data['msg_sig']) # to = email_data['to_email'] if "dev" in report_file: # send only to from address to = [email_data['from_email']] cc = [] else: to = email_data['to_email'] cc = email_data['cc_email'] # send the email utils.send_mail(send_from=email_data['from_email'], send_to=to, cc_to=cc, subject=report['report_name'] + ' - ' + str(datetime.now()), text=html, files=report_files) else: # run the CALENDAR reports pass utils.log("FINISHED REPORT NOTIFIER") self.save_run_ingest() pass
def main(): try: dim = int(SYS.argv[1]) num_games = int(SYS.argv[2]) mode = int(SYS.argv[3]) if mode: base = SYS.argv[4] mode2 = int(SYS.argv[5]) if mode2: base2 = SYS.argv[6] else: mode2 = int(SYS.argv[4]) if mode2: base2 = SYS.argv[5] if mode and mode2: file_num = SYS.argv[len(SYS.argv) - 1] DISPLAY = False TRAINING = True except: dim = 3 #input("Size of grid: ") num_games = input("How many games: ") mode = input("Player 1 is?\n You (0) | Minimax (1): ") if mode: base = raw_input("Minimax bonus depth: ") mode2 = input( "Who are you playing?\n ShallowBlue AI (0) | Minimax (1): ") if mode2: base2 = raw_input("Minimax bonus depth: ") if mode and mode2: file_num = raw_input("Write data to which file? (#Depth1Depth2): ") DISPLAY = True TRAINING = False numMoves = 2 * (dim**2 + dim) if mode == 1: player1 = Minimax(dim, base, True) elif mode == 0: player1 = Player("Human") else: print "Unknown command." if mode2 == 1: player2 = AI = Minimax(dim, base2, False) elif mode2 == 0: player2 = AI = NN.NNet(numMoves, dim) try: weight_params = map(int, np.loadtxt('weight_params.txt').tolist()) print "Loaded layers - " + str( weight_params[:len(weight_params) - 1]) except: print "Run Trainer.py to create ShallowBlue." raise SystemExit else: print "Unknown command." Trainer1 = Trainer(numMoves, dim, player1) Trainer2 = Trainer(numMoves, dim, player2) G = BD.BoxesDots(dim, [player1, player2]) for i in range(num_games): turns = random.randint(0, 1) if DISPLAY == True: print G.players[turns].getName() + " starts\n" G.display_game() # GAME LOOP while G.game_status(): cPlayer = G.players[turns % 2] check = cPlayer.getScore() G.turn(cPlayer) new_state = copy.deepcopy(G.game_state) # BREAKING CONNECTION if cPlayer == player1: Trainer1.record(G.old_state, new_state) else: Trainer2.record(G.old_state, new_state) if DISPLAY == True: print cPlayer.getName() + " your move" print cPlayer.getName() + " move - " + str(cPlayer.last_move) G.display_game() print cPlayer.getName() + " your score is " + str( cPlayer.getScore()) + "\n" print "---- Next Move ----" if check == cPlayer.getScore(): turns += 1 G.show_results() if i % (round(num_games / 3.0) + 1) == 0 and TRAINING: # ARTIFICIAL DATA IS BEING CREATED progress = str(round((float(i) / num_games) * 100)) + "% completed " + file_num + ".\n" with open('{0}_progress.txt'.format(file_num), 'a') as f: f.write(progress) UTIL.send_mail(progress) time.sleep(5) if mode and mode2: if list(base)[:3] == ["S", "E", "T"]: if player2.getScore() > player1.getScore(): Trainer2.write_record(file_num) print "Game recorded in \"move_record3#" + str( file_num) + "\"" else: print "Game not logged" elif player1.getScore() > player2.getScore(): print "Game recorded in \"move_record3#" + str(file_num) + "\"" Trainer1.write_record(file_num) else: print "Game recorded in \"move_record3#" + str(file_num) + "\"" Trainer2.write_record(file_num) elif not mode: if player1.getScore() > AI.getScore(): print "Ehh. lucky" print "Game recorded in \"move_record3#H\"" Trainer1.write_record("Human-Conquests") else: print "Nice try, Human." print "Game logged in \"move_record3#AI-Conquests.txt\"" Trainer2.write_record("AI-Conquests") else: if player1.getScore() > AI.getScore(): print "Game recorded in \"move_record3#SB-L-MM.txt\"" Trainer1.write_record("SB-L-MM") else: print "HE DID IT!!" print "Game recorded in \"move_record3#SB-W-MM.txt\"" Trainer2.write_record("SB-W-MM") Trainer1.clear_record() Trainer2.clear_record() G.reset() if TRAINING: UTIL.send_mail("Finished " + file_num + ".") print "Done playing." print "Exiting..."
fdays = [] for e in soup.findAll("p", {"class": "fcondition"}): fconds.append(e.text) for e in soup.findAll("p", {"class": "fday"}): fdays.append(e.text) for e in soup.findAll("span", {"class": "cdate"}): cdates.append(e.text) news = soup.find("div", {"class": "warning"}).findChildren() news = [n.text for n in news] data = list(zip(fconds,fdays+cdates)) #for i, d in enumerate(data): #print(i, d) #print('[x]', len(fconds), len(cdates), len(fdays)) info = {'general':data[0][0], 'portlouis':data[7][0], 'headline':news[0]} headline = decide_headline(info['general']) #print(info, headline) with open('subs.txt', 'r') as f: for mail in f: send_mail(mail, headline, template('base.html').render(news=info['headline'], general=info['general']))
def generate(self): auth_code = self.request.get("code") file_name = self.request.get("file_name") receipient_email = self.request.get("receipient_email") user = User().get(code=auth_code)[0] token_url = "https://api.devexhacks.com/oauth2/token?" request_params = { "client_id": os.environ["co_client_id"], "client_secret": os.environ["co_secret"], "grant_type": "client_credentials", } urlencoded_params = urllib.urlencode(request_params) token_response = urlfetch.fetch(url=token_url + urlencoded_params, method="POST", deadline=10) token_content = json.loads(token_response.content) request_header = { 'Authorization': 'Bearer {}'.format(token_content["access_token"]), } if not user.owner_id: address = json.loads(user.address) address.update({"streetAddress": address["addressLine1"]}) del address["addressLine1"] request_body = { "ownerIdInSourceSystem": user.email, "ownerDetails": { "phoneNumber": user.phone, "email": user.email, "dateOfBirth": user.dob, "individual": { "firstName": user.first_name, }, "address": address, } } url = 'https://api.devexhacks.com/vault/owner/match' response = urlfetch.fetch(url=url, payload=json.dumps(request_body), method="POST", headers=request_header) response_content = json.loads(response.content) user.owner_id = response_content["ownerId"] user.put() url = 'https://api.devexhacks.com/vault/assets' request_body = { "owners": [{ "ownerId": user.owner_id }], "assetName": file_name } response = urlfetch.fetch(url=url, payload=json.dumps(request_body), method="POST", headers=request_header) response_content = json.loads(response.content) vault_entry = Vault() vault_entry.add( email=user.email, owner_id=user.owner_id, file_id=response_content["assets"][0]["assetId"], file_name=file_name, ) print response_content["assets"][0]["assetId"] body_html = """<a href="{}">Upload here</a>""".format( "/".join(self.request.url.split('/')[:-1]) + "/upload?asset_id=" + response_content["assets"][0]["assetId"]) utils.send_mail( receiver_email=receipient_email, body=body_html, subject="{} {} asked you to Upload file to Drop Lock".format( user.first_name.lower().title(), user.last_name.lower().title()))
<td style="text-align:center; font-size:30px">{}</td> </tr> </tbody> </table> <br> Find attached, log file and some screenshots of your bot at work 😆 <br><br> Thanks for using our service ! <br><br> Ken<br> [email protected]""".format(Pinsta_username, BotProcess, CCYYMMDD, Ptags, Pcomments, Rlikes, Rcomments, Rfollows) body = body_html.replace("{{HTML_TO_REPLACE}}", message) file_list = [ r'/home/kdresdell/Documents/InstaPy/logs/{}/screenshot_1.png'.format( Pinsta_username), r'/home/kdresdell/Documents/InstaPy/logs/{}/screenshot_2.png'.format( Pinsta_username), r'/home/kdresdell/Documents/InstaPy/logs/{}/screenshot_3.png'.format( Pinsta_username), r'/home/kdresdell/Documents/InstaPy/logs/{}/general.log'.format( Pinsta_username), ] send_mail([Pemail], 'Your Inst@Bot process is done...', body, file_list)
def qr_callback(uuid, status, qrcode): send_mail(qrcode)
def register(): """ 注册账号 参数: username:str 用户名 email:str 邮箱 password:str 密码 返回: { "code":0,//非0表示调用成功 "message":"qwq"//code非0的时候表示错误信息 } """ if config.DISABLE_REGISTER: return make_response(-1, message="注册已停用") if config.USE_PHONE_WHEN_REGISTER_AND_RESETPASSWD: return make_response(-1, message="当前不使用邮箱注册") if session.get("uid") is not None: return make_response(-1, message="你已经登录了!") import re import utils if re.match(config.USERNAME_REGEX, request.form["username"]) is None: return make_response(-1, message="用户名必须满足以下正则表达式:" + config.USERNAME_REGEX) query = db.session.query(User).filter( User.username == request.form["username"]) if query.count(): return make_response(-1, message="此用户名或邮箱已被用于注册账号") from datetime import datetime # import uuid hasher = argon2.PasswordHasher() password_hash = hasher.hash(request.form["password"]) if config.REQUIRE_REGISTER_AUTH: # 需要邮箱验证 from config import AUTH_PASSWORD, AUTH_TOKEN, REGISTER_EMAIL_AUTH_EXPIRE_SECONDS from common.aes import encrypt, decrypt from common.datatypes import load_from_json, RegisterToken from urllib.parse import quote_plus import time data = RegisterToken(username=request.form["username"], email=request.form["email"], password=password_hash, expire_after=int(time.time()) + REGISTER_EMAIL_AUTH_EXPIRE_SECONDS, token=AUTH_TOKEN) encoded_token = encrypt(AUTH_PASSWORD, data.as_json()) # user.auth_token = str(uuid.uuid1()) print("token", encoded_token) send_mail( config.REGISTER_AUTH_EMAIL.format( auth_token=quote_plus(quote_plus(encoded_token))), "验证邮件", request.form["email"]) # db.session.add(user) # db.session.commit() return make_response(-1, message="验证邮件已经发送到您邮箱的垃圾箱,请注意查收") else: # 不需要验证 user = User(username=request.form["username"], email=request.form["email"], password=password_hash, register_time=datetime.now()) db.session.add(user) db.session.commit() session.permanment = True session["uid"] = user.id import time session["login_time"] = str(int(time.time())) return make_response(0)
def execute_task(task_id, is_show=False, is_export=False): """ 执行任务 parasm: task_id: TasksModel.task_no """ dt_now = datetime.datetime.now() if is_show: ex_type = 1 elif is_export: ex_type = 2 else: ex_type = 3 from application import app with app.app_context(): current_app.logger.info(f"TaskID: {task_id}正在执行..") task_obj = TasksModel.query.filter_by(task_no=task_id, is_deleted=False).first() if not task_obj: errmsg = "TaskID: {0} 执行失败, ID错误或已被删除".format(task_id) try: send_ding_errmsg(errmsg=errmsg, task_id=task_id) except: pass current_app.logger.error(errmsg) if is_show: return { "template": "db_err.html", "data": { "errmsg": str(errmsg) } } return project = task_obj.project sql_list = project.sql_model.all() task_type = project.task_type tag = None data = dict() # 根据不同任务类型处理 if task_type.type_id == 1: tag, data = handle_one_sql(sql_list) elif task_type.type_id == 2: tag, data = handle_o2o_sql(sql_list) elif task_type.type_id == 3: tag, data = handle_o2m_sql(sql_list) if not tag: try: send_ding_errmsg(errmsg=str(data), task_id=task_id, params=sql_list) except: pass current_app.logger.error(data) # 日志 write_task_log(ex_type, task_obj, False, str(data), dt_now) if is_show: return { "template": "db_err.html", "data": { "errmsg": str(data) } } return # 处理自定义函数的字段(目前根据字段名做处理) need_handle_dict = dict() field_list = data["field_list"] for k, v in DMS.default_functions().items(): for i in field_list: if k in i: i_index = field_list.index(i) i = i.split(k)[1].strip(" ").strip(":").strip(" ") data["field_list"][i_index] = i need_handle_dict[i_index] = v data_list = list(data["data_list"]) for i_i, i in enumerate(data_list): for k, v in need_handle_dict.items(): i = list(i) try: i[k] = v(i[k]) except: pass data_list[i_i] = i data["data_list"] = data_list current_app.logger.info(f"TaskID: {task_id}执行完成..") if is_show: write_task_log(ex_type, task_obj, True, "查询成功", dt_now) return {"template": "sql_ret.html", "data": data} elif is_export: ret_msg = "执行成功" status = True try: file_name = "{0}-{1}.xlsx".format(str(int(time.time())), valdate_code()) file_name = save_file(1, data, file_name) ret_html = "<a href='/dms/v1/down_file/{0}'>点击下载</a>".format( file_name) except Exception as e: ret_msg = str(e) status = False write_task_log(ex_type, task_obj, status, ret_msg, dt_now, file_name=file_name) return ret_html else: ret_msg = "发送成功" status = True current_app.logger.info("准备发送邮件..") # 发送邮件 task_log_obj = None try: file_name = "{0}-{1}-{2}.xlsx".format( project.name, str(datetime.datetime.now()).split()[0], valdate_code()) file_name = save_file(1, data, file_name) task_log_obj = write_task_log(ex_type, task_obj, status, "执行成功", dt_now, file_name=file_name) down_url = "http://{0}/dms/v1/down_file/{1}".format( current_app.config['MAIL_DOWN_HOST'] or redis.client['ServerHost'].decode(), file_name) mail_content = f"需求备注: {project.comments or '无'}\n下载地址: {down_url}" send_mail(title=project.name, content=mail_content, user_mail_list=project.user_mail_list.split(",")) current_app.logger.info("发送成功..") except Exception as e: ret_msg = str(e) status = False write_task_log(ex_type, task_obj, status, ret_msg, dt_now, project.user_mail_list, log_obj=task_log_obj) return True
# -*- coding: utf-8 -*- import utils import traceback from tweet_func import * def tweet(): api = auth_twitter() print("画像を検索") tweet_ranking(api) if __name__ == '__main__': try: tweet() except (Exception, tweepy.error.TweepError) as e: traceback.print_exc() utils.send_mail("An error has occurred.", traceback.format_exc()) raise e except: traceback.print_exc() utils.send_mail("An error has occurred.", traceback.format_exc())
# スクリーンショット保存ディレクトリ生成 SAVE_DIR = '%s/%s/%s' % (os.environ.get('SCREENSHOT_DIR'), START.strftime('%Y-%m'), START.strftime('%Y-%m-%d')) pathlib.Path(SAVE_DIR).mkdir(parents=True, exist_ok=True) crawler.access_to_sp(SAVE_DIR) # PUT response = api_client.call_lambda('putSocial', { 'dateOfAccess': WORK_DATE, 'result': crawler.RESULTS.fields(), }) put_success = True if response['ResponseMetadata'][ 'HTTPStatusCode'] == 200 else False MAIL_BODY = MAIL_TEMPLATE % ( WORK_DATE, '成功' if crawler.RESULTS.slot.get('success') else '失敗', '成功' if crawler.RESULTS.roulette.get('success') else '失敗', crawler.RESULTS.roulette.get('count') if crawler.RESULTS.roulette.get('count') else 0, '成功' if crawler.RESULTS.scratch.get('success') else '失敗', '成功' if put_success else '失敗', ) utils.send_mail(START, os.environ.get('MAIL_TO_ADDRESS'), 'ソーシャル関連ページアクセス結果通知', MAIL_BODY) utils.LOGGER.info('%s 処理終了' % WORK_DATE)
def add_comment(self, captcha: str, captcha_id: int, content: str, resource_id: int, ip: str, username: str, browser: str, parent_comment_id=None) -> dict: returned = {"status_code": 0, "message": ""} # check if this user is blocked reason = self.is_user_blocked(username) if reason: return {"status_code": HTTPStatus.FORBIDDEN, "message": reason} if check_spam(ip, browser, username, content) != 0: document = { "username": username, "ip": ip, "date": ts_date(), "browser": browser, "content": content, "resource_id": resource_id } inserted_id = self.db["spam"].insert_one(document).inserted_id document["_id"] = str(inserted_id) SpamProcessMongoResource.request_approval(document) return {"status_code": HTTPStatus.FORBIDDEN, "message": f"possible spam, reference id: {inserted_id}"} user_group = self.db["users"].find_one( {"username": username}, projection={"group": True, "_id": False} ) if not user_group: # admin don't have to verify code verify_result = CaptchaResource().verify_code(captcha, captcha_id) if not verify_result["status"]: returned["status_code"] = HTTPStatus.BAD_REQUEST returned["message"] = verify_result["message"] return returned exists = self.db["yyets"].find_one({"data.info.id": resource_id}) if not exists: returned["status_code"] = HTTPStatus.NOT_FOUND returned["message"] = "资源不存在" return returned if parent_comment_id: exists = self.db["comment"].find_one({"_id": ObjectId(parent_comment_id)}) if not exists: returned["status_code"] = HTTPStatus.NOT_FOUND returned["message"] = "评论不存在" return returned basic_comment = { "username": username, "ip": ip, "date": ts_date(), "browser": browser, "content": content, "resource_id": resource_id } if parent_comment_id is None: basic_comment["type"] = "parent" else: basic_comment["type"] = "child" # 无论什么评论,都要插入一个新的document inserted_id: str = self.db["comment"].insert_one(basic_comment).inserted_id if parent_comment_id is not None: # 对父评论的子评论,需要给父评论加children id self.db["comment"].find_one_and_update({"_id": ObjectId(parent_comment_id)}, {"$push": {"children": inserted_id}} ) self.db["comment"].find_one_and_update({"_id": ObjectId(inserted_id)}, {"$set": {"parent_id": ObjectId(parent_comment_id)}} ) returned["status_code"] = HTTPStatus.CREATED returned["message"] = "评论成功" # notification if parent_comment_id: # find username self.db["notification"].find_one_and_update( {"username": exists["username"]}, {"$push": {"unread": inserted_id}}, upsert=True ) # send email # TODO unsubscribe parent_comment = self.db["comment"].find_one({"_id": ObjectId(parent_comment_id)}) if resource_id == 233: link = f"https://yyets.dmesg.app/discuss#{parent_comment_id}" else: link = f"https://yyets.dmesg.app/resource?id={resource_id}#{parent_comment_id}" user_info = self.db["users"].find_one({"username": parent_comment["username"], "email.verified": True}) if user_info: subject = "[人人影视下载分享站] 你的评论有了新的回复" pt_content = content.split("</reply>")[-1] body = f"{username} 您好,<br>你的评论 {parent_comment['content']} 有了新的回复:<br>{pt_content}" \ f"<br>你可以<a href='{link}'>点此链接</a>查看<br><br>请勿回复此邮件" send_mail(user_info["email"]["address"], subject, body) return returned
date_str = datetime.date.today() - datetime.timedelta(days=1) date_str = date_str.strftime('%Y%m%d') _commands = cfg.get("job", {}).get("commands", []) commands = [ _command.format(date_str) if date_str else _command.format('') for _command in _commands ] global_cfg = load_cfg(cfg_file) if not global_cfg: sys.exit(0) servers = global_cfg.get("servers", []) _servers = [(server.split(' ')[0], server.split(' ')[1], server.split(' ')[2]) for server in servers if len(server.split(' ')) == 3] servers = _servers if _servers else servers if not commands or not servers: logger.error("miss required configuration") sys.exit(0) if not date_str: date_str = datetime.date.today() - datetime.timedelta(days=1) vv = count(commands[0], servers) mail = cfg.get("mail", {}) if mail and 'subject' in mail and 'content' in mail and 'to' in mail: subject = mail.get('subject') content = mail.get('content', '').format(date_str, vv) to = mail.get('to') cc = mail.get('cc') send_mail(subject, content, to, cc)
subject = I18nString(_("You have joined as %(username)s in %(site_name)s"), { 'username': new_user.username, 'site_name': settings.SITE_NAME }) message = I18nString(_("Hello %(username)s!\n You just joined to http://%(url)s/ ." " Soon the creation of your user will be reviewed by one of our" " admins and if everything is ok, we will enable your user and you" " will be able to start participating in our community." u"\n\n- The team of %(site_name)s."), { >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 'username': new_user.username, 'url': current_site.domain, 'site_name': settings.SITE_NAME }) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user], fail_silently=True) <<<<<<< HEAD self.flash(_(u"Pozdravljeni, <strong>%(username)s</strong>." u" Poslali smo vam sporočilo na <strong>%(email)s</strong>." u" Zdaj lahko začnete sodelovati v skupnosti.") % { 'username': new_user.username, 'email': new_user.email }, title=_(u"Uporabnik uspešno ustvarjen")) return redirect('main.views.index') class RegisterOrg(ViewClass): def GET(self): form = RegisterFormOrg()
<<<<<<< HEAD title = I18nString(_(u"Dobrodošli na strani %(site_name)s, %(username)s"), { 'site_name': settings.SITE_NAME, 'username': model.username }) message = I18nString(_(u"Pozdravljeni, %(username)s!\n\n" u"Potrdili smo vašo registracijo, " u"zdaj lahko začnete sodelovati v skupnosti " u"%(site_name)s.\n\n- %(site_name)s"), { ======= title = I18nString(_("Welcome to %(site_name)s, %(username)s"), { 'site_name': settings.SITE_NAME, 'username': model.username }) message = I18nString(_(u"Congratulations %(username)s!\n" u"The admins have accepted your registration request, " u"now you can start collaborating in our community in " u"http://%(url)s/.\n\n- The team of %(site_name)s."), { >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 'username': model.username, 'url': current_site.domain, 'site_name': settings.SITE_NAME }) send_mail(title, message, settings.DEFAULT_FROM_EMAIL, [model], fail_silently=True) model.save() admin.site.register(Profile, ProfileAdmin) admin.site.unregister(User)
def announce(self, short_summary, action): """ Send an announce mail about a new upload. @type short_summary: string @param short_summary: Short summary text to include in the mail @type action: bool @param action: Set to false no real action will be done. @rtype: string @return: Textstring about action taken. """ cnf = Config() # Skip all of this if not sending mail to avoid confusing people if cnf.has_key("Dinstall::Options::No-Mail" ) and cnf["Dinstall::Options::No-Mail"]: return "" # Only do announcements for source uploads with a recent dpkg-dev installed if float(self.pkg.changes.get("format", 0)) < 1.6 or not \ self.pkg.changes["architecture"].has_key("source"): return "" announcetemplate = os.path.join(cnf["Dir::Templates"], 'process-unchecked.announce') lists_todo = {} summary = "" # Get a unique list of target lists for dist in self.pkg.changes["distribution"].keys(): suite = get_suite(dist) if suite is None: continue for tgt in suite.announce: lists_todo[tgt] = 1 self.Subst["__SHORT_SUMMARY__"] = short_summary for announce_list in lists_todo.keys(): summary += "Announcing to %s\n" % (announce_list) if action: self.update_subst() self.Subst["__ANNOUNCE_LIST_ADDRESS__"] = announce_list if cnf.get("Dinstall::TrackingServer") and \ self.pkg.changes["architecture"].has_key("source"): trackingsendto = "Bcc: %s@%s" % ( self.pkg.changes["source"], cnf["Dinstall::TrackingServer"]) self.Subst[ "__ANNOUNCE_LIST_ADDRESS__"] += "\n" + trackingsendto mail_message = utils.TemplateSubst(self.Subst, announcetemplate) utils.send_mail(mail_message) del self.Subst["__ANNOUNCE_LIST_ADDRESS__"] if cnf.find_b("Dinstall::CloseBugs") and cnf.has_key( "Dinstall::BugServer"): summary = self.close_bugs(summary, action) del self.Subst["__SHORT_SUMMARY__"] return summary
def make_response_from_email(parsed_email): name, mto = parseaddr(parsed_email['to']) proxy_email_id = mto[:mto.find("@")] proxy_email_id = proxy_email_id.replace(settings.MAIL_PREFIX, "") message_id = parsed_email['message-id']\ .replace("<", "")\ .replace(">", "") logging.debug("Looking for proxy_email of %s" % proxy_email_id) try: to_user = CustomUser.objects.get(proxy_email_id=proxy_email_id) in_reply_to = None # http://www.jwz.org/doc/threading.html references = parsed_email.get('references', '') references = references and references.split(" ") or [] in_reply_to_id = parsed_email.get('in-reply-to', '') if in_reply_to_id: references.append(in_reply_to_id) tmp = [] for ref in references: tmp.append(ref.replace("<", "").replace(">", "")) references = tmp logging.debug("Possible references in thread: %s"\ % ", ".join(references)) in_reply_to = None for ref in references: try: in_reply_to = Mail.objects.get(message_id=ref) except Mail.DoesNotExist: continue if not in_reply_to: # take all the emails that this user has initiated, and # find ones with the same subject. sort them by date and # stick this in at the appropriate point. base_subject = strip_re(parsed_email['subject']) logging.debug("Trying subject heuristics") thread = Mail.objects.filter(mfrom=to_user, subject__contains=base_subject) logging.debug("Found thread %s" % thread) try: thread = thread[0] in_reply_to = thread.start_of_thread() logging.debug("Found thread start %s" % in_reply_to) except IndexError: pass if in_reply_to: name, mfrom = parseaddr(parsed_email['from']) mfrom, created = CustomUser.objects.get_or_create(email=mfrom) if created: if not in_reply_to.mto.organisation: name = mfrom.email[mfrom.email.find('@') + 1:] in_reply_to.mto.organisation, _ = \ Organisation.objects.get_or_create(name=name) in_reply_to.mto.save() mfrom.organisation = in_reply_to.mto.organisation mfrom.save() mto = to_user counter = 1 for part in parsed_email.walk(): if part.get_content_maintype() == "multipart": continue # it's just a container filename = part.get_filename() counter += 1 # XXX the following needs to change to save all parts # of a message if part.get_content_type() == "text/plain": charset = get_charset(part, get_charset(parsed_email)) message = unicode(part.get_payload(decode=True), charset, "replace") break else: message = "unknown" newmsg = Mail.objects.create(subject=parsed_email['subject'], mfrom=mfrom, mto=mto, message=message, source=parsed_email.as_string(), in_reply_to=in_reply_to, message_id=message_id) logging.debug("Sending notification to %s, from %s" \ % (newmsg.mto.email, newmsg.mfrom.email)) send_mail(mail=newmsg, message=newmsg.message, subject=newmsg.subject, mfrom=newmsg.mfrom.email, mto=newmsg.mto.email, reply_to=newmsg.mfrom.proxy_email) return newmsg else: logging.warn("Couldn't find thread for %s" % message_id) return EX_SOFTWARE except CustomUser.DoesNotExist: logging.warn("Couldn't find addressee %s" % message_id) return EX_NOUSER
def overdue_ticket_notifications(): date = add_days(getdate(), -1) query = """select distinct(tabIssue.name), tabIssue.question, tabIssue.branch, tabIssue.opening_date, tabIssue.opening_time, tabIssue.department, tabIssue.raised_by,tabToDo.owner FROM tabIssue LEFT JOIN tabToDo ON tabIssue.name=tabToDo.reference_name where tabIssue.status<>"Closed" and tabIssue.name in (select td.reference_name from tabToDo td where td.reference_type='Issue' and td.status='Open'and td.date<='{date}')""".format( date="%s" % date, ) names = frappe.db.sql(query, as_dict=True) tickets = {} if names: tickets = { "head": [ "SR", "Ticket ID", "Question", "Branch", "Opening Date", "Opening Time", "Assigned To" ], "total": len(names) } idx = 1 for tkt in names: tickets.update({ idx: [ idx, tkt.get("name"), tkt.get("question"), tkt.get("branch"), tkt.get("opening_date"), tkt.get("opening_time"), tkt.get("owner") ] }) idx += 1 ticket = { "total": 6, 1: ["Ticket ID", tkt.get("name")], 2: ["Branch", tkt.get("branch")], 3: ["Category", tkt.get("department")], 4: ["Opening Date", tkt.get("opening_date")], 5: ["Opening Time", tkt.get("opening_time")], 6: ["Question", tkt.get("question")], 7: ["Raised By", tkt.get("raised_by")], 8: ["Assigned To", tkt.get("owner")] } _args = { "date": date, "issue": tkt.get("name"), "user": tkt.get("raised_by"), "action": "aggr_ticket_overdue", "email": tkt.get("raised_by"), "ticket_detail": build_table(ticket, is_horizontal=True) } send_mail(_args, "[HelpDesk][Ticket Overdue] HelpDesk Notifications") args = { "email": frappe.db.get_value("User", "Administrator", "email"), "user": "******", "action": "aggr_ticket_overdue", "date": date, "ticket_detail": build_table(tickets) } send_mail(args, "[HelpDesk][Tickets Overdue] HelpDesk Notifications")
def test_send_email(): send_mail( ["*****@*****.**"], "A user has submitted a question", "Hello fellow Task Raider! Your application has been received! You will be contacted shortly!" " ") return "Succesfully sent", 200
def test_newsletteru(): send_mail(u'Hodně budem někde - Barcamp Brno 2017', '*****@*****.**', 'data/newsletter-reminder.md') return 'done'
def test_send_email2(): send_mail(["*****@*****.**"], "A user has applied to your post!", "Test company email!" " ") return "Succesfully sent", 200