def create_email_address( db_session: Session, email: str, account_id: int, send_verification_email: bool = True, ): """Add an email_address to a users account.""" email_obj = EmailAddress(account_id=account_id, email=email, primary=False, verified=False) db_session.add(email_obj) db_session.commit() db_session.refresh(email_obj) # Send verification email. if send_verification_email: token = create_token_from_id(email_obj.id) verification_link = "{}/{}/verify?token={}".format( FRONTEND_BASE_URL, email_obj.id, token) send_email( to_email=email, subject="Verify your email!", body="""Email Verification. <p />Please use the following link to verify your email address. <p /><a href="{}">{}</a> """.format(verification_link, verification_link), ) return email_obj
def password_reset_request(): if request.method == 'GET': return render_template('user/passwd_reset.html', form=None) elif request.method == 'POST': _form = request.form email_addr = _form["email"] u = User.query.filter_by(email=email_addr).first() message_email = "" if not email_addr: message_email = gettext("The email can not be empty") elif not email_address.match(email_addr): message_email = gettext('Email address is invalid.') elif not u: message_email = gettext("The email has not be registered") if message_email: return render_template('user/passwd_reset.html', message_email=message_email) else: token = u.generate_reset_token() # Clear the token status to "True". u.is_password_reset_link_valid = True db.session.commit() send_email(u.email, 'Reset Your Password', 'user/passwd_reset_email', user=u, token=token) return render_template('user/passwd_reset_sent.html')
def send_messages(*args, **kwargs): try: sender = User.query.get(kwargs.get('user_id')) recipients = User.query.filter(User.id != kwargs.get('user_id')) for user in recipients: message = Message() message.body = kwargs.get('body') # 发送方是自己 message.sender = sender # 接收方是所有其他用户 message.recipient = user db.session.add(message) db.session.commit() text_body = ''' 你好, 这是liyang的博客管理团队发出的群邮件 ''' html_body = ''' <p>你好 {0},</p> <p>{1}</p> <p> ----来自于Admin的邮件</p> '''.format(user.username, message.body) send_email('[myBlog] 温馨提醒', sender=app.config['MAIL_SENDER'], recipients=[user.email], text_body=text_body, html_body=html_body, sync=True) job = get_current_job() # 当前后台任务 task = Task.query.get(job.get_id()) # 通过任务ID查出对应的Task对象 task.complete = True db.session.commit() except Exception: app.logger.error('群发失败:', exc_info=sys.exc_info())
def check_and_send_email(): with app.app_context(): flight_repo = FlightRepo() print("Searching records....") flights = flight_repo.filter_by( **{ 'is_deleted': 'false', 'departure_time': ( datetime.now() + timedelta(days=1)).strftime('%B %d, %Y %H:%M') }) if flights: flight_seat_repo = FlightSeatRepo() user_repo = UserRepo() ticket_repo = TicketRepo() for flight in flights.items: flight_seats = flight_seat_repo.filter_by(**{ 'flight_id': flight.id, 'is_available': False }) for flight_seat in flight_seats.items: ticket = ticket_repo.filter_first( **{ 'flight_seat_id': flight_seat.id, 'is_deleted': False }) user = user_repo.filter_first(**{'id': ticket.user_id}) print("Sending email....") send_email('Flight Reminder', '*****@*****.**', [user.email_address], flight, flight_seat, user, ticket)
def resend_confirmation(): '''重新发送确认账户的邮件''' data = request.get_json() if not data: return bad_request('You must post JSON data.') if 'confirm_email_base_url' not in data or not data.get('confirm_email_base_url').strip(): return bad_request('Please provide a valid confirm email base url.') token = g.current_user.generate_confirm_jwt() text_body = ''' 您好,{} ~ 欢迎注册! '''.format(g.current_user.username) html_body = ''' <p>您好,{0}</p> <p>欢迎注册我的博客!大家一起来分享技术,畅谈人生~</p> <p></p> <p>请点击<a href="{1}">这里</a>确认您的账户</p> <p>或者把下面的链接粘贴到浏览器打开:</p> <p>{1}</p> '''.format(g.current_user.username,data.get('confirm_email_base_url') + token) send_email('邮件地址确认', sender=current_app.config['MAIL_SENDER'], recipients=[g.current_user.email], text_body=text_body, html_body=html_body) return jsonify({ 'status': 'success', 'message': '邮件已重新发送.' })
def send(self, dmp): title = "Dump " if not current_app.debug and not current_app.testing else "Test " title_today = title + datetime.date.today().strftime("%B %d, %Y") send_email(subject=title_today, sender=current_app.config['ADMINS'][0], recipients=current_app.config['ADMINS'], text_body=None, html_body=None, attachments=[("Dump.json", "application/json", dmp)])
def test_email(): from flask import current_app from app.utils.email import send_email send_email('[HousePriceCloud] Test Email', sender=current_app.config['MAIL_SENDER'], recipients=['*****@*****.**'], text_body='text body', html_body='<h1>HTML body</h1>') return jsonify('Send Email OK!')
def resend_confirmation(): token = current_user.generate_confirmation_token() send_email(current_user.email, 'Confirm Your Account', 'auth/email/confirm', user=current_user, token=token) flash('A new confirmation email has been sent to you by email.') return redirect(url_for('main.index'))
def test_email(): from flask import current_app from app.utils.email import send_email send_email('[MicroPub] Test Email', sender=current_app.config['MAIL_SENDER'], recipients=['*****@*****.**'], text_body='text body', html_body='<h1>HTML body</h1>') return jsonify('Send Email OK!')
def test_email(): from flask import current_app from app.utils.email import send_email send_email('[Madblog] Test Email', sender=current_app.config['MAIL_SENDER'], recipients=['*****@*****.**'], text_body='text body', html_body='<h1>HTML body</h1>') return jsonify('Send Email OK!')
def reset_password_request(): '''请求重置账户密码,需要提供注册时填写的邮箱地址''' data = request.get_json() if not data: return bad_request(_('You must post JSON data.')) message = {} if 'confirm_email_base_url' not in data or not data.get( 'confirm_email_base_url').strip(): message['confirm_email_base_url'] = _( 'Please provide a valid confirm email base url.') pattern = '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$' if 'email' not in data or not re.match(pattern, data.get('email', None)): message['email'] = _('Please provide a valid email address.') if message: return bad_request(message) user = User.query.filter_by(email=data.get('email')).first() if user: # 如果提供的邮箱地址对应的用户实例对象存在,就发邮件 token = user.generate_reset_password_jwt() text_body = ''' Dear {0}, To reset your password click on the following link: {1} If you have not requested a password reset simply ignore this message. Sincerely, The Madblog Team Note: replies to this email address are not monitored. '''.format(user.username, data.get('confirm_email_base_url') + token) html_body = ''' <p>Dear {0},</p> <p>To reset your password <a href="{1}">click here</a>.</p> <p>Alternatively, you can paste the following link in your browser's address bar:</p> <p><b>{1}</b></p> <p>If you have not requested a password reset simply ignore this message.</p> <p>Sincerely,</p> <p>The Madblog Team</p> <p><small>Note: replies to this email address are not monitored.</small></p> '''.format(user.username, data.get('confirm_email_base_url') + token) send_email('[Madblog] Reset Your Password', sender=current_app.config['MAIL_SENDER'], recipients=[user.email], text_body=text_body, html_body=html_body) # 不管前端提供的邮箱地址有没有对应的用户实例(不排除有人想恶意重置别人的账户),都给他回应 return jsonify({ 'status': 'success', 'message': _('An email with instructions to reset your password has been sent to you.' ) })
def reset_password_request(): """请求重置密码,需要填写时的邮箱""" json_data = request.json if not json_data: return bad_request("You must post Json data") message = {} if 'confirm_email_base_url' not in json_data.get( 'confirm_email_base_url').strip(): message[ 'confirm_email_base_url'] = "Plase provide a valid confirm email base url" pattern = '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$' if 'email' not in json_data and re.match(pattern, json_data.get('email')): message['email'] = "Please provide a valid email address." if message: return bad_request(message) user = User.query.filter_by(email=json_data.get('email')).first() if g.current_user != user: return bad_request("Please provide a valid email address") if user: token = user.generate_reset_password_jwt() text_body = ''' Dear {0}, To reset your password click on the following link: {1} If you have not requested a password reset simply ignore this message. Sincerely, The Madblog Team Note: replies to this email address are not monitored. '''.format(user.username, json_data.get('confirm_email_base_url') + token) html_body = ''' <p>Dear {0},</p> <p>To reset your password <a href="{1}">click here</a>.</p> <p>Alternatively, you can paste the following link in your browser's address bar:</p> <p><b>{1}</b></p> <p>If you have not requested a password reset simply ignore this message.</p> <p>Sincerely,</p> <p>The Madblog Team</p> <p><small>Note: replies to this email address are not monitored.</small></p> '''.format(user.username, json_data.get('confirm_email_base_url') + token) send_email('[Madblog] Reset Your Password', sender=current_app.config['MAIL_SENDER'], recipients=[user.username], text_body=text_body, html_body=html_body) return jsonify({ 'status': 'success', 'message': 'An email with instructions to reset your password has been sent to you.' })
def resend_confirmation(): token = current_user.generate_confirmation_token() send_email(recipients=[current_user.email], subject='Confirme sua conta', template='auth/email/confirm', user=current_user, token=token) flash('Uma nova mensagem de confirmação foi enviada ao seu email.', 'success') return redirect(url_for(current_app.config.get('MAIN_ENDPOINT')))
def email_message(): data = json.loads(request.data) email = data.get('email') subject = data.get('subject') body = data.get('body') if not email or not body: return_data = {'message': 'An email and body are required.'} return json.dumps(return_data), 500, {'Content-Type': 'application/json'} send_email(email, subject, body) return json.dumps(data), 200, {'Content-Type': 'application/json'}
def send_password_reset_email(user): token = user.get_reset_password_token() send_email('Reset Your Password', 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 send_password_reset_email(user): token = user.get_reset_password_token( current_app.config['RESET_PASSWORD_TOKEN_EXPIRES_IN']) reset_url = current_app.config['FRONT_URL'] + '/reset_password/' + token send_email(_('[Dinner-roulette] Reset Your Password'), sender=current_app.config['ADMINS'][0], recipients=[user.email], text_body=render_template('email/reset_password.txt', user=user, reset_url=reset_url), html_body=render_template('email/reset_password.html', user=user, reset_url=reset_url)) current_app.logger.info('%s requested password reset' % user.username)
def create_account( db_session: Session, first_name: str, last_name: str, email: str, password: str, is_system_admin: bool = False, is_active: bool = False, send_registration_email: bool = True, is_verified: bool = False, ): """Create an user account.""" account_obj = Account( first_name=first_name, last_name=last_name, is_system_admin=is_system_admin, is_active=is_active, ) db_session.add(account_obj) db_session.flush() email_obj = EmailAddress(account_id=account_obj.id, email=email, primary=True, verified=is_verified) password_obj = Password(account_id=account_obj.id, password=password) db_session.add(email_obj) db_session.add(password_obj) db_session.commit() # Send registration email. if send_registration_email: token = create_token_from_id(email_obj.id) registration_link = "{}/{}/verify?token={}".format( FRONTEND_BASE_URL, email_obj.id, token) send_email( to_email=email, subject="Welcome!", body="""Weclome to the website. <p />Please use the following link to continue your registration. <p /><a href="{}">{}</a> """.format(registration_link, registration_link), ) db_session.refresh(account_obj) return account_obj
def change_email_request(): form = ChangeEmailForm() if form.validate_on_submit(): if current_user.verify_password(form.password.data): new_email = form.email.data.lower() token = current_user.generate_email_change_token(new_email) send_email(current_user.email, 'Confirm your email address', 'auth/email/change_email', user=current_user, token=token) flash('An email with instructions to confirm your new email') return redirect(url_for('main.index')) else: flash('Invalid password', 'danger') return render_template('auth/change_email.html', form=form)
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data.lower(), username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, 'Confirm Your Account', 'auth/email/confirm', user=user, token=token) flash('A confirmation email has been sent to you by email', 'success') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
def order_send_mail(id): ''' 功能: 小程序订单任务完成,通过邮件发送结果 参数: <int:id> 订单的id { "type": "尽调报告结果", "email": "*****@*****.**" } 返回格式: { "status": "complete", // 已完成 "company": '上海思华科技股份有限公司', "create": "2000-08-15 00:00:00.0", "complete": "2000-08-15 00:00:00.0", "id": 234, "price": 39.9, "code": "sdasdasdsadsadsadasd" // 订单号, } ''' data = request.get_json() if not data: code = ResponseCode.InvalidParameter data = 'You must post JSON data.' return ResMsg(code=code, data=data).data html_body = ''' <p>亲爱的用户你好,</p> <p>感谢您使用核查宝小程序!</p> <p>生成的文件见附件,请查收!</p> <p>Sincerely,</p> <p>The hechabao app Team</p> <p><small>Note: replies to this email address are not monitored.</small></p> ''' order = Order.query.get_or_404(id) result_address = order.to_dict()["result"] email = data["email"] if data["email"] else g.current_user.email send_email(data["type"] + " : " + order.company, sender=current_app.config['MAIL_SENDER'], recipients=[email], html_body=html_body, attachments=['/root/wiz-wxapp.tar.gz']) # 制作返回内容 return ResMsg(data=data).data
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, password=form.password.data) if user.email in PreAllowedUser.get_emails(): user.role = Role.query.filter_by(name='Staff').first() db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(recipients=[user.email], subject='Confirme sua conta', template='auth/email/confirm', user=user, token=token) flash('Uma mensagem de confirmação foi enviada para seu email.', 'success') return redirect(url_for(current_app.config.get('MAIN_ENDPOINT'))) return render_template('auth/register.html', form=form)
def password_reset_request(): if not current_user.is_anonymous: return redirect(url_for('main.index')) form = PasswordResetRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: token = user.generate_reset_password_token() send_email(user.email, 'Reset Your Password', 'auth/email/reset_password', user=user, token=token) flash('An email with password reset instructions has been' ' sent to the given email address.') return redirect(url_for('auth.login')) flash('User not found', 'danger') return render_template('auth/reset_password.html', form=form)
def change_email_request(): form = ChangeEmailForm() if form.validate_on_submit(): if current_user.verify_password(form.password.data): new_email = form.email.data token = current_user.generate_email_change_token(new_email) send_email(new_email, _('Confirm your email address'), 'auth/email/change_email', user=current_user, token=token) flash( _('An email with instructions to confirm your new email address has been sent to you.' )) return redirect(url_for('main.index')) else: flash(_('Invalid email or password.')) return render_template("auth/change_email.html", form=form)
def resend_confirmation(): '''重新发送确认账户的邮件''' data = request.get_json() if not data: return bad_request(_('You must post JSON data.')) if 'confirm_email_base_url' not in data or not data.get( 'confirm_email_base_url').strip(): return bad_request(_('Please provide a valid confirm email base url.')) token = g.current_user.generate_confirm_jwt() text_body = ''' Dear {}, Welcome to Madblog! To confirm your account please click on the following link: {} Sincerely, The Madblog Team Note: replies to this email address are not monitored. '''.format(g.current_user.username, data.get('confirm_email_base_url') + token) html_body = ''' <p>Dear {0},</p> <p>Welcome to <b>Madblog</b>!</p> <p>To confirm your account please <a href="{1}">click here</a>.</p> <p>Alternatively, you can paste the following link in your browser's address bar:</p> <p><b>{1}</b></p> <p>Sincerely,</p> <p>The Madblog Team</p> <p><small>Note: replies to this email address are not monitored.</small></p> '''.format(g.current_user.username, data.get('confirm_email_base_url') + token) send_email('[Madblog] Confirm Your Account', sender=current_app.config['MAIL_SENDER'], recipients=[g.current_user.email], text_body=text_body, html_body=html_body) return jsonify({ 'status': 'success', 'message': _('A new confirmation email has been sent to you by email.') })
def resend_confirmation(userid): user = user_module.User.query.filter_by(id=uuid.UUID(userid).hex).first() if user: token = user.generate_confirmation_token() send_email(user.email, 'Please confirm Your Email', 'confirmation', user=user, token=token, company_name=current_app.config['COMPANY_NAME']) flash( 'We\'ve resent you the confirmation email. Please open your mail and click the link inside.' ) return render_template("confirmemail.html", userid=userid, company_name=current_app.config['COMPANY_NAME']) return error_handler.app_error( 'User identification error', 'Sorry but user not found. Please login or register again.')
def send_confirmation_email( user, subject, template, redirect_to, token_type, to = None, token_dict = None, expiration = app.config['TOKEN_EXPIRES_IN'] ): token = user.generate_token(expiration, token_type, token_dict) confirm_url = url_for(redirect_to, token=token, _external=True) to = user.email if to is None else to send_email( to = to, subject = subject, template = template, user = user, confirm_url = confirm_url, expiration = expiration )
def password_reset_request(): if not current_user.is_anonymous: return redirect(url_for('main.index')) form = PasswordResetRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: token = user.generate_reset_token() send_email(user.email, _('Reset Your Password'), 'auth/email/reset_password', user=user, token=token, next=request.args.get('next')) flash( _('An email with instructions to reset your password has been sent to you.' )) return redirect(url_for('auth.login')) return render_template('auth/reset_password.html', form=form)
def register_api(): form = RegistrationForm() if form.validate(): user = user_module.User(email=form.email.data, username=form.username.data, confirmed=False) user.set_password(form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, 'Please confirm Your Email', '/non_auth/confirmation', user=user, token=token, company_name=current_app.config['COMPANY_NAME']) confirm_email = url_for('auth.confirm_email', userid=str(user.id)) return jsonify({'result': True, 'redirect': confirm_email}) else: return jsonify({'result': False, 'errors': form.errors})
def handle_register(): register_form_info = RegisterForm(request.form) if register_form_info.validate(): if User.objects(username=register_form_info.username.data): flash(u'用户名己被注册') return register() else: new_user = User( username=register_form_info.username.data, password=register_form_info.password.data, email=register_form_info.email.data ) new_user.save() send_email(rec=ADMIN_MAIL, html_content='', subject='有新用户需要审核 {}'.format(new_user.email)) # login_user(user=new_user, remember=True) flash(u'帐户注册成功, 请等待管理员审核') return redirect(url_for('main.index')) else: flash(u'用户名或密码不符合要求') return register()
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data, role_id=1) print(user) print(user.verify_password(form.password.data)) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, _('Confirm Your Account'), 'auth/email/confirm', user=user, token=token) flash(_('Registration Successful.')) flash(_('A confirmation email has been sent to you by email.')) return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
def register(): if current_user.is_authenticated: # If user is logged in, redirect return redirect(url_for('main.index')) form = RegistrationForm() if form.validate_on_submit(): # For valid post request user = User(email=form.email.data, password=form.password.data) db.session.add(user) db.session.commit() token = gen_token(user.email) send_email( to=user.email, subject='Confirm Your Account', template='auth/email/confirm', user=user, token=token ) login_user(user) flash('A confirmation email has been sent.', 'success') return redirect(url_for('main.index')) return render_template('auth/register.html', title="Register", form=form)
def add_member( db_session: Session, tenant_id: int, email: str, do_send_email: bool = True ): """Add a new member to the tenant.""" tenant_obj = db_session.query(Tenant).get(tenant_id) # If email address: email_obj = ( db_session.query(EmailAddress).filter(EmailAddress.email == email).first() ) if email_obj and email_obj.account: # Account already exists, go ahead and add them. tenant_account_obj = TenantAccount() tenant_account_obj.tenant_id = tenant_id tenant_account_obj.account_id = email_obj.account_id db_session.add(tenant_account_obj) db_session.commit() # TODO: Send email telling them we added them. if do_send_email: # send_email() # Send the email! send_email( to_email=email, subject=f"You've been added to {tenant_obj.name}", body=( f"Weclome to {tenant_obj.name}." f"<p />You have been invited into the new group. Please use the link below to login." f"<p /><a href='{FRONTEND_BASE_URL}{LOGIN_URL_PATH}'>Login</a>" ), ) else: # Never been apart of this site. # Create relationship tenant_account_obj = TenantAccount() tenant_account_obj.tenant_id = tenant_id tenant_account_obj.email_address = email db_session.add(tenant_account_obj) db_session.commit()