示例#1
0
def reset_password():
    form = EmailForm()
    if not form.validate_on_submit():
        return render_template('reset.html', form=form)

    user = User.query.filter_by(email=form.email.data).first()
    if user is not None:
        recover_url = url_for('reset_with_token',
                              token=serializer.dumps(user.email,
                                                     salt='recover-key'),
                              _external=True)

        msg = Message(
            html=render_template('email_password_reset.html', url=recover_url),
            subject='Password reset requested',
            mail_from='*****@*****.**',
            mail_to=user.email,
        )

        req = msg.send()

        if req.status_code not in [
                250,
        ]:
            pass  # TODO message is not sent, deal with this

    flash(
        'If that email is attached to an account, a password reset link has been sent to it'
    )
    return redirect(url_for('front_page'))
示例#2
0
def send_recovery_email(email):
    context = {
        'client': client,
        'recover_url': os.getenv('RECOVER_URL'),
        'token': Serializer.generate_token(email)
    }
    plain = render_template('emails/account_recovery.txt', **context)
    msg = Message(subject='Recover Your Account', mail_from=mailer, text=plain)
    return msg.send(to=email)
示例#3
0
def test_flask_send_dummy():
    # Send via dummy backend
    app = Flask(__name__)
    app.config.update({'EMAIL_BACKEND': 'flask_emails.backends.DummyBackend'})
    from flask_emails import Message
    # Message.init_app(app)
    ctx = app.test_request_context()
    ctx.push()
    m = Message(**SAMPLE_MESSAGE)
    m.send(smtp={'timeout': 1})
示例#4
0
def send_confirmation_email(email, name):
    context = {
        'client': client,
        'confirm_url': os.getenv('CONFIRMATION_URL'),
        'token': Serializer.generate_token(email)
    }
    plain = render_template('emails/user_confirmation.txt', **context)
    msg = Message(subject='Welcome, {}'.format(name),
                  mail_from=mailer,
                  text=plain)
    return msg.send(to=email)
示例#5
0
def execute(id):
    payment = Payment.find(request.args.get('paymentId'))

    order = Order.query.get(id)

    if not order or order.buyer != current_user:
        flash('Your order was not found, maybe it was already cancelled?')
        return redirect(url_for('shop'))

    if order.paid:
        flash('Your order was already paid, not charging you twice!')
        return redirect(url_for('shop'))

    if order.payment_id != payment.id:
        flash('This payment does not seem to match your order!')
        return redirect(url_for('shop'))

    if not payment.execute(dict(payer_id=request.args.get('PayerID'))):
        flash('An error occured while processing your order: {}'.format(
            payment.error))
        return redirect(url_for('shop'))

    order.paid = True
    order.item.quantity -= 1
    db.session.commit()

    message = Message(
        html=render_template(
            'order_receipt.html',
            order=order,
            item=order.item,
            user=order.buyer,
        ),
        subject='Receipt for your purchase - {}'.format(
            app.config['SITE_NAME']),
        mail_from=(
            app.config['SITE_NAME'],
            'noreply@%s' % app.config['SUPPORT_EMAIL'].split('@')[1],
        ),
    )
    user = order.buyer
    response = message.send(to=(
        '{} {}'.format(user.first_name, user.last_name),
        user.email,
    ))

    flash('Your order was processed successfully{}. Thank you!'.format(
        '' if response.status_code == 250 else (
            ', but your purchase receipt could not be sent. '
            'Contact us at {} in order to get your receipt.'
        ).format(app.config['SUPPORT_EMAIL'])))
    return redirect(url_for('shop'))
示例#6
0
def test_flask_send_real():
    # Send via real backend
    app = Flask(__name__)
    app.config.update({
        'EMAIL_HOST': 'mx.yandex.ru',
        'EMAIL_FAIL_SILENTLY': False
    })
    from flask_emails import Message
    ctx = app.test_request_context()
    ctx.push()
    # Message.init_app(app)
    m = Message(**SAMPLE_MESSAGE)
    r = m.send()
    assert r.status_code == 250
示例#7
0
def test_flask_message():
    app = Flask(__name__)
    app.config.update({'EMAIL_DEFAULT_FROM': 'John Brawn <*****@*****.**>'})
    ctx = app.test_request_context()
    ctx.push()

    from flask_emails import Message
    m = Message(html='...')
    assert m.mail_from == ('John Brawn', '*****@*****.**')
示例#8
0
def check():
    last = getLastPrice()
    email_pass = request.args.get('pass')
    if email_pass:
        config_copy = mail_config
        config_copy['EMAIL_HOST_PASSWORD'] = email_pass
        mail = EmailsConfig(config=config_copy)

        message = Message(config=mail,
                          html=f'<html><p>{last}</p></html>',
                          subject=f"Daily Update - ${last}",
                          mail_from=("Cron Job", "*****@*****.**"))

        try:
            r = message.send(to=("Nick Jordan", "*****@*****.**"))
        except Exception as e:
            print("Invalid mail settings")
    return jsonify({'last': last})
示例#9
0
def register():
    form = RegisterForm()

    if form.validate_on_submit():
        data = form.data
        for key in dict(data):
            if key not in dir(User):
                del data[key]

        data['activation_key'] = uuid.uuid4().hex

        user = User(**data)

        db.session.add(user)
        db.session.commit()

        message = Message(
            html=render_template('activation_email.html', user=user),
            subject='Activate your account - {}'.format(
                app.config['SITE_NAME']),
            mail_from=(
                app.config['SITE_NAME'],
                'noreply@%s' % app.config['SUPPORT_EMAIL'].split('@')[1],
            ),
        )
        response = message.send(to=(
            '{} {}'.format(user.first_name, user.last_name),
            user.email,
        ))

        flash('Your account was successfully created{}.'.format(
            '' if response.status_code == 250 else (
                ', but your activation e-mail could not be sent. '
                'Contact us at {} in order to activate your account.'
            ).format(app.config['SUPPORT_EMAIL'])))
        return redirect(url_for('index'))

    return render_template('register.html', form=form)
示例#10
0
def register():
    ''' register a new user '''
    if current_user.is_authenticated:
        return redirect(url_for('front_page'))
    form = RegistrationForm()
    if not form.validate_on_submit():
        return render_template('register.html', title='Register', form=form)

    this_user = User()
    form.populate_obj(this_user)
    this_user.set_password(form.password.data)
    this_user.set_pin(form.pin.data)
    this_user.create_token()
    db.session.add(this_user)
    db.session.commit()
    flash(
        'Congratulations, you are now a registered user, you are now logged in!'
    )
    login_user(this_user)

    confirm_url = url_for('confirm_email',
                          token=serializer.dumps(this_user.email,
                                                 salt='email-confirm-key'),
                          _external=True)

    req = Message(
        html=render_template('email_activate.html', url=confirm_url),
        subject='Confirm your email for the ZAPS Mahjong Scorer',
        mail_from='*****@*****.**',
        mail_to=this_user.email,
    ).send()

    if req.status_code not in [
            250,
    ]:
        pass  # TODO message is not sent, deal with this

    return redirect(url_for('view_profile', user_id=this_user.user_id))
示例#11
0
    def send_email(self, account_registration_from_user=None):
        """Email password reset link to the user, possibly in wording of initial registration."""
        password_reset_url = url_for('public.reset_password', email=self.user.email,
                                     code=self.code, _external=True)
        service_name = current_app.config['SERVER_NAME'] or current_app.config['APP_NAME']
        if account_registration_from_user:
            subject = _('Account activation and password reset for %(username)s '
                        'at %(server_name)s', username=self.user.email, server_name=service_name)
            body_text = _(
                'Hello %(full_name)s,'
                '\n\n'
                'You have been granted a user account at %(server_name)s by %(current_user)s. '
                'Use the secret link below to set a personal account password, and \
thereby activating your account:'
                '\n\n'
                '%(password_reset_url)s'
                '\n\n\n\n'
                'P.S. If you received this mail for no obvious reason, please inform us about it \
at [email protected]!'
                '\n\n',
                full_name=self.user.full_name, server_name=service_name,
                current_user=account_registration_from_user.email,
                password_reset_url=password_reset_url
            )
            body_html = _(
                '<p>'
                'Hello %(full_name)s,'
                '<br/><br/>'
                'You have been granted a user account at %(server_name)s by %(current_user)s. '
                'Use the secret link below to set a personal password, and \
thereby activating your account:'
                '<br/><br/>'
                '<a href="%(password_reset_url)s">%(password_reset_url)s</a>'
                '<br/><br/>'
                '</p>'
                '<p><small>'
                'P.S. If you received this mail for no obvious reason, please inform us about it '
                'at <a href="mailto:[email protected]">[email protected]</a>!'
                '</small></p>',
                full_name=self.user.full_name, server_name=service_name,
                current_user='******'.format(
                    account_registration_from_user.email),
                password_reset_url=password_reset_url
            )

        else:
            subject = _('Password reset for %(username)s at %(server_name)s',
                        username=self.user.email, server_name=service_name)
            body_text = _(
                'Hello %(full_name)s,'
                '\n\n'
                'Here is the secret link for resetting your personal account password:'******'\n\n'
                '%(password_reset_url)s'
                '\n\n\n\n'
                'P.S. If you received this mail for no obvious reason, please inform us about it \
at [email protected]!'
                '\n\n',
                full_name=self.user.full_name, password_reset_url=password_reset_url
            )
            body_html = _(
                '<p>'
                'Hello %(full_name)s,'
                '<br/><br/>'
                'Here is the secret link for resetting your personal account password:'******'<br/><br/>'
                '<a href="%(password_reset_url)s">%(password_reset_url)s</a>'
                '<br/><br/>'
                '</p>'
                '<p><small>'
                'P.S. If you received this mail for no obvious reason, please inform us about it '
                'at <a href="mailto:[email protected]">[email protected]</a>!'
                '</small></p>',
                full_name=self.user.full_name, password_reset_url=password_reset_url
            )

        result = Message(
            subject=subject,
            mail_to=(self.user.full_name, self.user.email),
            text=body_text,
            html=body_html
        ).send()

        if not hasattr(result, 'status_code'):
            result = result[0]

        assert result.status_code == 250
示例#12
0
def send_startup_email():
    context = {'time': datetime.utcnow()}
    plain = render_template('emails/startup.txt', **context)
    msg = Message(subject='Auth Server Up', mail_from=mailer, text=plain)
    return msg.send(to=os.getenv('DEVELOPER_EMAIL'))
示例#13
0
 def welcome_mail(addr):
     message = Message(html=render_template('email/welcome.html', header="Привет!", text="Добро пожаловать на КУДАБЫ.РУ"),
               subject="Добро пожаловать!",
               mail_from=("КУДАБЫ", "*****@*****.**"))
     r = message.send(to=(addr))
示例#14
0
 def verify_mail(**kwargs):
     message = Message(html=render_template('email/verify_email.html', hash= kwargs['hash'], uid= kwargs['uid']),
             subject="Подтверждение адреса электронной почты",
             mail_from=("КУДАБЫ", "*****@*****.**"))
     r = message.send(to=(kwargs['email']))