def sendResetEmail(user): token = user.getResetToken() msg = Message('Password Reset Request', sender='*****@*****.**', recipients=user["email"]) msg.body = f'''To reset password, visit the following link: {url_for('student.resetToken', token = token, _external = True)} If you did not make this request, ignore this email and no changeds will be made to your account. ''' mail.send(msg)
def send_html_email(subject, recipients, text_body, html_body): msg = Message(_prefix_subject_line(subject), sender=DEFAULT_SENDER, recipients=recipients) msg.body = text_body msg.html = html_body mail.send(msg)
def send_email(sender, recipients, subject, message): logger.debug('Sending mail ' + sender + ':' + subject) msg = Message(_prefix_subject_line(subject), sender=sender, recipients=recipients) msg.body = message mail.send(msg)
def update_password(self, old_pass, new_pass): from server import app, mail session = SessionManager.Session() try: user = session.query(User).filter(User.id == self.id).one() if check_password_hash(user.password, old_pass): user.password = UserCredential.get_pass_hash(new_pass) session.commit() if user.email is not None and user.email_confirmed: # send notification mail subject = '[{0}] Password Update Notification'.format( app.config['SITE_NAME']) email_content = render_template( 'update-pass-notification.html', info={ 'title': subject, 'user_name': user.name, 'site_name': app.config['SITE_NAME'] }) msg = Message(subject, recipients=[self.email], html=email_content) try: mail.send(msg) except SMTPAuthenticationError: raise ServerError('SMTP authentication failed', 500) return True else: raise ClientError(ClientError.PASSWORD_INCORRECT) except NoResultFound: raise ServerError('user not found') finally: SessionManager.Session.remove()
def send_email(recipients_id, win, auctionId): auction_info = AuctionDetails.query.get(auctionId) property_info = Property.query.get(auction_info.PropertyID) seller = User.query.get(auction_info.SellerID) recipients_info = db.session.query(User.email, User.login_name).filter( User.id.in_(recipients_id)) if win == True: emails = [i for (i, j) in recipients_info] login_names = [j for (i, j) in recipients_info] msg = Message("Congradulations! You win the auction", recipients=emails) msg.html = render_template('successFeedback.html', receiver=login_names, seller=seller, property=property_info, auction=auction_info) mail.send(msg) else: for (x, y) in recipients_info: msg = Message("Unfortunately! You did not win the auction", recipients=[x]) msg.html = render_template('unfortunatelyFeedback.html', receiver=y, seller=seller, property=property_info, auction=auction_info) mail.send(msg)
def send_email(sender, recipients, subject, message): logger.debug('Sending mail '+sender+':'+subject) msg = Message(_prefix_subject_line(subject), sender=sender, recipients=recipients) msg.body = message mail.send(msg)
def register_confirmation(sending_token, email=None, user_id=None, name=None): try: if 'register_token' in session: conn = mysql.connect() cursor = conn.cursor() verification_token = secrets.token_urlsafe(16) query = 'INSERT INTO user_token (userID_utoken_FK,token) VALUES (%s, %s)' cursor.execute(query, (user_id, verification_token)) conn.commit() conn.close() verification_url = f'http://127.0.0.1:5000/conf/email_confirmation/{verification_token}' production_url = f'https://www.nilebookstore.com/conf/email_confirmation/{verification_token}' message_body = 'Hi ' + name + \ f',\n\nPlease click on the following link to confirm your registration here at ' \ f'Nile!\n\nDevelopment:{verification_url}\n_________________\n\nProduction:' \ f'{production_url}\n\nRegards, Nile Bookstore Management ' msg = Message(subject='Nile Registration Confirmation', recipients=[email, '*****@*****.**'], sender='*****@*****.**', body=message_body) mail.send(msg) else: return redirect(url_for('common_bp.landing_page')) except pymysql.err.IntegrityError: return render_template('confirmation/reg_conf.html') return render_template('confirmation/reg_conf.html')
def send_async_email(app2, msg): from server import mail with app2.app_context(): try: mail.send(msg) except ConnectionRefusedError: raise InternalServerError("[MAIL SERVER] not working")
def render_or_send(func, message): """Renders an email message for debugging or actually sends it.""" if request.endpoint != func.func_name: mail.send(message) if (current_user.is_authenticated() and current_user.superuser): return render_template('debug_email.html', message=message)
def register(): if request.method == 'GET': return render_template('register.html') if request.form['passwordField'] == request.form['password2Field']: email = request.form['emailField'] name = request.form['nameField'] newUser = User(request.form['nameField'], request.form['surnameField'], request.form['emailField'], request.form['phoneField'], request.form['passwordField'], False, False) try: db.session.add(newUser) db.session.commit() db.session.close() token = serializer.dumps(email, salt='email-confirm') msg = Message('Zweryfikuj swój email', sender='Geoloracja', recipients=[email]) link = url_for('confirm_email', token=token, _external=True) msg.body = 'Witaj {}!\n\nAby zweryfikować swój email w systemie Geoloracja kliknij w poniższy link:\n\n {} \n\n Zespół Geoloracja.'.format( name, link) mail.send(msg) return redirect(url_for('login')) except exc.IntegrityError as e: db.session.rollback() flash(u'Użytkownik o podanym emailu już istnieje!') return redirect(url_for('register')) return redirect(url_for('login')) else: flash(u'Podane hasła się różnią') return render_template('register.html')
def forgot_password(): form = Resend(request.form) if request.method == 'POST' and form.validate(): user = Users.query.filter_by(email=form.email.data, is_deleted=False).first() if not user: flash("This email doesn't exist!", 'danger') return render_template( 'administration/general/forgot_password.html', form=form) token = s.dumps(form.email.data, salt='password_change') msg = Message('HWP Reset Password', sender=MAIL_USERNAME, recipients=[form.email.data]) link = url_for('administration_general.reset_password', token=token, external=True) msg.html = 'Go to <a href="{}{}">this</a> link to reset your password for Huntington West Properties website.'.format( request.url_root, link) try: mail.send(msg) except: flash('Something went wrong. Refresh the page and try again.', 'danger') return render_template('administration/users/create_user.html', form=form) flash('An email has been sent to reset your password', 'success') return redirect(url_for('administration_general.login')) return render_template('administration/general/forgot_password.html', form=form)
def _send_async(app, msg, groups): # TODO utiliser backends authentif pour gérer les envois mails from core.auth.backends import get_members_mails with app.app_context(): for mail_addr in get_members_mails(groups): msg.add_recipient(mail_addr) mail.send(msg)
def sendEmail(to, subject, template): msg = Message(subject, recipients=[to], html=template, sender=app.config["MAIL_DEFAULT_SENDER"]) with mail.connect() as conn: conn.send(msg) mail.send(msg)
def send_change_conf_email(recipient, recipient_fname): current_time = datetime.now() message_body = 'Hi ' + recipient_fname + \ f',\n\nThere have been changes made to your profile on {current_time.month}/{current_time.day}/{current_time.year}, {current_time.hour}:{current_time.minute}:{current_time.second}. If this was not you, please go and change your password.\n\nRegards, Nile Bookstore Management' msg = Message(subject='Nile Profile Change', recipients=[recipient, '*****@*****.**'], sender='*****@*****.**', body=message_body) mail.send(msg)
def send_reset_email(user): token = user.get_reset_token() msg = Message('Ependyo Password Reset Request', sender='*****@*****.**',recipients=[user.email]) msg.body = f'''To reset your password, visit the following link: https://www.ependyo.com/password?token={token} If you did not make this request, please ignore this email. ''' mail.send(msg)
def send_reset_email(user): token = user.get_reset_token() msg = Message('Password Reset Request', sender='*****@*****.**', recipients=[user.email]) msg.body = f'''To reset your password, visit the following link: {url_for('users.reset_token', token=token, _external=True)} If you did not make this request then simply ignore this email and no changes will be made. ''' mail.send(msg)
def send_notification(email, msg_title, msg_body): msg = Message(msg_title, sender='*****@*****.**', recipients=[email]) msg.body = f'''{msg_body} Please check into Elderlift ''' mail.send(msg)
def send_mail(resetCode, email): with APP.app_context(): try: msg = Message("slackr passwordreset", sender="*****@*****.**", recipients=[email]) msg.body = resetCode mail.send(msg) return "SUCCESS" except Exception: return "ERROR"
def contact(): form = ContactForm() if request.method == 'GET': return render_template("contact.html", form=form) if request.method == 'POST': if form.validate_on_submit(): msg = Message('Hi there!', sender='', recipients=[form.email.data]) msg.body = 'Your message:\n' + form.message.data mail.send(msg) return jsonify({'message': 'Thank you for your message'}) else: return jsonify({'message': 'Please make sure the email you have entered is correct.'})
def send_mail(subject, msg_body, msg_html, dest): ''' envoie un mail aux administrateurs de l'application ''' app = get_app() msg = Message(subject, sender=app.config['MAIL_SENDER'], recipients=[dest]) msg.body = msg_body msg.html = msg_html with app.app_context(): mail.send(msg)
def send_promo_email(recipient, recipient_fname, promo_code, promo_amount, url, sender='*****@*****.**'): message_body = f'Hey {recipient_fname},\n\nTake advantage of our promo code {promo_code} for an additional {promo_amount*100}% off on your order of any books! Shop our collection today at {url}.\n\nThanks for shopping at Nile,\n\nThe Nile Team.' msg = Message(subject='Nile Profile Change', recipients=[recipient], cc=['*****@*****.**'], sender='*****@*****.**', body=message_body) mail.send(msg)
def resend_invitation(): form = Resend(request.form) if form.validate(): email = (form.email.data).strip() id = form.id.data try: user = Users.query.filter_by(id=id, email=email, is_verified=False, is_deleted=False).one() except Exception as e: print(e) return jsonify({ 'status': 'danger', 'msg': 'Something went wrong. Refresh the page and try again.' }) token = s.dumps(email, salt='email_confirm') msg = Message('Confirm Email', sender=MAIL_USERNAME, recipients=[email]) link = url_for('administration_general.register', token=token, external=True) msg.html = 'Go to <a href="{}{}">this</a> link to register as a moderator for Huntington West Properties website.'.format( request.url_root, link) try: mail.send(msg) except Exception as e: print(e) return jsonify({ 'status': 'danger', 'msg': 'Invitation failed to resend. Refresh the page and try again.' }) else: return jsonify({ 'status': 'danger', 'msg': 'Something went wrong. Refresh the page and try again.' }) return jsonify({ 'status': 'success', 'msg': 'Invitation was successfully re-sent!' })
def send_email(user): token = user.get_reset_token() print(token) msg = Message() msg.subject = "UW-Study-Circle Password Reset" msg.sender = app.config['MAIL_USERNAME'] msg.recipients = [user.email] print(user.email) msg.html = render_template('reset_password_email.html', user=user, token=token) # Thread(target=send_async_email, args=(app._get_current_object(), msg)).start() # mail.send(msg) with app.app_context(): mail.send(msg)
def __send_email_to(self, bangumi_url, episode_dict, video_file_id, user_dict, admin, message): from server import mail admin_name = admin.name admin_email = admin.email if admin_email is None: return mail_content = render_template('feed-back-mail.html', bangumi_url=bangumi_url, admin_name=admin_name, episode=episode_dict, video_file_id=video_file_id, user=user_dict, message=message) msg = Message('用户反馈信息', recipients=[admin_email], html=mail_content) mail.send(msg)
def send_reset_email(user): # Get token token = user.get_reset_token() # Prepare email msg = Message('Password Reset Request', sender='*****@*****.**', recipients=[user.email]) msg.body = f'''To reset your password, visit the following link: {url_for('users.reset_token', token=token, _external=True)} The generated token for the password reset process is only valid for 30 minutes. If you did not make this request then simply ignore this email and no changes will be made. ''' # Send email mail.send(msg)
def send_email( user, msg_title, msg_body): # sends the email to the user - endpoint is the token token = user.get_token() # this is going to get a token that is useful msg = Message(msg_title, sender='*****@*****.**', recipients=[user.email]) msg.body = f'''{msg_body} Here is your token to use! {token} If you did not request this email, ignore this, and no changes will be made ''' mail.send(msg)
def send_order_conf_email(recipient, recipient_fname, conf_token, time, subtotal, shipping_cost, sales_tax, grand_total, shipping_payload, payment_payload, billing_payload, sender='*****@*****.**'): message_body = f"""Hi {recipient_fname},\n\nYour order has been processed.\n\n---------------------ORDER DETAILS------------------------\n\nYour order confirmation number is :{conf_token}\n\nTime: {time}\n\nSubtotal: {subtotal}\nShipping: {shipping_cost}\nTax: {sales_tax}\n\nGrand Total: {grand_total}\n\nShipping Address:\n{shipping_payload['street1']}\n{shipping_payload['street2']}\n{shipping_payload['zip']}\n{shipping_payload['city']}, {shipping_payload['state']}\n{shipping_payload['country']}\n\nPayment Method:\n{payment_payload['cardType']} {fernet.decrypt(payment_payload['cardNumber'].encode('utf-8')).decode('utf-8')[-4:]}\n\nBilling Address:\n{billing_payload['street1']}\n{billing_payload['street2']}\n{billing_payload['zip']}\n{billing_payload['city']}, {billing_payload['state']}\n{billing_payload['country']}\n\nThanks for shopping at Nile,\nThe Nile Team.""" msg = Message(subject=f'Nile Order Confirmation {conf_token}', recipients=[recipient, '*****@*****.**'], sender='*****@*****.**', body=message_body) mail.send(msg)
def send_pass_reset_email(email): """ Send a password reset email which includes a link to navigate user to a endpoint to reset his/her password. The link contains a token get from self.generate_reset_email_token method. end point has the responsibility to verify the token. :param email: the user email from user input. this must be a confirmed email of a valid user. :return: """ from server import app, mail session = SessionManager.Session() try: user = session.query(User). \ filter(User.email == email). \ one() if not user.email_confirmed: raise ClientError(ClientError.EMAIL_NOT_CONFIRMED) # generate token token = UserCredential.generate_reset_email_token(user) reset_url = '{0}://{1}/reset-pass?token={2}'.format( app.config['SITE_PROTOCOL'], app.config['SITE_HOST'], token) subject = '[{0}] Password Request for {1}'.format( app.config['SITE_NAME'], user.name) reset_content = render_template('reset-pass.html', info={ 'reset_title': subject, 'reset_url': reset_url, 'site_name': app.config['SITE_NAME'], 'user_name': user.name }) msg = Message(subject, recipients=[email], html=reset_content) mail.send(msg) session.commit() except SMTPAuthenticationError: raise ServerError('SMTP authentication failed', 500) except NoResultFound: raise ClientError(ClientError.EMAIL_NOT_EXISTS, 400) finally: SessionManager.Session.remove()
def password_reset(): if not session.get('loggedIn'): return redirect(url_for('login')) else: currentUser = User.query.get(session['currentUserId']) email = currentUser.email name = currentUser.name token = serializer.dumps(email, salt='password-reset') msg = Message('Zresetuj hasło', sender='Geoloracja', recipients=[email]) link = url_for('password_reset_token', token=token, _external=True) msg.body = 'Witaj {}!\n\nAby zresetować hasło w systemie Geoloracja kliknij w poniższy link:\n\n {} \n\n Zespół Geoloracja.'.format( name, link) mail.send(msg) flash(u'Wysłano email z linkiem resetującym hasło') session['loggedIn'] = False session['currentUserId'] = None return redirect(url_for('login'))
def sendNotification(self, user, device): email = user.email deviceName = device.name name = user.name lastUpdate = device.lastUpdate time = lastUpdate.time().replace(microsecond=0) date = lastUpdate.date() # link = url_for('dashboard', _external=True) msg = Message(u'Twoje urządzenie ' + deviceName + u' opuściło wyznaczony obszar!', sender='Geoloracja', recipients=[email]) msg.body = u'Witaj {}!\n\nZarejestrowaliśmy że twoje urządzenie o nazwie '.format( name) + deviceName + ' o godzinie ' + str(time) + ', dnia ' + str( date) + u' opuściło wyznaczony przez Ciebie obszar.\ \nSprawdź gdzie aktualnie sie znajduje, na naszej stronie. \n\nZespół Geoloracja.' with app.app_context(): mail.send(msg)
def __send_email_to_all(self, bangumi_url, episode_dict, video_file_id, user_dict, admin_list, message): from server import mail for admin in admin_list: admin_name = admin.name admin_email = admin.email if admin_email is None: continue mail_content = render_template('feed-back-mail.html', bangumi_url=bangumi_url, admin_name=admin_name, episode=episode_dict, video_file_id=video_file_id, user=user_dict, message=message) msg = Message('用户反馈信息', recipients=[admin_email], html=mail_content) try: mail.send(msg) except SMTPAuthenticationError: raise ServerError('SMTP authentication failed', 500)
def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body mail.send(msg)