def send_email(to, subject, template, **kwargs): msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) mail.send(msg)
def signup(): if current_user.is_authenticated: return redirect(url_for('web.index')) form_data = {} if request.method == 'POST': validation_result = validate_registration_form(request.form.to_dict()) if ValidationResults.SUCCESS in validation_result: try: user = User(request.form) token = s.dumps(user.email, salt=current_app.config.get('MAIL_SALT')) msg = generate_confirmation_mail(user.email, token) mail.send(msg) add_new_user(user) session['email_to_confirm'] = user.email return redirect(url_for('web.finish_signup')) except Exception as ex: flash(str(ex)) for message in validation_result: flash(message.value) form_data = request.form return render_template( 'signup.html', google_client_key=current_app.config.get('GOOGLE_CLIENT_KEY'), form_data=form_data)
def flag(type_=None, postid=None): if not session.get('logged_in'): return redirect(url_for("index")) if type_ not in ["1","2","3","4"] or postid == None: abort(404) post = Posts.objects.get(postid=postid) if User.objects.get(alias=session.get("alias")) in post.flaggedBy: return redirect(url_for("index")) post.flaggedBy.append(User.objects.get(alias=session.get("alias"))) post.flags += 1 post.flagTypes.append(int(type_)) post.save() mods = User.objects(isMod = True) mod_emails = [] for mod in mods: mod_emails.append(mod.email) msg = Message("Post has been flagged", sender="*****@*****.**", recipients=mod_emails) msg.body = "{0} has flagged a post by {1} entitled {2} for {3}".format(session.get("alias"), post.author.alias, post.title, type_) mail.send(msg) flash("You have flagged {0} by {1}".format(post.title, post.author.alias)) return redirect(url_for("viewPost", pid=postid))
def send_email(app, subject, recipient, content): with app.app_context(): msg = Message(subject, sender=os.getenv("MAIL_USERNAME"), recipients=[recipient], html=content) mail.send(msg)
def send_email(to, subject, template, **kwargs): msg = Message(app.config["WEBCHAT_MAIL_SUBJECT_PREFIX"] + subject, sender=app.config["WEBCHAT_MAIL_SENDER"], recipients=[to]) msg.body = render_template(template + ".txt", **kwargs) msg.html = render_template(template + ".html", **kwargs) mail.send(msg)
def internal_server_error(e): message = repr(e) trace = traceback.format_exc() trace = string.split(trace, '\n') timestamp = (datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S')) if current_user.is_authenticated: user = current_user.username else: user = '******' gathered_data = ('message: {}\n\n\n' 'timestamp: {}\n' 'ip: {}\n' 'method: {}\n' 'request.scheme: {}\n' 'request.full_path: {}\n' 'user: {}\n\n\n' 'trace: {}'.format(message, timestamp, request.remote_addr, request.method, request.scheme, request.full_path, user, '\n'.join(trace))) # send email to admin if app.config['TESTING']: print(gathered_data) else: mail_message = gathered_data msg = Message('Error: ' + message[:40], body=mail_message, recipients=[app.config['ADMIN_MAIL']]) mail.send(msg) flash(_('A message has been sent to the administrator'), 'info') bookcloud_before_request() return render_template('500.html', message=gathered_data), 500
def register(): form = RegisterForm() if form.validate_on_submit(): result1 = form.check_email(form.email) if result1: result2 = form.check_username(form.username) if result2: user = User(first=form.first_name.data, last=form.last_name.data, email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() msg = Message('Successful Register', sender='*****@*****.**', recipients=[user.email]) msg.body = f'You have successfully registered for Roy BookStore! Come and buy books,{user.firstname}!' mail.send(msg) return redirect(url_for('login')) elif not result2: flash('Username already registered!') elif not result1: flash('Email already registered!') return render_template('register.html', form=form)
def save(self): email = self.email.data site_name = current_app.config['PROJECT_SITE_NAME'] site_url = current_app.config['PROJECT_SITE_URL'] sender = current_app.config['MAIL_DEFAULT_SENDER'] # create signed data s = get_signer() data = { 'email': email, 'signup': True } signed_data = s.dumps(data) # set context to template render context = dict( site_name=site_name, site_url=site_url, email=email, signed_data=signed_data ) # load template html = render_template( 'accounts/emails/signup.html', **context ) # create and send message msg = Message( u'Confirm your account - {0}.'.format(site_name), sender=sender, recipients=[email] ) msg.html = html mail.send(msg)
def call_to_pickup(run): recipients = [c.addict.email for c in run.coffees if c.addict.alerts] subject = "Alert: your coffee is ready to pickup!" body = "%s has taken your coffee to %s. Please go fetch and pay.\nRegards, your favourite Coffee Bot!" % ( run.fetcher.name, run.pickup) msg = Message(subject=subject, body=body, recipients=recipients) mail.send(msg)
def send_email(to, subject, template): msg = Message(subject, recipients=[to], html=template, sender='*****@*****.**') print(msg) mail.send(msg)
def send_async_email(app, msg): """ Allows sending of emails in the brackground without slowing the application down. """ with app.app_context(): mail.send(msg)
def verification_code(account_id: str, account_email: str): if is_none(account_id) or is_none(account_email): return response_util.http_bad_request('Fill all the request body!') else: verification_query = VerificationModel.query.filter_by( owner_id=account_id).first() if not verification_query: return response_util.http_not_found('account id not found!') else: generated_code = random.randint(000000, 999999) verification_query.code = generated_code try: db.session.commit() mail_message = Message( subject='Verification Code', html=render_template('mail_template.html', full_name=verification_query.name, code=generated_code), sender=('WarungKu', '*****@*****.**'), recipients=[account_email]) mail.send(mail_message) except HTTPException: return response_util.http_internal_server_error() token = security_util.access_token(account_id) return response_util.http_ok('Code verification has been sent!', { 'token': 'Bearer {}'.format(token), 'expired': '1 Minutes' })
def page(slug): form = None if not slug in ["disclaimer", "contact_us"]: return abort(404) if slug == "contact_us": form = ContactForm(request.values) if request.method == "POST" and form.validate_on_submit(): flash("contact_us_submitted") if not request.headers.getlist("X-Forwarded-For"): ip = request.remote_addr else: ip = request.headers.getlist("X-Forwarded-For")[0] subject = "{0} from {1}".format(dict(contact_topics)[form.topic.data], form.name.data) msg = Message(subject) msg.sender = "MyLust.XXX Contact Form <*****@*****.**>" msg.body = "{name} - {email} - {ip} \n\n{message}".format(name=form.name.data, email=form.email.data, ip=ip, message=form.message.data) msg.add_recipient(app.config["CONTACT_EMAIL"]) mail.send(msg) return redirect(url_for("catalog.page", slug="contact_us")) return render_template ( "catalog/page_{0}.html".format(slug), form=form, hide_search=True )
def notify_run_owner_of_coffee(owner, addict, coffee): if owner.alerts: recipients = [owner.email] run = coffee.run subject = "Alert: coffee added for run to %s at %s" % (run.cafe.name, run.readtime()) body = "%s has requested a coffee for run %d. See the NCSS Coffeerun site for details." % (addict.name, run.id) msg = Message(subject, recipients) mail.send(msg)
def send_email(subject, sender, recipients, text, bcc=None): from application import mail message = Message(subject, sender=sender, recipients=recipients, html=text, bcc=bcc) mail.send(message)
def send_async_email(app, msg): """app context automatically managed by Flask allows Flask to avoid passing args/instances across functions may need to be manually created for custom threads many extensions need to know app instance because their config stored in app.config app.app_context() makes app instance accessible via Flask's current_app""" with app.app_context(): mail.send(msg)
def send_notification(task): msg = Message( 'Task status has changed', sender=os.environ['WORK_MAIL'], recipients=[os.environ['ADMIN_EMAIL']] ) msg.body = f"The status of the task '{task.subject}' has been changed to '{task.status.value}'" mail.send(msg)
def send_reset_email(user): token = user.get_reset_token() msg = Message("Password Request Message") msg.sender = os.getenv('MAIL_USERNAME') msg.recipients = [user.user_email] msg.body = f''' Click the following link to proceed further: {url_for('users.reset_token', token=token, _external=True)} if You did\'nt make the request. Ignore this message. ''' mail.send(msg)
def send_email(subject, sender, recipients, text_body, html_body, sync=False): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body if sync: mail.send(msg) else: Thread(target=send_async_email, args=(current_app._get_current_object(), msg)).start()
def mailsend(): """Sends a test email through the makeuoft email account""" # msg = Message('Confirm Email', sender= '*****@*****.**', recipients= [session['email']]) msg = Message('Test', recipients=['*****@*****.**']) msg.body = 'This is a test' msg.html = render_template('mails/reset-password.html', username="******", link="github.com") mail.send(msg)
def send_reset_email(user): #token = user.get_reset_token() #expires_seconds=1800s default msg = Message('Password Reset Request', sender='*****@*****.**', recipients=[user.email]) msg.body = ''.join(["PASSWORD REST NOT SUPPORTED YET"]) mail.send(msg)
def send_newsletter_email(email, token): msg = Message('Newsletter subscription', sender='*****@*****.**', recipients=[email]) msg.body = f''' Thanks for signing up to our newsletter! To confirm your subscription, click the following URL (expires in 24 hours): {url_for('main.newsletter_signup_verify', token=token, _external=True)} If you did not sign up for our newsletter, don't click the above URL and no action will be taken. This is an automatic email. Please do not reply. ''' msg.html = render_template('confirm_email.html', link=url_for('main.newsletter_signup_verify', token=token, _external=True), title="Confirm your subscription", sub_title="Please confirm your subscription to our newsletter (links expire in 24 hours)", button_text="Confirm Your Subscription", bottom_header="Didn't sign up?", bottom_content="If you believe this was a mistake or you did not intend on subscribing to our newsletter, you can ignore this message and nothing will happen.") mail.send(msg)
def send_email(to, subject, template, **kwargs): subject = "欢迎注册CWY的网站" body = render_template(template + ".txt", **kwargs) message = Message(subject=subject, recipients=[to], body=body) try: mail.send(message) return True except Exception as e: return False
def sendCode(self, receiver, code): body = "您的验证码为: " + code + "\n,请尽快输入且不要透露给其他人" message = Message(subject=self.subject, recipients=[receiver], body=body) try: mail.send(message) return True except Exception as e: return False
def retrieve_password(email: str): user = models.User.query.filter_by(email=email).first() if user: msg = Message('your planetary API password is ' + user.password, sender='*****@*****.**', recipients=[email]) mail.send(msg) return jsonify(message='Password send to ' + email) else: return jsonify(message="The email doesn't exist..."), 401
def send_approvedApplication_email(user): token = user.get_reset_token() msg = Message('Your Application was Approved', sender='*****@*****.**', recipients=[user.email]) msg.body = f'''Congratulations! Your Application has been reviewed and has been approved. To set your new password, visit the following link: {url_for('reset_token', token=token, _external=True)} Welcome to Active Teaming System. ''' 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('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_confirmation_email(name, email): msg = Message("The Undefined Blog: Subscription Confirmation", sender=os.getenv("MAIL_USERNAME"), recipients=[email], body=f""" Dear {name}, You have successfully subscribed to The Undefined Blog! """) mail.send(msg)
def change_admin(superuser, username): g.user = None if 'user_id' in session: try: g.user = User.objects.get(pk=session['user_id']) if g.user.is_superuser: if superuser == "True": superuser = True else: superuser = False user_to_change = User.objects.filter(username=username).first() user_to_change.is_superuser = superuser user_to_change.change_superuser(is_superuser=superuser) flash( u'The admin privileges for the user %s was changed successfully.' % username, 'success') new_admin = User.objects.filter(username=username).first() if superuser and new_admin.is_superuser: try: site_name = current_app.config['PROJECT_SITE_NAME'] site_url = current_app.config['PROJECT_SITE_URL'] sender = current_app.config['MAIL_DEFAULT_SENDER'] # set context to template render context = dict(site_name=site_name, site_url=site_url, assign_by=g.user.name, new_admin_name=new_admin.name) # load template html = render_template( 'accounts/emails/admin_confirmation.html', **context) # create and send message msg = Message( u'Confirmation - admin privileges - {0}.'.format( site_name), sender=sender, recipients=[new_admin.email]) msg.html = html mail.send(msg) except: flash( u"Was not possible to send a confirmation by e-mail for the user %s." % new_admin.name, 'error') else: flash(u"You do not have permission!", 'error') except: flash( u'Was not possible to assign the admin privileges for the user %s.' % username, 'success') return redirect(url_for('accounts_app.manager_user'))
def send_contact_email(email, message, default_email="*****@*****.**"): msg = Message('Contact Form submitted on website', sender='*****@*****.**', recipients=[default_email]) msg.body = f''' Someone submitted a contact form on the Future Creators Website. They said their email was: {email} Their message is: {message} This is an automatic email. Please do not reply to the sender, but to the email the user specified. ''' msg.html = render_template('contact_email.html', link="mailto:" + email, title="Contact Form Submitted", sub_title="Someone submitted a contact form on the Future Creators Website", button_text="Reply", bottom_content="Email: " + email, bottom_header=message, bottom_top_header="Message:") mail.send(msg)
def sendMail(subject, sndr, body, email, email_type=False): try: msg = Message(subject, sender=sndr, recipients=[email]) if not email_type: msg.body = body else: msg.html = render_template("email.html", body=body) mail.send(msg) return 'Mail sent!' except Exception, e: return (str(e))
def signup(): """ Signup, creates a new user if the session is logged in return to index when form is valided if the passwords match and the password length is greater than 8 characters then create the password hash if it is not the throw errors try to create the user object and catch all expected erropasswordrs. """ form = SignupForm() error = None if session.get('logged_in'): return redirect(url_for('index')) if form.validate_on_submit(): if len(app.config.get("EMAIL_DOMAINS")) > 0: if not any(x in form.email.data for x in app.config.get("EMAIL_DOMAINS")): return render_template('signup.html', form = form, err = app.config.get("BAD_DOMAIN_MSG")), 400 elif form.password.data == form.password2.data and len(form.password.data) >= 8: pw_hash = generate_password_hash(form.password.data) try: user = User(email = form.email.data.lower(), alias = form.alias.data, password = pw_hash, color="#"+str(uuid.uuid4())[:6]) code = str(uuid.uuid4()) user.emailVerifyKey = code if len(User.objects) == 0: user.isMod = True user.isJudge = True msg = Message("Hello", sender="*****@*****.**", recipients=[form.email.data.lower()]) msg.body = url_for("verifyemail", code=code) msg.html = "<a href='http://"+app.config.get('DOMAIN')+url_for("verifyemail", code=code)+"'>Verify Here</a>" mail.send(msg) user.save() return render_template("signupLanding.html") #error = "Email not correct" except ValidationError: error = 'Email is not an email' except errors.NotUniqueError: error = 'Email or username is already in use' except: error = "Other Stupid Error"#is this for smtplib.SMTPAuthenticationError else: if len(form.password.data) < 8: error = 'Password too short' else: error = 'Passwords do not match' return render_template('signup.html', form = form, err = error)
def contact(): if request.method == 'POST': extra_headers = {} if 'return-addr' in request.form: extra_headers['Reply-To'] = request.form['return-addr']; with mail.record_messages() as outbox: msg = Message(recipients=[app.config['MAIL_DEFAULT_RECIPIENT']], subject="Contact form message from %s" % (app.config['SERVER_NAME'] if app.config['SERVER_NAME'] is not None else 'the website'), body=request.form['content'], extra_headers=extra_headers) mail.send(msg) sent = outbox[0] flash("Message has been sent.") return redirect(url_for('article')) article = models.Article.query.get('contact') return render_template('contact_form.html', article=article)
def send_security_email(msg): mail.send(msg)
def send_async_mail(msg): mail.send(msg)
def send_async_email(app, msg): with app.app_context(): mail.send(msg)
def send_async_email_helper(msg): with app.app_context(): mail.send(msg)
def send_email(to, subject, template, **kwargs): msg = Message(app.config["WEBCHAT_MAIL_SUBJECT_PREFIX"]+subject, sender=app.config["WEBCHAT_MAIL_SENDER"], recipients=[to]) msg.body = render_template(template + ".txt", **kwargs) msg.html = render_template(template + ".html", **kwargs) mail.send(msg)