def forgotPassword(self): form = RecoveryForm() if request.method == 'POST': try: user = User.get_by_username(form.username.data) if user: # initializing size of string N = 8 # using secrets.choices() # generating random strings res = ''.join( secrets.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase + string.punctuation) for i in range(N)) user.update_password(res, res) flash('Password change successful!') mail = Mail() mail.init_app(current_app) mail.send_message(subject="PASSWORD CHANGED!", recipients=[user.email], html=render_template( 'pwd_forgot_email.html', username=form.username.data, res=res)) return redirect(url_for('UserView:login')) except TypeError as e: flash(str(e)) return render_template('forgot_password.html', form=form)
def change_permissions(self, user): if current_user.is_admin: form = ChangePermissionsForm() if request.method == 'POST': user.change_permissions(form.is_admin.data, form.can_post_provided.data, form.can_post_solicited.data) mail = Mail() mail.init_app(current_app) mail.send_message( subject="Your YDP Account", recipients=[user.email], body= f"""Hello {user.name}, Your YCP Project Database account permissions have been modified by an admin""" ) return redirect(url_for('UserPageView:view', id=user.id)) else: catalog = user.get_user_projects() form.is_admin.data = user.is_admin form.can_post_provided.data = user.can_post_provided form.can_post_solicited = user.can_post_solicited return render_template('userpage.html', catalog=catalog, user=user, permissions_form=form, current_user=current_user) else: return 'Access denied', 403
class EmailSender: """ This class is for sending emails in a convenient manner, using the Mail SMTP server settings as specified in the Flask config object. Example for email confirmation: app = Flask(__name__) email_sender = EmailSender(app) ... recipients = ['*****@*****.**'] subject = 'message from generic fan girl #34193' body = 'HIIII OMG I'M YOUR BIGGEST FAN CAN I HAVE YOUR DIGITAL AUTOGRAPH' email_sender.send(recipients, subject, body) """ def __init__(self, app=None): """ A convenience constructor for initializing the email sender """ if isinstance(app, Flask): self.init_app(app) def init_app(self, app): """ Initialize the email sender by pulling any required settings from the Flask config """ if isinstance(app, Flask): self.mail = Mail() self.mail.init_app(app) self.sender = app.config['MAIL_DEFAULT_SENDER'] def send(self, recipients, subject, body): """ A simple method to send an HTML email to a list of recipients with a subject """ try: self.mail.send_message( subject=subject, recipients=recipients, html=body, sender=self.sender ) except smtplib.SMTPAuthenticationError as ex: raise JsonError(status='error', reason='The GMail login failed. Please see the logs', status_=500)
def post(self, **_): """ Create an new user account """ schema = DaoCreateUserSchema() data = request.get_json() or {} try: data = schema.load(data) except ValidationError as errors: return ResultErrorSchema( message='Payload is invalid', errors=errors.messages, status_code=400 ).jsonify() # check if the username is already in use user_exists = User.query.filter_by(username=data['username']).first() if user_exists: return ResultErrorSchema( message='Username already in use!', status_code=422 ).jsonify() # get the role object data['role'] = Role.query.filter_by(name=data.get('role')).first() if not data['role']: return ResultErrorSchema( message='Role does not exist!', status_code=404 ).jsonify() # create the user and add it to the database user = User(**data) db.session.add(user) db.session.commit() # generate token to verify email s = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) token = s.dumps(data['email'], salt='verify-email') # send email with verification token to enable account mail = Mail(current_app) link = f'{request.scheme}://{request.host}{url_for("app.views.auth.verify", token=token)}' body = render_template('mail_verify_account.html', link=link, password=data['password']) mail.send_message("Activate your account!", recipients=[data['email']], html=body) return ResultSchema( data=user.jsonify(), status_code=201 ).jsonify()
def submitContact(self, user): #current_user is a local proxy object, so we have to compare by id if user.id != current_user.id: mail = Mail() mail.init_app(current_app) mail.send_message( subject="Your YDP Account", recipients=[user.email], body= f"""Hello {user.name},\n Your YCP Project Database account has been modified by an admin""" ) contact = request.form['contact'] user.add_contact(contact) return redirect(url_for('UserPageView:view', id=user.id))
def send_register_mail(mail: flask_mail.Mail, user: Users) -> None: html = f'''Hello {user.username},<br> <br> You just signed up for an account!<br> Please confirm your ownership of this email address by clicking the link below:<br> <a href="{EXTERNAL_URI}/verify?token={user.token}">{EXTERNAL_URI}/verify?token={user.token}</a><br> <br> Not expecting this email?<br> If you received this by mistake or weren't expecting it, please disregard this email.<br> <br> ''' subject = 'Verify your Tuxae Jupyter Manager account' mail.send_message(subject, sender=MAIL_USERNAME, recipients=[user.email], html=html)
def send_forgot_password_mail(mail: flask_mail.Mail, user: Users) -> None: html = f'''Hello {user.username},<br> <br> You just ask to reset your password from your account!<br> You can use the link below:<br> <a href="{EXTERNAL_URI}/reset-password?token={user.token}">{EXTERNAL_URI}/reset-password?token={user.token}</a><br> <br> Not expecting this email?<br> If you received this by mistake or weren't expecting it, please disregard this email.<br> <br> ''' subject = 'Reset your password from your Tuxae Jupyter Manager account' mail.send_message(subject, sender=MAIL_USERNAME, recipients=[user.email], html=html)
def review_user(self): id = request.args.get('id', type=int) approval = request.args.get('approval', type=int) #we gotta do truthy/falsey again user = User.get_by_id(id) user.review(approval) approve_deny_text = 'approved' if approval else 'denied' append_text = '\nYou may now login and begin posting projects' if approval else '' mail = Mail() mail.init_app(current_app) mail.send_message( subject="Your YDP Account", recipients=[user.email], body= f"""Hello {user.name}, \nYour YCP Project Database account has been {approve_deny_text}.{append_text}""" ) return redirect(url_for('AdminPanelView:view'))
def send(self, subject, recipients, body, attechment=None): mail = Mail(None) # print(str(recipients)) send = mail.send_message(subject=subject, sender=CONST.MAIL_USERNAME, recipients=recipients, body=body) # print(send) return send
def edit(self, project): form = EditForm() if request.method == 'POST': edit_data = dict(form.data) for attribute in DegreeAttributes: edit_data[attribute.name] = attribute.value in form.degree.data edit_data['grade'] = GradeAttributes(edit_data['grade']) if form.maxProjSize.data is None: flash("You must enter a project size.") return render_template('set_project_data.html', form=form, project=project) project.edit(current_user, **edit_data) if current_user.id != project.poster.id: mail = Mail() mail.init_app(current_app) mail.send_message( subject="Your YDP Project", recipients=[project.poster.email], body= f"""Hello {project.poster.name},\n Your YCP Project Database project '{project.title}' has been modified by an admin""" ) return redirect( url_for('ProjectView:view', id=project.id, is_provided=Tests.is_provided_test(project))) else: for field in form: if hasattr(project, field.name): field.data = getattr(project, field.name) form.grade.data = project.grade.value form.degree.data = [ attribute.value for attribute in DegreeAttributes if getattr(project, attribute.name) ] return render_template('set_project_data.html', form=form, project=project)
def post(self): """ Request password reset """ schema = DaoRequestPasswordResetSchema() data = request.get_json() or {} try: data = schema.load(data) except ValidationError as errors: return ResultErrorSchema( message='Payload is invalid', errors=errors.messages, status_code=400 ).jsonify() # generate token to reset password s = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) token = s.dumps(data['email'], salt='reset-password') user = User.query.filter_by(email=data['email']).first() if user: # send email mail = Mail(current_app) link = f'{request.scheme}://{request.host}{url_for("app.views.auth.confirm_password_reset", token=token)}' body = render_template('mail_password_reset.html', link=link, totp=user.totp_enabled) # check if the email should be encrypted if user.gpg_enabled and user.gpg_fingerprint: pass # todo encrypt email mail.send_message("Password Recovery", recipients=[data['email']], html=body) return ResultErrorSchema( message='Request has been send. Check your inbox!', status_code=200 ).jsonify()
def changePassword(self): bold_start = "\033[1m" bold_end = "\033[0m" form = ChangePasswordForm() if request.method == 'POST' and check_password_hash( current_user.password, form.old_password.data): try: if current_user.email: current_user.update_password(form.new_password.data, form.confirm_new.data) ''' Passed mail in servlet because if I put it in the server it causes a circular error ''' mail = Mail() mail.init_app(current_app) mail.send_message(subject="PASSWORD CHANGED!", recipients=[current_user.email], html=render_template( 'pwd_update_email.html', username=current_user.username)) flash("Please login again") return redirect(url_for('UserView:logout')) except Exception as e: flash(str(e)) return render_template('change_pwd.html', form=form)
def send_mail(to, subject, **kwargs): # load email settings and update app config dynamically with open('mailconfig.py') as f: mailconfig = f.read() mailconfig = ast.literal_eval(mailconfig) mailconfig['MAIL_PASSWORD'] = base64.b64decode( mailconfig['MAIL_PASSWORD'].encode('utf8')).decode('utf8') app.config.update(mailconfig) # send email mail = Mail(app) msg = mail.send_message(subject, sender=('MSM Admin', app.config['MAIL_SENDER']), recipients=to, **kwargs)
def telegram(): if request.method == 'POST': form_name = request.form['form-name'] if form_name == "Enviar correo": mail = Mail(app) msg = mail.send_message(sender='*****@*****.**', recipients=['*****@*****.**'], body=request.form['mensaje'], subject=request.form['asunto']) if form_name == "Enviar telegram": nombre = request.form['nombre'] texto = request.form['texto'] chatid = 'CHAT_ID' bot.send_message(chatid, nombre + ": " + texto) flash('Mensaje enviado existosamente', "success") return render_template('telegram.html') return render_template('telegram.html')
def kirim_email(to, subject, template): message = Message(subject=app.FormulirPendaftaran.email, recipients=[to], html=template, sender=app.app.config['MAIL_DEFAULT_SENDER']) Mail.send_message(message)
app.config['MAIL_USERNAME'] = mail_user app.config['MAIL_PASSWORD'] = mail_pass app.config['MAIL_SUPPRESS_SEND'] = False # Create database connection object db = MongoEngine(app) #Bootstrap Bootstrap(app) #Setup Mail mail = Mail(app) mail.init_app(app) # mail test with mail.record_messages() as outbox: mail.send_message(subject='testing', body='test', recipients=['*****@*****.**']) assert len(outbox) == 1 assert outbox[0].subject == "testing" # Setup Flask-Security user_datastore = MongoEngineUserDatastore(db, User, Role) security = Security(app, user_datastore, confirm_register_form=ExtendedConfirmRegisterForm) #security = Security(app, user_datastore) @app.route('/') def index():
app.config['MAIL_PASSWORD'] = mail_pass app.config['MAIL_SUPPRESS_SEND'] = False # Create database connection object db = MongoEngine(app) #Bootstrap Bootstrap(app) #Setup Mail mail = Mail(app) mail.init_app(app) # mail test with mail.record_messages() as outbox: mail.send_message(subject='testing', body='test', recipients=['*****@*****.**']) assert len(outbox) == 1 assert outbox[0].subject == "testing" # Setup Flask-Security user_datastore = MongoEngineUserDatastore(db, User, Role) security = Security(app, user_datastore, confirm_register_form=ExtendedConfirmRegisterForm) #security = Security(app, user_datastore) @app.route('/') def index(): return render_template('index.html')