def change_email(): user_id = session.get('current_user') form = NewEmailForm() if form.validate_on_submit(): new_email = form.new_email.data db = get_db() cur = db.execute('select email from users where email is ?', \ (new_email,)) row = cur.fetchone() if row == None: token = generate_email_token(user_id, new_email) send_email(new_email, 'Confirm your new email address', 'email/change_email', token=token) flash('A confirmation email has been sent to your address.') return redirect(url_for('main.main_view')) else: flash('That email address is already registered.') return redirect(url_for('auth.change_email')) db = get_db() cur = db.execute('select email from users where id is ?', (user_id, )) row = cur.fetchone() current_email = row[0] return render_template('change_email.html', form=form, \ current_email=current_email)
def isRegin(reginData): uname = reginData.get("uname") pwd = reginData.get("pwd") email = reginData.get("email") resData = {"flag": "error", "msg": ""} #返回的JSON字符串 try: qData1 = session.query(User).filter_by(uname=uname).all() qData2 = session.query(User).filter_by(email=email).all() if len(qData1) != 0: resData['msg'] = "用户已存在" elif len(qData2) != 0: resData['msg'] = "该邮箱已注册" else: user = User(uname, pwd, email) session.add(user) session.commit() resData['flag'] = "success" resData['msg'] = "账号注册成功" token = generate_confirmation_token(email) htmlStr = '<h4>欢迎您注册,请单击<a href="' + LINK_URI + '/regin/email?qt=' + token + '" target="_blank">立即激活</a>进行激活</h4>' send_email("测试邮件", htmlStr, email) except InvalidRequestError: session.rollback() resData['msg'] = "账号注册失败" except Exception as e: print(str(type(e))) resData['msg'] = repr(e) session.rollback() return resData
def approve_or_reject(request, context): if 'approve' in request.GET: a_id = request.GET['approve'] if check_notapproved(a_id): contract_id = application.objects.get(id=a_id).contract_id api.application_action(contract_id, 'approve') x = application.objects.get(id=a_id) x.approved = True x.save() mail.send_email( application.objects.get(id=a_id).applicant.username, "Your voterId application with aadhar " + application.objects.get(id=a_id).aadhar + " has been approved.", "LetsVote Application Approved") context['action_success'] = True elif 'reject' in request.GET: a_id = request.GET['reject'] if check_notapproved(a_id): contract_id = application.objects.get(id=a_id).contract_id api.application_action(contract_id, 'reject') mail.send_email( application.objects.get(id=a_id).applicant.username, "Your voterId application with aadhar " + application.objects.get(id=a_id).aadhar + " has been rejected. Please try submitting your application again.", "LetsVote Application Rejected") application.objects.filter(id=a_id).delete() context['action_success'] = True
def change_email(user_id): """ Обработчик для отправки сообщения для подтверждения смены почты """ session = db_session.create_session() user = get_user(session, user_id) emails = {user.email for user in session.query(User).all()} form = ConfirmEmailForm(emails, user.email) if request.method == 'GET': # Текущая почта form.email.data = user.email if form.validate_on_submit(): # Отправление письма на новую почту link = f'http://{host}:{port}/finish_changing/{user_id}/{form.email.data}/{user.get_token()}' send_email(app=app, mail=mail, subject='Change email', sender=app.config['ADMINS'][0], recipients=[form.email.data], html_body=render_template('email_template.html', username=user.nickname, link=link)) return redirect(url_for('check_email')) return render_template('confirm_email_form.html', title='Изменение почты', form=form)
def recover_password(): """ Обработчик для отправления письма на почту для смены пароля """ session = db_session.create_session() emails = {user.email for user in session.query(User).all()} form = ConfirmEmailForm(emails, is_email_edit=False) if form.validate_on_submit(): # Отправка письма для подтверждения почты user = session.query(User).filter( User.email == form.email.data).first() link = f'http://{host}:{port}/new_password/{user.id}/{user.get_token()}' send_email(app=app, mail=mail, subject='Recover password', sender=app.config['ADMINS'][0], recipients=[form.email.data], html_body=render_template('email_template.html', username=user.nickname, link=link)) return redirect(url_for('check_email')) return render_template('confirm_email_form.html', title='Восстановление пароля', form=form, rec_pas=True)
def post(self): args = post_user_parser.parse_args() if db.session.query(User).filter(User.Email.like( args['email'])).first() is None: if not match(r"(^|\s)[-a-z0-9_.]+@([-a-z0-9]+\.)+[a-z]{2,6}(\s|$)", args['email']): return jsonify({ 'status': 'BAD', 'result': 'Incorrect email address' }) user = User(Name=args['name'], Email=args['email'], DisplayName=args['display_name'], FamilyName=args['family_name'], RegistrationDate=datetime.now(), LastVisit=datetime.now()) db.session.add(user) db.session.commit() user = db.session.query(User).filter(User.Email.like( args['email'])).first() access_token = create_access_token(identity=user.Id) send_email(subject="Auth MarkerSet", recipients=[args['email']], text_body="You have recently authorized to MarkerSet.", html_body="") return jsonify({'status': 'OK', 'result': access_token})
def contacts(): form = ContactForm(request.form) if request.method == "POST": send_email(form.title.data, form.text.data) flash("Message sent", "success") return redirect(url_for('contacts')) return render_template('contacts.html', form=form)
def register(): form = RegistrationForm() if form.validate_on_submit(): db = get_db() email = form.email.data password = form.password.data current_time = datetime.utcnow().date() password_hash = pwd_context.hash(password) role = 'user' db.execute('insert into users (email, password, role, \ joined_on, status) values (?, ?, ?, ?, ?)' , \ (email, password_hash, role, current_time, 'unconfirmed')) db.commit() session['logged_in'] = True session['status'] = 'unconfirmed' cur = db.execute('select id from users where email = ?', (email, )) row = cur.fetchone() user_id = row[0] session['current_user'] = user_id token = generate_confirmation_token(user_id) send_email(email, 'Thanks for registering—please confirm your email', 'email/confirm', token=token) flash( Markup('You have been registered and are now logged in. \ </br>A confirmation has been sent to your email address.')) return redirect(url_for('main.main_view')) return render_template('register.html', form=form)
def async_send_email(self, subject, body): # app = current_app._get_current_object() # with app.app_context(): send_email(subject, current_app.config["MAIL_USERNAME"], ADMINS, "", body)
def send_password_reset_email(user): token = user.get_reset_password_token() send_email(_('[{}] Reset your password'.format(current_app.config['APP_NAME'])), sender=current_app.config['ADMINS'][0], recipients=[user.email], text_body=render_template('email/reset_password.txt', user=user, token=token), html_body=render_template('email/reset_password.html', user=user, token=token))
def change_pass(): form = SelectForm() if form.submit.data: token = generate_confirmation_token(form.email.data) confirm_url = url_for('confirm_pass', token=token, _external=True) html = render_template('change_pass.html', confirm_url=confirm_url) subject = "Сылка для изменения пароля" send_email(form.email.data, subject, html) return "На ваш email отправлено письмо" return render_template('email_pass.html', title='Email', form=form)
def apply(): jdata = {'code': -1, 'data': {}} if check_is_login(): id = request.values.get('id', '') user = Students.query.filter_by(id=id).first() jdata['code'] = 0 send_email( current_app._get_current_object().config['FLASKY_MAIL_SENDER'], '来自' + id + '的申请', '/mail/apply', user=user) return jsonify(jdata)
def request_reset(): form = ResetPasswordForm() if form.validate_on_submit(): user_id = get_user_id(form.email.data) token = generate_confirmation_token(user_id) send_email(email, 'Link to reset your password', 'email/reset_password', token=token) flash('Your password reset token has been sent.') return redirect(url_for('auth.login')) return render_template('reset_password.html', form=form)
def do_send_notification(parents, subject, body): emails = set() vk_domains = set() vk_links = set() for parent in parents: if parent.notification_types & (1 << shift_email) != 0: emails.add(parent.email) if parent.notification_types & (1 << shift_vk) != 0: vk_domains.add(parent.vk_link[len(vk_link_prefix):]) vk_links.add(parent.vk_link) if len(emails) == 0 and len(vk_domains) == 0: return None if len(emails) > 0: send_email(subject, body, emails) if len(vk_domains) > 0: send_vk_messages(subject, body, vk_domains) return '{}\n{}'.format('\n'.join(emails), '\n'.join(vk_links))
def vote(request, context): if 'vote' in request.GET: a_id = request.GET['vote'] if not check_notapproved(a_id): contract_id = application.objects.get(id=a_id).contract_id api.application_action(contract_id, 'vote') x = application.objects.get(id=a_id) x.voted = True x.save() mail.send_email( application.objects.get(id=a_id).applicant.username, "Dear " + x.applicant.first_name + " " + x.applicant.last_name + ",\nYour vote has been registered on LetsVote.", "LetsVote Vote Registered") context['action_success'] = True
def contact(language): labels = contact_form[language] title = labels['title'] name = labels['name'] email = labels['email'] text = labels['text'] submit = labels['submit'] form = VisitorForm() if form.validate_on_submit(): subject = 'mu-law.com' body = 'Message:\n' + form.text.data body += '\n\nname: ' + form.name.data + '\nemail: ' + form.email.data send_email(subject, body) return redirect(url_for('thank_you', language=language)) return render_contact(form, title, name, email, text, submit, language)
def add_email(): form = SelectForm() if form.submit.data: User.query.filter_by(id=current_user.id).update( {"email": form.email.data}) db.session.commit() token = generate_confirmation_token(current_user.email) confirm_url = url_for('confirm_email', token=token, _external=True) html = render_template('activate.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(current_user.email, subject, html) print(1) flash('Congratulations, you are now a registered user!') return "На ваш email было высланно письмо" return render_template('email.html', title='Email', form=form)
def request_reset(): details = get_details() if not details: return abort(404) form = ResetPasswordForm() if form.validate_on_submit(): email = form.email.data user_id = get_element_id('auth', Query().email == email) token = generate_confirmation_token(user_id) send_email(email, 'Link to reset your password', 'email/reset_password', token=token) flash('Your password reset token has been sent.') return redirect(url_for('auth.login')) return render_template('reset_password.html', form=form, details=details)
def resend_confirmation(): user_id = session.get('current_user') status = session.get('status') if status == 'confirmed': flash('You have already confirmed your email address') return redirect(url_for('main.main_view')) elif status == 'unconfirmed': token = generate_confirmation_token(user_id) db = get_db() cur = db.execute('select email from users where id = ?', (user_id, )) row = cur.fetchone() email = row[0] send_email(email, 'Your new confirmation token', 'email/confirm', token=token) flash('A new confirmation email has been sent to your address.') return redirect(url_for('main.main_view'))
def delete_account(): current_user = session.get('current_user') db = get_db() cur = db.execute('select email from users where id = ?', \ (current_user,)) row = cur.fetchone() email = row[0] db.execute('update users set email = ?, password = ? where id = ?', \ (None, None, current_user,)) db.execute('delete from tasks where creator_id = ?', \ (current_user,)) db.commit() session['logged_in'] = False send_email(email, 'Your account has been deleted at your request', 'email/account_deleted') flash('Your account has been deleted at your request. \ You are now logged out.') return (redirect(url_for('main.main_view')))
def request_password_reset(): form = RequestPasswordResetForm() if form.validate_on_submit(): # Verify that email is not already in use email = form.email.data db = get_db() cur = db.execute('select id from users where email is ?', (email, )) row = cur.fetchone() if row != None: user_id = row[0] token = generate_confirmation_token(user_id) send_email(email, 'Link to reset your password', 'email/reset_password', token=token) flash('A link to reset your password has been sent.') return redirect(url_for('auth.login')) else: flash('That email is not registered') return redirect(url_for('auth.request_password_reset')) return render_template('reset_password.html', form=form)
def message_dispatch_sendgrid(email_to: list, subject: str, body: str, *args, **kwargs) -> object: # converting it to array if type(email_to) == str: email_to = [email_to] # apenas o ambiente de development if os.getenv('APP_SETTINGS') == "config.DevelopmentConfig" or \ os.getenv('APP_SETTINGS') == "config.DevelopmentContainerConfig" or \ app.config["DEBUG"]: # replace for email.com.br emails with debug true making sure we are sending not to production for i, val in enumerate(email_to): val = val.split("@")[0] + "@email.com.br" email_to[i] = val to_email = [] for m in email_to: key = "email" to_email.append({key: m}) from_email = kwargs[ "from_email"] if "from_email" in kwargs else app.config[ 'SENDGRID_DEFAULT_FROM'] if "from_email" in kwargs: kwargs.pop("from_email") try: mail.send_email( from_email=from_email, to_email=to_email, subject=subject, html= "<html><body><b> This is something default content </body></html>", *args, **kwargs) return True except Exception as e: raise e
def registration(): """ Обработчик для регистрации пользователя """ form = RegistrationForm() if form.validate_on_submit(): session = db_session.create_session() # Проверка на существование пользователя с указанной почтой if session.query(User).filter(User.email == form.email.data).first(): return render_template( 'registration.html', title='Регистрация', form=form, message='Пользователь с такой почтой уже существует') # # Создание нового пользователя user = User( nickname=form.nickname.data, email=form.email.data, ) user.set_password(form.password.data) # # Отправка сообщения на указанную почту для подтверждения почты link = f'http://{host}:{port}/verifying_email/{user.nickname}/{user.email}' \ f'/{user.password}/{user.get_token()}' send_email(app=app, mail=mail, subject='Change email', sender=app.config['ADMINS'][0], recipients=[form.email.data], html_body=render_template('email_template.html', username=user.nickname, link=link)) # return redirect(url_for('check_email')) return render_template('registration.html', title='Регистрация', form=form)
def email_register(): form = EmailForm() if request.method == 'POST': form.email.data = form.email_name.data + current_app.config[ 'REGISTRATION_EMAIL_DOMAIN'] if form.validate_on_submit(): email = User.query.filter_by(email=form.email.data).first() if not email: token = generate_confirmation_token(form.email.data) flash( '{}으로 이메일이 전송되었습니다. 전송된 URL을 통하여 회원가입을 진행해주십시오.'.format( form.email.data), 'info') confirm_url = url_for('auth.confirm_email', token=token, _external=True) contents = render_template('/constant/email.html', confirm_url=confirm_url) send_email(form.email.data, '[CVIP] email verification', contents) return redirect('/') else: flash('email already exist.', 'danger') return render_template('/main/auth/register.html', form=form)
def send_async_email(app, mailargs): with app.app_context(): mail.send_email(**mailargs)
def sendmail(email): token = generate_validate_email(email) link = 'http://localhost:8888/api/v1/mail/'+token return send_email(email, 'jigsaw validate email', '<div><a href="'+link+'">'+link+'</a>链接有效时间为1小时</div>')
def generatetoken(): token = current_user.generate_confirm_token().decode('utf-8') send_email(current_user.email, '确认你的邮箱!', '/mail/comfirm', token=token) flash('验证邮件已经发送到你的邮箱,请查看!') return redirect(url_for('main.profile'))
def sendEmail(): data = json.loads(request.data.decode("utf-8")) send_email(data['title'], data['text']) return "200 OK"
def addWork(): if current_user.is_admin(): form = WorkForm() tid = current_user.fk_tid form.courses.choices = [ (c.id, c.name) for c in Courses.query.filter_by(fk_tid=tid).order_by('name') ] if form.validate_on_submit(): housework = Houseworks(fk_tid=tid, title=form.title.data, state=int(form.state.data), content=form.content.data, createdate=datetime.now(), fk_cid=form.courses.data) content = housework.content patten = re.compile("<img[^>]*>") src = patten.findall(content) print(src) srcnew = [ i.replace(' ', '').replace('<imgsrc="', 'app').replace( '"style="max-width:100%;">', '') for i in src ] db.session.add(housework) try: db.session.commit() except: db.session.rollback() flash('更新数据失败!') for i in srcnew: pic = PicSave.query.filter_by(path=i, fk_sid=current_user.id).first() if pic is not None: pic.fk_workid = housework.id print(housework.id) db.session.add(pic) try: db.session.commit() except: db.session.rollback() flash('更新数据失败!') delpic = PicSave.query.filter_by(fk_sid=current_user.id, fk_workid=None).all() for p in delpic: os.remove(p.path) db.session.delete(p) db.session.commit() cname = Courses.query.filter_by(id=housework.fk_cid).first().name sendto = EmailSender.query.filter_by(fk_tid=tid, isopen=True).all() print(sendto) for i in sendto: user = Students.query.filter_by(id=i.fk_sid).first() send_email(i.email, '来自' + i.fk_tid + '的' + cname + '(有新消息)', '/mail/mail', info=housework, user=user) return redirect(url_for('main.info')) return render_template('/addwork.html', form=form) else: return render_template('/404.html')
def sendEmail(): send_email() return redirect(url_for('admin.root'))
def sendEmail(): send_email() return redirect(url_for('admin.root'))