def handle(self, **kwargs):
        logger.info('{} CanceledStateHandler'.format(SERVICE_TYPE))

        booking_id = kwargs['booking_id']
        status = kwargs['status']
        req_user_id = kwargs['req_user_id']

        validate_status(status)
        booking_info = Booking.objects.get(short_id=booking_id)

        # only renters can cancel their booking
        # todo change req_user_id to renter_id
        if booking_info.renter != req_user_id:
            raise Exception("Only renters can cancel their own booking")

        if status in booking_info.phases:
            raise Exception('Status {} already set'.format(status))

        # todo - reuse this for owner
        # if booking_info.current_phase != \
        #         AbstractStateHandler.BOOKING_PHASE_ACCEPTED:
        #     raise Exception(
        #         'Need to set status {} before {}'.
        #         format(
        #             AbstractStateHandler.BOOKING_PHASE_ACCEPTED,
        #             status
        #         )
        #     )

        booking_info.current_phase = status
        booking_info.phases[status] = {"date_time": datetime.now().timestamp()}
        booking_info.save()

        vehicle = Vehicle.objects.get(id=booking_info.vehicle['id'])
        if booking_info.reserved_date_time in vehicle.reserved_list:
            vehicle.reserved_list.remove(booking_info.reserved_date_time)
            vehicle.save()

        renter = User.objects(id=booking_info.renter).first()
        owner = User.objects(id=booking_info.owner).first()

        # send email to renter
        send_email(
            to_email=renter.email,
            # todo localize
            subject="Bạn đã huỷ chuyến {}".format(booking_info.short_id),
            content="Bạn đã huỷ chuyến {}".format(booking_info.short_id))
        # send email to owner
        send_email(to_email=owner.email,
                   subject="Khách thuê {} đã huỷ chuyến {}".format(
                       renter.name, booking_info.short_id),
                   content="Khách thuê {} đã huỷ chuyến {}".format(
                       renter.name, booking_info.short_id))

        return booking_info
Exemple #2
0
def send_password_reset_email(user):
    token = user.get_reset_password_token()
    send_email('[Microblog] Password Recovery',
               sender=current_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))
Exemple #3
0
def re_send_confirm():
    user = current_user._get_current_object()
    token = user.generate_confirmation_token()
    send_email('*****@*****.**',
               user.email,
               '认证你的账号',
               template='auth/email/confirm',
               user=user,
               token=token)
    flash('一封新的验证邮件发送成功!', 'success')
    return redirect(url_for('main.index'))
Exemple #4
0
def contacts():
    form = ContactForm(request.form)

    if form.validate_on_submit():
        send_email(str(escape(form.name.data.strip())),
                   str(escape(form.email.data.strip())),
                   str(escape(form.subject.data.strip())),
                   str(escape(form.message.data.strip())))

        return redirect(url_for('app.email_success'))

    return render_template('app/contacts.html', form=form)
Exemple #5
0
def register():
    form = RegistrationForm()
    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, "Confirm Your Account", "auth/email/confirm", user=user, token=token)
        flash("A confirmation email has been sent to you.")
        login_user(user, form.password.data)
        return redirect(url_for("main.index"))
    return render_template("auth/register.html", form=form)
def signup():
    form = Signup()
    if form.validate_on_submit():
        user = User(name=form.name.data, email=form.email.data, password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_email(user.email, "Confirmed Your store Account", "auth/email/confirm", user=user, token=token)
        flash("Check your email for the confirmation Email from us!")
        login_user(user, form.password.data)
        return redirect(url_for("main.index"))
    return render_template("auth/signup.html", form=form)
    def handle(self, **kwargs):
        logger.info('{} DoneStateHandler'.format(SERVICE_TYPE))

        booking_id = kwargs['booking_id']
        status = kwargs['status']
        validate_status(status)
        booking_info = Booking.objects.get(short_id=booking_id)

        if datetime.now().timestamp() < \
                booking_info.reserved_date_time.get('to') - \
                (config.HOURS_TO_GIVE_VEHICLE_BACK_TO_OWNER * 3600):
            raise Exception(
                "Done status can only set after the last date of booking")

        if status in booking_info.phases:
            raise Exception('Status {} already set'.format(status))

        if booking_info.current_phase != \
                AbstractStateHandler.BOOKING_PHASE_ACCEPTED:
            raise Exception('Need to set status {} before {}'.format(
                AbstractStateHandler.BOOKING_PHASE_ACCEPTED, status))

        booking_info.current_phase = status
        booking_info.phases[status] = {"date_time": datetime.now().timestamp()}
        booking_info.save()

        vehicle = Vehicle.objects.get(id=booking_info.vehicle['id'])
        if booking_info.reserved_date_time in vehicle.reserved_list:
            vehicle.reserved_list.remove(booking_info.reserved_date_time)
            vehicle.save()

        renter = User.objects(id=booking_info.renter).first()
        owner = User.objects(id=booking_info.owner).first()

        # send email to renter
        send_email(
            to_email=renter.email,
            # todo localize
            subject="Bạn đã hoàn thành chuyến {}".format(
                booking_info.short_id),
            content="Bạn đã hoàn thành chuyến {}".format(
                booking_info.short_id))
        # send email to owner
        send_email(
            to_email=owner.email,
            # todo localize
            subject="Chuyến {} đã hoàn thành!".format(booking_info.short_id),
            content="Chuyến {} đã hoàn thành!".format(booking_info.short_id))

        return booking_info
Exemple #8
0
def initiate_password_reset(email):
    """Send the user an email to start the password reset process."""
    user = User.query.filter_by(email=email).first()
    if user is not None:
        token = user.generate_password_reset_token()
        send_email(
            user.email,
            "Reset Your Password",
            "auth/email/reset_password",
            user=user,
            token=token,
        )
    else:
        raise InvalidEmail("We couldn't find an account with that email address")
Exemple #9
0
def register():
    try:
        username = request.json["username"]
        email = request.json["email"]
        password = request.json["password"]
    except KeyError:
        return error_missing_json_key("username", "email", "password")
    new_user = User(email=email, username=username, email_verified=False)
    new_user.set_password(password)
    db.session.add(new_user)
    try:
        db.session.commit()
    except DatabaseError as error:
        return (
            jsonify({
                "msg":
                "Couldn't create a new user. Failed with error: '{}'".format(
                    error)
            }),
            500,
        )
    db.session.refresh(new_user)
    verify_email_url = url_for(
        "auth.verify_email",
        token=jwt.encode(
            {
                "token_type":
                "verify_email",
                "user_id":
                new_user.id,
                "exp": (datetime.datetime.utcnow() +
                        datetime.timedelta(seconds=3600)).timestamp(),
            },
            current_app.secret_key,
        ),
        _external=not current_app.testing,
    )
    html_content = render_template("email_verify.jinja",
                                   verify_email_url=verify_email_url)
    send_email(
        new_user.email,
        "Verify your email.",
        html_content,
        "Follow this link to verify your email: {}".format(verify_email_url),
    )
    return jsonify({
        "msg": "Created a new user.",
        "data": new_user.id,
        "status": "success"
    })
Exemple #10
0
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, "Confirm your email address", "auth/email/change_email", user=current_user, token=token
            )
            flash("An email with instructions to confirm your new email address " + "has been sent to you.")
            return redirect(url_for("main.index"))
        else:
            flash("Invalid email or password")
    return render_template("auth/change_email.html", form=form)
Exemple #11
0
def send_verify_email(user: User, verify_key: str):
    context = get_substitutions_templates()
    context["user"] = user
    context["verify_key"] = verify_key
    context["event"] = get_next_or_past_event()
    template = get_notification_template(
        method="email", type="signup", task="verify", format="html"
    )
    subject = get_notification_template(
        method="email", type="signup", task="verify", format="subject"
    )
    body = render_to_string(template, context)

    send_email(subject=subject, body=body, to=user.email, tags=[MailTag.VERIFY])
    def handle(self, **kwargs):
        logger.info('{} RejectedStateHandler'.format(SERVICE_TYPE))
        booking_id = kwargs['booking_id']
        status = kwargs['status']
        req_user_id = kwargs['req_user_id']

        validate_status(status)

        booking_info = Booking.objects.get(short_id=booking_id)
        # check ìf current user allow to reject the booking
        vehicle = Vehicle.objects(id=booking_info.vehicle['id']).first()

        if vehicle.owner != req_user_id:
            raise Exception(
                "Only vehicle owner can reject the booking request")

        if status in booking_info.phases:
            raise Exception('Status {} already set'.format(status))

        if booking_info.current_phase == \
                AbstractStateHandler.BOOKING_PHASE_ACCEPTED:
            raise Exception("Can't reject after accepting the booking")

        booking_info.current_phase = status
        booking_info.phases[status] = {"date_time": datetime.now().timestamp()}
        booking_info.save()

        renter = User.objects(id=booking_info.renter).first()
        owner = User.objects(id=booking_info.owner).first()

        # send email to renter
        send_email(
            to_email=renter.email,
            # todo localize
            subject="Yêu cầu thuê xe {} đã bị từ chối".format(
                booking_info.short_id),
            content="Yêu cầu thuê xe {} đã bị từ chối bởi {}".format(
                booking_info.short_id, owner.name))
        # send email to owner
        send_email(
            to_email=owner.email,
            # todo localize
            subject="Bạn đã từ chối yêu cầu thuê {}".format(
                booking_info.short_id),
            content="Bạn đã từ chối yêu cầu thuê {}".format(
                booking_info.short_id),
        )

        return booking_info
Exemple #13
0
def send_slack_email(user_id: UUID):
    context = get_substitutions_templates()
    user = User.objects.get(id=user_id)
    context["user"] = user
    template = get_notification_template(method="email",
                                         app="user",
                                         task="slack",
                                         format="html")
    subject = get_notification_template(method="email",
                                        app="user",
                                        task="slack",
                                        format="subject")
    body = render_to_string(template, context)

    send_email(subject=subject, body=body, to=user.email, tags=[MailTag.SLACK])
Exemple #14
0
def user_info_view():
    uid = request.headers.get('identify')
    user = User.query.get_or_404(uid)
    if request.method == 'PUT':
        form = UserValidate().validate_api()
        if form.email.data and form.email.data != user.email:
            user.email_is_validate = False
            user.email = form.email.data
            send_email(to=form.email,
                       subject='账户邮件修改确认',
                       content=url_for('admin.auth_email_view',
                                       token=user.generate_token()))
        user.update(form.data)
        return generate_res()
    return generate_res(data=UserInfoView(user))
def change_email_request():
    """ user request to change their passwords """
    form = ChangeEmail()
    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, "Confirm your email Address", "auth/email/change_email", user=current_user, token=token
            )
            flash("We have send an email with instruction how to reset your password")
            return redirected(url_for("main.index"))
        else:
            flash("Password is Invalid")
    return render_template("auth/change_email.html", form=form)
Exemple #16
0
    def form_valid(self, form):
        site = Site.objects.get_current().name
        send_email(
            '[{0}] Registro de monitoreo satelital'.format(site),
            [form.instance.email],
            'cms/satellite_monitoring_email.html',
            {'contact': form.instance},
            from_addr=config.EMAIL_SATELITAL,
            bcc_mails=self.bcc_list,
        )
        messages.info(
            self.request,
            'Gracias por su interés, pronto le contactaremos.',
        )

        return super(SatelliteMonitoringContactView, self).form_valid(form)
Exemple #17
0
def send_password_reset_email(user: Any) -> None:
    project_name = "miniblog"
    subject = f"{project_name} - Password recovery for user {user.username}"
    token = user.get_reset_password_token()
    link = url_for('auth.reset_password', token=token, _external=True)
    logo = url_for('static', filename='images/MINIBlog.png', _external=True)
    template_str = render_template("email/build/reset_password.html",
                                   user=user,
                                   project_name=project_name,
                                   logo=logo,
                                   link=link)
    send_email(
        email_to=user.email,
        subject_template=subject,
        html_template=template_str,
    )
def change_email_request():
    ''' user request to change their passwords '''
    form = ChangeEmail()
    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,'Confirm your email Address', 'auth/email/change_email',
                        user= current_user, token=token)
            flash('We have send an email with instruction how to reset your password')
            return redirect(url_for('main.index'))
        else:
            flash('Password is Invalid')
    return render_template('auth/change_email.html', form=form)
Exemple #19
0
def register():
    user_data = request.get_json()

    # user exists
    if UserModel.count(user_data["email"]):
        return jsonify("Email already registered"), 400

    # incomplete user data
    if not all([
        user_data.get("first_name"), 
        user_data.get("last_name"), 
        user_data.get("password")
        ]):
        return jsonify("You must provide an email, first_name, last_name, and password"), 400
    
    # good to go, let's get them registered
    user_instance = UserModel(
        user_data["email"], 
        created_at=datetime.datetime.utcnow(),
        first_name=user_data["first_name"], 
        last_name=user_data["last_name"],
    )

    # hash the password
    user_instance.setPasswordHash(user_data["password"])

    # compose and send activation email
    email_template = """
        <h1>Rentalated</h1>
        <a href="{url}/test/activate/{encoded_id}">
            <p>Click this link to activate your account!</p>
        </a>
    """.format(url=config.WEBSITE_URL, encoded_id=encode_activation_token(user_data["email"]))

    send_email(
        user_data["email"], 
        "The time has come for you to activate your Rentalated account.",
        email_template
    )

    # save the user with .activated=False
    user_instance.save()

    return jsonify({
        "msg": "user saved && activation email sent",
        "saved_user": user_instance.serialize()
    })
def signup():
    form = Signup()

    if form.validate_on_submit():

        user = User(name =form.name.data,
                    email=form.email.data,
                    password= form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_email(
                    user.email, 'Confirmed Your Inventory Account', 'auth/email/confirm',
                    user=user, token=token)
        flash('Check your email for the confirmation Email from us!')
        login_user(user,form.password.data)
        return redirect(url_for('main.index'))
    return render_template('auth/signup.html', form=form)
Exemple #21
0
    def post(self, request):
        ids = self.request.POST.get('ids')
        ids = ids.split(',')
        print(ids)
        title = self.request.POST.get('title')
        text = self.request.POST.get('text')
        if 'sms' in self.request.POST.get('action'):
            for id in ids:
                d = Doctor.objects.get(id=id)
                if d.phone:
                    send_sms(d.phone, title + '\n' + text)
        if 'email' in self.request.POST.get('action'):
            for id in ids:
                d = Doctor.objects.get(id=id)
                if d.email:
                    send_email(title, text, [d.email,])

        return Response(status=201)
Exemple #22
0
def signup():
    form = Signup()
    if form.validate_on_submit():
        user = User(name=form.name.data,
                    email=form.email.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_email(user.email,
                   'Confirmed Your store Account',
                   'auth/email/confirm',
                   user=user,
                   token=token)
        flash('Check your email for the confirmation Email from us!')
        login_user(user, form.password.data)
        return redirect(url_for('main.index'))
    return render_template('auth/signup.html', form=form)
Exemple #23
0
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,
                       'Confirm your email address',
                       'auth/email/change_email',
                       user=current_user,
                       token=token)
            flash(
                "An email with instructions to confirm your new email address "
                + "has been sent to you.")
            return redirect(url_for('main.index'))
        else:
            flash("Invalid email or password")
    return render_template('auth/change_email.html', form=form)
Exemple #24
0
def register():
    form = RegistrationForm()
    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,
                   'Confirm Your Account',
                   'auth/email/confirm',
                   user=user,
                   token=token)
        flash("A confirmation email has been sent to you.")
        login_user(user, form.password.data)
        return redirect(url_for('main.index'))
    return render_template('auth/register.html', form=form)
Exemple #25
0
def check_website_change():
    for ski_area, value in const.SKI_AREAS.items():
        for key, url in value.items():
            old_content = db.get_content(ski_area)
            new_content = website_parser.get_plain_text(url)

            # compare old content to new content and update the db with the new content
            if old_content:
                if website_parser.compare_plain_texts(old_content,
                                                      new_content) < 90:
                    try:
                        utils.send_email(
                            "{} has updated their website".format(ski_area))
                    except:
                        utils.print_error_message("Error sending email")
            updated = db.set_content(new_content, ski_area)

            if not updated:
                utils.print_error_message("Error updating website change db")
def password_reset_request():
    ''' users who request for a password change '''
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetRequest()     

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_confirmation_token()
            send_email(
                        user.email, 'Reset your password', 'auth/email/reset_password',
                        user=user, token=token, next=request.args.get('next'))
            flash('we have send an email with instruction how to reset your password')
            return redirect(url_for('auth.login'))
        else:
            flash('No account found with that email address')
            return redirect(url_for('auth.change_password'))
    return render_template('auth/reset_password.html', form=form)
Exemple #27
0
def send_subscriber_new(subscriber: Subscriber, event: Event = None):
    context = get_substitutions_templates()
    context["subscriber"] = subscriber
    if event:
        context["event"] = event
    template = get_notification_template(method="email",
                                         type="subscribe",
                                         task="new",
                                         format="html")
    subject = get_notification_template(method="email",
                                        type="subscribe",
                                        task="new",
                                        format="subject")
    body = render_to_string(template, context)

    send_email(subject=subject,
               body=body,
               to=subscriber.email,
               tags=[MailTag.SUBSCRIBE])
def send_mail_to_pools(pools, subject, template, delay):
    print("Loading data...\n")

    recipients = get_mail_addresses_for_pools(pools)

    print("Template\n========\n")
    print(template)

    print("\nSending this as an email to %d recipients of pool(s) %s: y/N" % \
            (len(recipients), pools))
    raw = raw_input().lower()
    if raw and strtobool(raw):
        size = len(recipients)
        for i,email in enumerate(recipients):
            send_email(email, subject, template, {}, no_template = True)
            print("%f [%d/%d] %s" % (i/size, i, size, email))
            sleep(float(delay))
    else:
        print("Aborted")
Exemple #29
0
async def detected_new_adapter(
    new_adapter: schemas.NewAdapter, request: requests.Request
):
    client_host = request.client.host

    project_name = settings.PROJECT_NAME
    subject = f"{project_name} - New Adapter"
    with open(Path(settings.EMAIL_TEMPLATES_DIR) / "new_adapter.html") as f:
        template_str = f.read()
    email_to = settings.FIRST_SUPERUSER
    send_email(
        email_to=email_to,
        subject_template=subject,
        html_template=template_str,
        environment={
            "project_name": project_name,
            "new_adapter": new_adapter.new_adapter,
            "client_host": client_host,
        },
    )
Exemple #30
0
def change_email_request():
    ''' user request to change their passwords '''
    form = ChangeEmail()
    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,
                       'Confirm your email Address',
                       'auth/email/change_email',
                       user=current_user,
                       token=token)
            flash(
                'We have send an email with instruction how to reset your password'
            )
            return redirected(url_for('main.index'))
        else:
            flash('Password is Invalid')
    return render_template('auth/change_email.html', form=form)
Exemple #31
0
def sign_up():
    if current_user.is_authenticated:
        content = [f"Session Active", f"You are already logged in."]
        flash(content, category="info")
        return redirect(url_for("BP_home.home"))
    form = RegistrationForm()
    if form.validate_on_submit():
        user_name = form.username.data.title()
        user_password = encryptor.generate_password_hash(form.password.data).decode(
            "utf-8"
        )
        new_user = User(
            username=user_name,
            email=form.email.data,
            password=user_password,
            contact=form.contact.data,
        )
        db.session.add(new_user)
        db.session.commit()
        register_token = new_user.generate_token()
        utils.send_email(
            "Activate Account: KreatiVision",
            "*****@*****.**",
            [new_user.email],
            render_template(
                "registration-mail.txt", token=register_token, name=new_user.username
            ),
            render_template(
                "registration-mail.html", token=register_token, name=new_user.username
            ),
        )
        return render_template(
            "email-sent.html",
            title="Activate Account",
            mail=utils.redact_email(new_user.email),
            case="register",
        )
    return render_template(
        "register.html", title="Create Account", page="Register", form=form
    )
Exemple #32
0
def test_send_email(mock_post, app):
    # Given: attrs for an function.
    calls = [
        mock.call('https://api.mailgun.net/v3//messages',
                  auth=('api', ''),
                  data={
                      'from': 'test <*****@*****.**>',
                      'to': '',
                      'subject': 'Test',
                      'text': 'Test message.'
                  })
    ]

    # When: the attrs passed to the function.
    with app.app_context():
        # Then: requests.post should be called with them and send a message
        # to us from behalf an e-mail address that specified
        send_email(name='test',
                   email='*****@*****.**',
                   subject='Test',
                   message='Test message.')
        assert mock_post.mock_calls == calls
Exemple #33
0
def password_reset_request():
    if not current_user.is_anonymous:
        return redirect(url_for("main.index"))
    form = PasswordResetRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_confirmation_token()
            send_email(
                user.email,
                "Reset Your Password",
                "auth/email/reset_password",
                user=user,
                token=token,
                next=request.args.get("next"),
            )
            flash("An email with instructions to reset your password has been sent to you.")
            return redirect(url_for("auth.login"))
        else:
            flash("Unable to find an account associated with that email address")
            return redirect(url_for("auth.password_reset_request"))
    return render_template("auth/reset_password.html", form=form)
Exemple #34
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            try:
                complaint = form.save(commit=False)

                complaint.company_relation = \
                    dict(data.COMPANY_RELATION_CHOICES)[int(form.cleaned_data['company_relation'])]

                if int(form.cleaned_data['company_relation']
                       ) == data.OTHER_CHOICE:
                    complaint.company_relation = form.cleaned_data[
                        'other_relation']

                complaint.people_complaint = []
                for k, item in request.POST.items():
                    if k.startswith('personcomplaint_set-'):
                        complaint.people_complaint.append(item)
                complaint.save()

                send_email(
                    subject='[GECOLSA] Nueva denuncia desde el portal web',
                    recipients=settings.DEFAULT_EMAIL_COMPLAINT,
                    email_template='email/complaint_email.html',
                    dictionary={'data': complaint},
                    attach=complaint.document.url
                    if complaint.document else None)

                messages.success(self.request, 'Envío satisfactorio')
                return HttpResponseRedirect(reverse('requests_complaints'))

            except (ValueError, KeyError):
                messages.error(self.request,
                               'Revisa los errores del formulario.')
                return self.render_to_response(
                    self.get_context_data(form=form))

        return self.form_invalid(form)
Exemple #35
0
def send_invoice(invoice: Invoice, request=None):
    context = get_substitutions_templates()
    context["invoice"] = invoice
    context["event"] = invoice.company_event.event
    context["user"] = invoice.responsible_company
    template = get_notification_template(
        method="email", type="sponsorship", task="invoice", format="html"
    )
    subject = get_notification_template(
        method="email", type="sponsorship", task="invoice", format="subject"
    ).format(event_name=str(invoice.company_event.event))
    body = render_to_string(template, context)
    attachments = [
        (
            invoice.invoice.file.name[invoice.invoice.file.name.rfind("/") + 1 :],
            invoice.invoice.file.read(),
            "application/pdf",
        )
    ]

    save_message(
        invoice.company_event.event.id,
        invoice.responsible_company.id,
        subject,
        body,
        MessageType.INVOICE,
        attachment=invoice.invoice,
    )

    send_email(
        subject=subject,
        body=body,
        to=invoice.responsible_company.email,
        tags=[MailTag.INVOICE],
        attachments=attachments,
    )

    invoice.mark_as_sent(request=request)
Exemple #36
0
def register():
    form = RegistrationForm()  # 实例化表单
    if form.validate_on_submit():  # 当form被提交时执行
        # 获取表单信息
        username = form.username.data
        email = form.email.data
        password = form.password.data
        user = User(username=username,
                    email=email,
                    password=password,
                    role=Role.query.filter_by(name='普通用户').first())
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_email('*****@*****.**',
                   user.email,
                   '认证你的账号',
                   template='auth/email/confirm',
                   user=user,
                   token=token)
        flash('注册成功,你现在可以登录了', 'success')
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)
Exemple #37
0
def password_reset_request():
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_confirmation_token()
            send_email(user.email,
                       'Reset Your Password',
                       'auth/email/reset_password',
                       user=user,
                       token=token,
                       next=request.args.get('next'))
            flash(
                "An email with instructions to reset your password has been sent to you."
            )
            return redirect(url_for('auth.login'))
        else:
            flash(
                "Unable to find an account associated with that email address")
            return redirect(url_for('auth.password_reset_request'))
    return render_template('auth/reset_password.html', form=form)
Exemple #38
0
def resend_user_activation():
    email = query_parser.parse_args()["email"]
    email = urllib.parse.unquote(email)
    user = UserModel.query.filter_by(email=email).first()
    activation_id = uuid4().hex
    redis_store.object.set(activation_id, str(user.id),
                           app.config["ACTIVATION_EXPIRES"])
    activation_link = (request.url_root[:-1] + url_for(
        "user_activation.user_activation", activation_id=activation_id) +
                       f"?email={email}")
    send_email(
        subject="Account Activation",
        sender=app.config["ADMIN"],
        recipients=[
            user.email,
        ],
        text_body=render_template("email/account_activation.txt",
                                  link=activation_link),
        html_body=render_template("email/account_activation.html",
                                  link=activation_link),
    )
    return render_template("new_activation_sent.html",
                           title="Activation Resent")
Exemple #39
0
    def form_valid(self, form):
        pattern = re.compile(r'(?!&)utm_[^=]*=[^&]*(?=&|$)')
        obj = form.save()
        obj.recipients = settings.DEFAULT_TO_EMAIL[0]
        obj.save()
        utm_list = re.findall(pattern, obj.full_path.rstrip())

        utm_dict = {}
        if utm_list:
            utm_dict = {
                utm.split('=')[0]: utm.split('=')[1]
                for utm in utm_list
            }

        send_email(
            '[GECOLSA] Contacto desde el portal web',
            [form.instance.email],
            'common/contact_email_user.html',
            {'contact': form.instance},
        )

        send_email(
            '[GECOLSA] Contacto desde el portal web',
            settings.DEFAULT_TO_EMAIL,
            'common/contact_email.html',
            {
                'contact': form.instance,
                'utm_dict': utm_dict
            },
        )

        return JsonResponse({
            'ok':
            True,
            'message':
            'Gracias por su interés, pronto le contactaremos.'
        })
def password_reset_request():
    """ users who request for a password change """
    if not current_user.is_anonymous:
        return redirect(url_for("main.index"))
    form = PasswordResetRequest()

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_confirmation_token()
            send_email(
                user.email,
                "Reset your password",
                "auth/email/reset_password",
                user=user,
                token=token,
                next=request.args.get("next"),
            )
            flash("we have send an email with instruction how to reset your password")
            return redirect(url_for("auth.login"))
        else:
            flash("No account found with that email address")
            return redirect(url_for("auth.change_password", form=form))
    return render_template("auth/reset_password.html", form=form)
Exemple #41
0
def send_mail(
        task, assigned=False, created=False, user=None,
        resolved=False, done=False, rejected=False, confirmed=False, **kwargs):
    if assigned:
        # Notify whoever was assigned via email
        send_email(
            task.assigned_to.email,
            "New Maintenance Task Assignment",
            'main/email/new-assignment',
            task=task
        )
    elif created:
        # Notify the admin of the new task.
        send_email(
            current_app.config['MAINTRAQ_ADMIN'],
            "New Maintenance Request",
            "main/email/new-task-request",
            task=task, user=user
        )
    elif resolved:
        send_email(
            task.requested_by.email,
            "Maintenance Request Resolved",
            "main/email/resolved",
            task=task
        )
    elif done:
        send_email(
            current_app.config['MAINTRAQ_ADMIN'],
            "Newly Completed Maintenance Task",
            "main/email/task-complete",
            task=task, user=user, **kwargs
        )
    elif rejected:
        send_email(
            task['requested_by'],
            "Maintenance Request Rejected",
            "main/email/task-rejected",
            task=task
        )
    elif confirmed:
        send_email(
            task.requested_by.email,
            "Maintenance Request Confirmed",
            "main/email/task-confirmed",
            task=task
        )
Exemple #42
0
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_email(current_user.email, "Confirm Your Account", "auth/email/confirm", user=current_user, token=token)
    flash("A new confirmation has been sent to you via email")
    return redirect(url_for("main.index"))
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_email(current_user.email, 'Confirm Your Email','auth/email/confirm',
                user=current_user, token=token)
    flash('We have sent a new confirmation email')
    return redirect(url_for('main.index'))
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_email(current_user.email, "Confirm Your Email", "auth/email/confirm", user=current_user, token=token)
    flash("We have sent a new confirmation email")
    return redirect(url_for("main.index"))