def post(self): args = email_post_parser.parse_args() email = email_type(args['email']) user = User.verify_auth_token(args['token']) if not user: raise InvalidToken() dup_email = User.query.filter_by(email=email).first() if dup_email: raise DuplicateInfo('该邮箱已被绑定') if user.email: user.confirmed = False user.email = email db.session.add(user) db.session.commit() token = user.generate_confirmation_token().decode() send_email(email, '确认你的邮件', 'email/confirm', token=token) return {'message': '确认邮件已发送'}, 200
def post(self): verify_post_parser = reqparse.RequestParser() verify_post_parser.add_argument( 'nickname', type=str, required=True ) verify_post_parser.add_argument( 'email', type=str, required=True ) args = verify_post_parser.parse_args() user = User.query.filter_by(nickname=args['nickname']).first() if not user or not user.email or user.email != args['email']: raise WrongInfo('邮箱或用户名错误') verify_token = Verify.generate_confirmation_token( args['nickname'], args['email']).decode() send_email(args['email'], '查收重置密码的 token', 'email/confirm', token=verify_token) return {'message': '邮件已发送'}, 200
def index(): req_data = request.form if req_data.get("user_name") != None: if User.query.filter_by( user_name=req_data.get("user_name")).first() == None: new_user = User(user_name=req_data.get("user_name"), user_image=request.files.get("image").read(), user_email_adrs=req_data.get("email"), user_password=req_data.get("user_password")) db.session.add(new_user) db.session.commit() email = new_user.user_email_adrs email_token = token_serializer.dumps(email, salt='email-confirmation') salutation = "hi-NewUser{}".format(req_data.get("user_name")) text_message = 'click on the link for account confirm <a href="http://127.0.0.1:5000' + url_for( '.email_token_varify', token=email_token) + '"> click to account confirmations</a>' htmk_message = 'click on the link for account confirm <a href="http://127.0.0.1:5000' + url_for( '.email_token_varify', token=email_token) + '"> click to account confirmations</a>' send_email(salutation, "*****@*****.**", [email], "hi kio" + text_message, "<h1>hello kioplolo<h2>" + htmk_message + "</h2></h1>") return { 'req': str(req_data.get("user_name")), "heeloo from th blurpints": str(datetime.utcnow()), 'token': email_token }
def test_send_email(test_app, mocker, sender, config_set_arg, config_set, tags): """Tests the send_email function.""" mocked_boto3_client = mocker.patch('app.emails.boto3.client') mocked_boto3_client_instance = mocked_boto3_client.return_value mocked_render_template = mocker.patch('app.emails.render_template') mocked_template_html = mocked_render_template.return_value test_app.config['NO_EMAIL'] = False with test_app.app_context(): test_app.config['SES_REGION_NAME'] = 'foo' test_app.config['AWS_ACCESS_KEY_ID'] = 'bar' test_app.config['AWS_SECRET_ACCESS_KEY'] = 'baz' test_app.config['SES_DEFAULT_EMAIL_SOURCE'] = '*****@*****.**' send_email('foo', ['bar'], 'foo.html', {'baz': 'qux'}, sender=sender, configuration_set_name=config_set_arg) mocked_boto3_client.assert_called_with( 'ses', region_name='foo', aws_access_key_id='bar', aws_secret_access_key='baz') mocked_render_template.assert_called_with('foo.html', baz='qux') mocked_boto3_client_instance.send_email.assert_called_with( Source='*****@*****.**', Destination={'ToAddresses': ['bar']}, Message={ 'Subject': {'Data': 'foo'}, 'Body': { 'Html': {'Data': mocked_template_html} } }, ConfigurationSetName=config_set, Tags=tags )
def signup(): form = SignupForm() if g.user is not None and g.user.is_authenticated: return redirect(url_for('.user', nickname = g.user.nickname)) if request.method == 'POST': if form.validate() is False: return render_template('auth/register.html', form=form) else: nickname = form.email.data.split('@')[0] nickname = User.make_unique_nickname(nickname) if form.user_role.data == 'adviser': role = ROLE_ADVISER elif form.user_role.data == 'applicant': role = ROLE_APPLICANT user = User(nickname, form.firstname.data, form.lastname.data, form.email.data, form.password.data, role) user.role = role db.session.add(user) db.session.commit() #send activation email token = user.generate_confirmation_token() send_email(user.email, 'Confirm Your Account', 'auth/confirm', user=user, token=token) flash('Registration was successful.' 'Please click the activation link sent to your email to activate your account.') return redirect(url_for('auth.login')) elif request.method == 'GET': return render_template('auth/register.html', form=form)
def send_password_reset_email(employee): token = employee.get_reset_password_token() send_email('[CompensationManagementSystem] Reset Your Password', sender=app.config['ADMINS'][0], recipients=[employee.email], text_body=render_template('emails/reset_password.txt', employee=employee, token=token), html_body=render_template('emails/reset_password.html', employee=employee, token=token))
def send_password_reset_email(user): token = user.get_reset_password_token() send_email(_('[Microblog] Reset Your Password'), sender=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 resend_confirmation(): if current_user.confirmed: return redirect(url_for('main.home')) else: token = current_user.generate_confirmation_token() send_email(current_user.email, 'Confirm your Account', 'auth/mail/confirm', user=current_user, token=token) flash('A new mail has been sent') return redirect(url_for('main.home'))
def place_order(email, orders): total = 0 for order in orders: db.session.add(order) total += order.cost db.session.commit() activation_link = get_activation_link(orders) letter = render_template("emails/confirmation.txt", orders=orders, link=activation_link, total=total) send_email("Order confirmation", [email], letter)
def send_activated_email(user_email, user_email_hash): """Sends an email telling a user that they've been authorized. Args: user_email: the email address of the user. user_email_hash: the hash of the user's email address. """ send_email( 'You\'re all set to access our benchmarks!', [user_email], 'activated-email.html', { 'title': 'You\'re all set to access our benchmarks!', 'email_hash': user_email_hash })
def send_password_reset_email(user): token = user.get_reset_password_token() send_email( '[Tweeter] Reset Your Password', sender=current_app.config['ADMINS'] [0], # from admin email specified in config.py recipients=[user.email], # send to user's 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_reset_email(sender, user): token=user.get_reset_token() body=render_template('mail/reset-password-mail.txt', token=token, user=user, website=url_for('app.main.index')) html=render_template('mail/reset-password-mail.html', token=token, user=user, website=url_for('app.main.index')) send_email(sender=sender, subject='Reset Password Request - [Alium || Resume Builder]', recipient=user.email, body=body, html=html)
def payBillForm(): form = PayBillForm() allCards = Card.query.all() cards = [] for card in allCards: if card.cardHolderRef == current_user.id: cards.append(card) if form.validate_on_submit(): mycard = request.form.get('card') mycard = mycard.split(",") amount = float(form.amount.data) * 100 str(amount) payment = { "amount": form.amount.data, "description": form.description.data, "card": { "number": mycard[0], "cvv": mycard[1], "expMonth": mycard[2], "expYear": mycard[3] } } ###############Add payment to it's database here######### dbpayment = Payment(company="Utility", amount=form.amount.data, description=form.description.data, paymentMakerRef=current_user.id, paymentCardRef=mycard[0]) db.session.add(dbpayment) db.session.commit() ###############Add payment to it's database here######### payment = simplify.Payment.create(payment) # card = Card(addressState=form.addressState.data,expMonth=form.expMonth.data, expYear=form.expYear.data, # addressCity=form.addressCity.data,addressZip=form.addressZip.data,cvv=form.cvv.data, number=form.number.data) flash('Payment was succesfully!') amount = form.amount.data #sms(amount) user = Customer.query.get(current_user.id) email = user.email send_email('Payment Recieved', [email], render_template("payment_email.html", fname=user.fname)) return redirect(url_for('index')) return render_template('payBillForm.html', title='Pay Bill', form=form, cards=cards)
def reset_password_request(): form = PasswordResetRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data.lower()).first() if user: token = user.generate_reset_token() send_email(form.email.data, 'Password Reset', 'auth/mail/reset_password', token=token, user=current_user) flash('Password reset link sent with instructions') else: flash('Invalid email') return render_template('auth/forgot_password_request.html', form=form)
def on_failure(self, exc, task_id, args, kwargs, einfo): from app.emails import send_email error_details = OrderedDict( [('Exception', exc), ('Task ID', task_id), ('Args', args), ('Kwargs', kwargs), ('Stack Trace', traceback.format_exception( None, exc, einfo.tb))]) send_email( 'Application Error (Celery Task)', [os.environ.get('ADMIN_EMAIL')], 'error-email-internal.html', {'error_details': error_details}, error=True)
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, '请确认你的邮箱地址', 'auth/email/change_email', user=current_user, token=token) flash('一封带有确认你新邮箱地址说明的邮件已经发送给你') return redirect(url_for('main.index')) else: flash('不合法的邮箱或密码') return render_template('auth/change_email.html', form=form)
def update_email(): form = UpdateEmailForm() if form.validate_on_submit(): if current_user.verify_password(form.password.data): new_email = form.email.data.lower() session['new_email'] = new_email token = current_user.generate_email_update_token( new_email=new_email) send_email(new_email, 'Account Updated', 'auth/mail/update_email', token=token) flash('mail sent with instructions') return redirect(url_for('main.home')) else: flash('Check your password') return render_template('auth/update_email.html', form=form)
def reg(): if g.user is not None and g.user.is_authenticated: return redirect(url_for('index')) form = RegForm() if form.validate_on_submit(): respemail = form.email.data respepassword = form.password.data nickname = "" if nickname is None or nickname == "": nickname = respemail.split('@')[0] nickname = User.make_valid_nickname(nickname) nickname = User.make_unique_nickname(nickname) user = User(nickname=nickname, email=respemail, password=respepassword) db.session.add(user) db.session.commit() newuser = User.query.filter_by(email=respemail).first_or_404() db.session.add(newuser.follow(newuser)) # 关注自己 db.session.commit() # 发送邮件 subject = sting_utf8("确认你的邮箱") token = ts.dumps(newuser.email, salt='email-confirm-key') confirm_url = url_for('confirm_email', token=token, _external=True) txt = render_template('member/email_confirm.txt', confirm_url=confirm_url) html = render_template('member/email_confirm.html', confirm_url=confirm_url) send_email(subject, '', [newuser.email], txt, html) remember_me = False if 'remember_me' in session: remember_me = session['remember_me'] session.pop('remember_me', None) login_user(user, remember=remember_me) return redirect(request.args.get('next') or url_for('index')) return render_template('member/reg.html', title=sting_utf8('注册'), form=form, providers=app.config['OPENID_PROVIDERS'])
def registe(): form = RegisteForm() if form.validate_on_submit(): user = User(email=form.email.data, name=form.name.data) user.password = form.password.data db.session.add(user) db.session.commit() token = user.generate_registe_token() send_email(form.email.data, 'Confirm Your Account', 'auth/email/confirm', user=user, token=token) flash('A email has been sent to your email') return redirect(url_for('main.index')) return render_template('auth/registe.html', form=form)
def test_send_error_email_or_email_disabled(test_app, mocker, caplog): """Tests the send_email function for an error email or if NO_EMAIL is set.""" mocked_boto3_client = mocker.patch('app.emails.boto3.client') mocker.patch('app.emails.render_template') test_app.config['NO_EMAIL'] = True with test_app.app_context(): test_app.config['SES_REGION_NAME'] = 'foo' test_app.config['AWS_ACCESS_KEY_ID'] = 'bar' test_app.config['AWS_SECRET_ACCESS_KEY'] = 'baz' test_app.config['SES_DEFAULT_EMAIL_SOURCE'] = '*****@*****.**' send_email('foo', ['bar'], 'foo.html', {}) log_text = ('NO_EMAIL environment variable set. ' 'Suppressing an email with the following params: ' 'Sender: {}. Recipients: {}. Subject: {}.'.format( '*****@*****.**', ['bar'], 'foo')) assert log_text in caplog.text mocked_boto3_client.return_value.send_email.assert_not_called()
def register(): form = RegisterForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data.lower(), password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, 'Account confirmation', 'auth/mail/confirm', user=user, token=token) flash('Account created,Login to continue') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
def contact(): form = ContactForm() if request.method == 'POST': if form.validate() is False: flash('All fields are required.') return render_template('contact.html', form=form) else: #text_body = """ #From: %s < %s > #%s """ % (form.name.data, form.email.data, form.message.data) #send_email(ADMINS[0], form.subject.data, text_body) send_email(ADMINS[0], form.subject.data, 'auth/contact', form=form) return render_template('contact.html', success=True) elif request.method == 'GET': return render_template('contact.html', form=form)
def contact(): form = ContactForm() if request.method == 'POST': if form.validate() is False: flash('All fields are required.') return render_template('contact.html', form=form) else: #text_body = """ #From: %s < %s > #%s """ % (form.name.data, form.email.data, form.message.data) #send_email(ADMINS[0], form.subject.data, text_body) send_email(ADMINS[0], form.subject.data, 'auth/contact', form=form) return render_template('contact.html', success=True) elif request.method == 'GET': return render_template('contact.html', form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): customer = Customer(email=form.email.data, phone=form.phone.data, fname=form.fname.data, lname=form.lname.data) customer.set_password(form.password.data) send_email( 'Registration Complete', [form.email.data], render_template("register_email.html", fname=form.fname.data)) db.session.add(customer) db.session.commit() flash('Congratulations, you are now registered!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def password_reset_request(): ''' 密码重置请求 :return: ''' if not current_user.is_anonymous: return render_template('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, '重置你的密码', 'auth/email/reset_password', user=user, token=token) flash('一封指示重置密码的电子邮件已经发送给你') #print('An email with instructions to reset your password has been sent to you') return redirect(url_for('auth.login')) return render_template('auth/password_reset.html', form=form)
def register(): ''' 用户注册,并给所注册email发送验证邮件 :return: ''' form = RegisterationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, '请确认你的帐号', 'auth/email/confirm', user=user, token=token) flash('一封确认邮件已经发到你的邮箱喽,请注意查收呀.') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
def post(self, request): register_form = UserRegisterForm(request.POST) if register_form.is_valid(): user = register_form.save() user.is_active = False user.set_password(request.POST['password1']) user.save() uid = urlsafe_base64_encode(force_bytes(user.pk)) activate_url = "{}/{}/{}".format( "http://localhost:8000/activate", uid, default_token_generator.make_token(user=user) ) send_email( recipient_list=[user.email], activate_url=activate_url ) return HttpResponse("Check your email list to activate account!") return HttpResponse("Wrong Data")
def send_resume_as_mail(user): template = f'user-{user.current_template}-pdf.html' pdf = redirect(url_for('app.main.generate_pdf')) body = render_template('mail/resume-mail.txt', user=user, website=url_for('app.main.index')) html = render_template('mail/resume-mail.html', user=user, website=url_for('app.main.index')) pdf = pdfkit.from_string(pdf, False, configuration=app.config['PDF_TO_HTML']) response = make_response(pdf) response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] = 'inline; filename.pdf' sent = send_email(sender=app.config['MAIL_USERNAME'], subject='Your Resume | Alium-Resume', recipient=user.email, body=body, attachment=response) return sent if sent else None
def send_report( # pylint: disable=too-many-locals list_stats, agg_stats, list_id, list_name, user_email_or_emails): """Generates charts using Plotly and emails them to the user. Args: list_stats: a dictionary containing analysis results for a list. agg_stats: a dictionary containing aggregate analysis results from the database. list_id: the list's unique MailChimp id. list_name: the list's name. user_email_or_emails: a list of emails to send the report to. """ # Generate epoch time to append to filenames # This is a hacky workaround for webmail image caching epoch_time = str(int(time.time())) # Figure out whether there's two sets of stats per graph contains_prev_month = len(list_stats['subscribers']) == 2 if contains_prev_month: # Calculate the diffs (for month-over-month change labels) diff_vals = generate_diffs(list_stats, agg_stats) # Get the current month and previous month in words (for labels) cur_month = datetime.now().month last_month = cur_month - 1 or 12 cur_month_formatted = calendar.month_abbr[cur_month] last_month_formatted = calendar.month_abbr[last_month] bar_titles = [ 'Your List<br>as of ' + last_month_formatted, 'Your List<br>as of ' + cur_month_formatted, 'Average<br>as of ' + last_month_formatted, 'Average<br>as of ' + cur_month_formatted ] stacked_bar_titles = [ 'Average <br>as of ' + last_month_formatted + ' ', 'Average <br>as of ' + cur_month_formatted + ' ', 'Your List <br>as of ' + last_month_formatted + ' ', 'Your List <br>as of ' + cur_month_formatted + ' ' ] else: diff_vals = None bar_titles = ['Your List', 'Average'] stacked_bar_titles = ['Average ', 'Your List '] draw_bar(bar_titles, [*list_stats['subscribers'], *agg_stats['subscribers']], diff_vals['subscribers'] if diff_vals else None, 'Chart A: List Size', list_id + '_size_' + epoch_time) draw_bar(bar_titles, [*list_stats['open_rate'], *agg_stats['open_rate']], diff_vals['open_rate'] if diff_vals else None, 'Chart C: List Open Rate', list_id + '_open_rate_' + epoch_time, percentage_values=True) draw_stacked_horizontal_bar( stacked_bar_titles, [('Subscribed %', [*agg_stats['subscribed_pct'], *list_stats['subscribed_pct']]), ('Unsubscribed %', [*agg_stats['unsubscribed_pct'], *list_stats['unsubscribed_pct']]), ('Cleaned %', [*agg_stats['cleaned_pct'], *list_stats['cleaned_pct'] ]), ('Pending %', [*agg_stats['pending_pct'], *list_stats['pending_pct']]) ], diff_vals['subscribed_pct'][::-1] if diff_vals else None, 'Chart B: List Composition', list_id + '_breakdown_' + epoch_time) histogram_legend_uri = ('https://s3-us-west-2.amazonaws.com/email-' 'benchmarking-imgs/open_rate_histogram_legend.png') draw_histogram( { 'title': 'Open Rate by Decile', 'vals': np.linspace(.05, .95, num=10) }, { 'title': 'Subscribers', 'vals': list_stats['hist_bin_counts'][0] }, 'Chart D: Distribution of Subscribers by Open Rate', histogram_legend_uri, list_id + '_open_rate_histogram_' + epoch_time) high_open_rt_vals = [ *list_stats['high_open_rt_pct'], *agg_stats['high_open_rt_pct'] ] draw_donuts( ['Open Rate >80%', 'Open Rate <=80%'], [(title, [high_open_rt_vals[title_num], 1 - high_open_rt_vals[title_num]]) for title_num, title in enumerate(bar_titles)], diff_vals['high_open_rt_pct'] if diff_vals else None, 'Chart E: Percentage of Subscribers with User Unique Open Rate >80%', list_id + '_high_open_rt_pct_' + epoch_time) cur_yr_inactive_vals = [ *list_stats['cur_yr_inactive_pct'], *agg_stats['cur_yr_inactive_pct'] ] draw_donuts(['Inactive in Past 365 Days', 'Active in Past 365 Days'], [(title, [ cur_yr_inactive_vals[title_num], 1 - cur_yr_inactive_vals[title_num] ]) for title_num, title in enumerate(bar_titles)], diff_vals['cur_yr_inactive_pct'] if diff_vals else None, 'Chart F: Percentage of Subscribers who did not Open ' 'in last 365 Days', list_id + '_cur_yr_inactive_pct_' + epoch_time) # Send charts as an email report send_email('Your Email Benchmarking Report is Ready!', user_email_or_emails, 'report-email.html', { 'title': 'We\'ve analyzed the {} list!'.format(list_name), 'list_id': list_id, 'epoch_time': epoch_time }, configuration_set_name=(os.environ.get('SES_CONFIGURATION_SET') or None))
def import_analyze_store_list(list_data, org_id, user_email=None): """Imports a MailChimp list, performs calculations, and stores results. Args: list_data: see init_list_analysis(). org_id: the unique id of the organization associated with the list. user_email: the user's email address. Only passed when the user requested the analysis (as opposed to Celery Beat). Returns: A dictionary containing analysis results for the list. Throws: MailChimpImportError: an error resulting from a MailChimp API problem. """ # Create a new list instance and import member data/activity mailing_list = MailChimpList(list_data['list_id'], list_data['total_count'], list_data['key'], list_data['data_center']) try: # Import basic list data do_async_import(mailing_list.import_list_members()) # Import the subscriber activity as well, and merge do_async_import(mailing_list.import_sub_activity()) except MailChimpImportError as e: # pylint: disable=invalid-name if user_email: send_email( 'We Couldn\'t Process Your Email Benchmarking Report', [user_email, os.environ.get('ADMIN_EMAIL') or None], 'error-email.html', { 'title': 'Looks like something went wrong ☹', 'error_details': e.error_details }) raise # Remove nested jsons from the dataframe mailing_list.flatten() # Do the data science shit mailing_list.calc_list_breakdown() mailing_list.calc_open_rate(list_data['open_rate']) mailing_list.calc_frequency(list_data['creation_timestamp'], list_data['campaign_count']) mailing_list.calc_histogram() mailing_list.calc_high_open_rate_pct() mailing_list.calc_cur_yr_stats() # Create a set of stats list_stats = ListStats( frequency=mailing_list.frequency, subscribers=mailing_list.subscribers, open_rate=mailing_list.open_rate, hist_bin_counts=json.dumps(mailing_list.hist_bin_counts), subscribed_pct=mailing_list.subscribed_pct, unsubscribed_pct=mailing_list.unsubscribed_pct, cleaned_pct=mailing_list.cleaned_pct, pending_pct=mailing_list.pending_pct, high_open_rt_pct=mailing_list.high_open_rt_pct, cur_yr_inactive_pct=mailing_list.cur_yr_inactive_pct, list_id=list_data['list_id']) # If the user gave their permission, store the stats in the database if list_data['monthly_updates'] or list_data['store_aggregates']: # Create a list object to go with the set of stats email_list = EmailList( list_id=list_data['list_id'], creation_timestamp=list_data['creation_timestamp'], list_name=list_data['list_name'], api_key=list_data['key'], data_center=list_data['data_center'], store_aggregates=list_data['store_aggregates'], monthly_updates=list_data['monthly_updates'], org_id=org_id) email_list = db.session.merge(email_list) db.session.add(list_stats) try: db.session.commit() except: db.session.rollback() raise return list_stats
def test_email(): with app.app_context(): send_email('*****@*****.**','Test','auth/email/demo')
def resend_confirmation(): token = current_user.generate_confirmation_token() send_email(current_user.email, 'Confirm Your Account', 'auth/confirm', user=current_user, token=token) flash('A new confirmation email has been sent to you by email.') return redirect(url_for('main.index'))