コード例 #1
0
ファイル: views.py プロジェクト: jochenklar/wbc
def unsubscribe(request, email=None):
    if request.method == 'POST':
        form = UnsubscribeForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.pop('email')
            try:
                subscriber = Subscriber.objects.get(email=email)

                try:
                    v = Validation.objects.get(email=email)
                except Validation.DoesNotExist:
                    v = Validation(email=email)

                v.action='unsubscribe'
                v.save()

                validate_path = reverse('wbc.news.views.validate',args=['.']).strip('.')

                send_mail(email, 'news/mail/unsubscribe.html', {
                    'validate_link': settings.SITE_URL + validate_path + v.code
                })

            except Subscriber.DoesNotExist:
                pass # don't tell the user

            return render(request,'news/unsubscribe.html', {'success': True})
    else:
        form = UnsubscribeForm(initial={'email': email})

    return render(request,'news/unsubscribe.html', {'form': form})
コード例 #2
0
ファイル: views.py プロジェクト: ricardopadilha/modoboa
def compose(request):
    url = "?action=compose"
    if request.method == "POST":
        status, resp = send_mail(request, posturl=url)
        return resp

    form = ComposeMailForm()
    return render_compose(request, form, url, insert_signature=True)
コード例 #3
0
def compose(request):
    url = "?action=compose"
    if request.method == "POST":
        status, resp = send_mail(request, posturl=url)
        return resp

    form = ComposeMailForm()
    return render_compose(request, form, url, insert_signature=True)
コード例 #4
0
ファイル: views.py プロジェクト: userzimmermann/wbc
def subscribe(request):
    entities = District.objects.all().values()

    unsubscribe_path = reverse(
        'wbc.news.views.unsubscribe', args=['.']).strip('.')
    validate_path = reverse('wbc.news.views.validate', args=['.']).strip('.')

    if request.method == 'POST':
        form = SubscribeForm(request.POST, entities=entities)
        if form.is_valid():
            email = form.cleaned_data.pop('email')
            entitiesJson = dumps(form.cleaned_data)

            try:
                v = Validation.objects.get(email=email)
            except Validation.DoesNotExist:
                v = Validation(email=email)

            v.entities = entitiesJson
            v.action = 'subscribe'
            v.save()

            send_mail(email, 'news/mail/subscribe.html', {
                'unsubscribe_link': settings.SITE_URL + unsubscribe_path + email,
                'validate_link': settings.SITE_URL + validate_path + v.code
            })

            return render(request, 'news/subscribe.html', {
                'success': True,
                'unsubscribe_link': settings.SITE_URL + unsubscribe_path + email
            })
    else:
        form = SubscribeForm(entities=entities)

    return render(request, 'news/subscribe.html', {
        'form': form,
        'unsubscribe_link': settings.SITE_URL + unsubscribe_path,
        'entities': entities
    })
コード例 #5
0
ファイル: views.py プロジェクト: rascul/charg
def request_release(requestid):
    cur = g.db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
    cur.execute("select * from requests where requestid = %s", (requestid,))

    if cur.rowcount == 1:
        request = cur.fetchone()
        cur.execute("select * from chars where charid = %s", (request.charid,))

        if cur.rowcount == 1:
            char = cur.fetchone()

            if current_user.uid == char.creator:
                cur.execute("delete from requests where charid = %s", (request.charid,))
                cur.execute(
                    "update chars set owner = %s, released = current_timestamp where charid = %s",
                    (request.name, char.charid),
                )
                g.db.commit()

                body = app.config.get("RELEASE_MESSAGE") % (
                    char.name,
                    char.password,
                    char.sex,
                    char.race,
                    char.char_class,
                    char.homeland,
                    char.level,
                    char.hitpoints,
                    char.moves,
                    char.stat_str,
                    char.stat_int,
                    char.stat_wil,
                    char.stat_dex,
                    char.stat_con,
                    char.stat_str + char.stat_int + char.stat_wil + char.stat_dex + char.stat_con,
                    char.rent,
                    char.notes,
                )

                if send_mail(
                    mail, app.config.get("MAIL_SENDER_ADDRESS"), request.email, app.config.get("RELEASE_SUBJECT"), body
                ):
                    return redirect(url_for("requests"))
                else:
                    return render_template("fail.html", message="Could not send email.")
            else:
                return render_template("fail.html", message="This is not your character.")
        else:
            return render_template("fail.html", message="That character does not exist.")
    else:
        return render_template("fail.html", message="That request does not exist.")
コード例 #6
0
ファイル: views.py プロジェクト: ricardopadilha/modoboa
def compose_and_send(request, action, callback=None):
    mbox = request.GET.get("mbox", None)
    mailid = request.GET.get("mailid", None)
    if mbox is None or mailid is None:
        raise WebmailError(_("Bad request"))
    url = "?action=%s&mbox=%s&mailid=%s" % (action, mbox, mailid)
    if request.method == "POST":
        status, resp = send_mail(request, url)
        if status and callback:
            callback(mbox, mailid)
        return resp

    form = ComposeMailForm()
    modclass = globals()["%sModifier" % action.capitalize()]
    email = modclass(mbox, mailid, request, form, addrfull=True, links="1")
    return render_compose(request, form, url, email)
コード例 #7
0
def compose_and_send(request, action, callback=None):
    mbox = request.GET.get("mbox", None)
    mailid = request.GET.get("mailid", None)
    if mbox is None or mailid is None:
        raise WebmailError(_("Bad request"))
    url = "?action=%s&mbox=%s&mailid=%s" % (action, mbox, mailid)
    if request.method == "POST":
        status, resp = send_mail(request, url)
        if status and callback:
            callback(mbox, mailid)
        return resp

    form = ComposeMailForm()
    modclass = globals()["%sModifier" % action.capitalize()]
    email = modclass(mbox, mailid, request, form, addrfull=True, links="1")
    return render_compose(request, form, url, email)
コード例 #8
0
ファイル: views.py プロジェクト: rascul/charg
def request_char(charid):
    cur = g.db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)

    # check if charid exists
    cur.execute("select charid from chars where charid = %s", (charid,))
    if cur.rowcount != 1:
        return render_template("fail.html", message="Invalid character.")

    request_name = request.form.get("name")
    request_email = request.form.get("email")

    # verify we got both name and email, maybe at a later point verify
    # that the email address is valid
    if not request_name:
        return render_template("fail.html", message="You must enter a name.")
    if not request_email:
        return render_template("fail.html", message="You must enter a email address.")

    cur.execute(
        "insert into requests (charid, name, email) values (%s, %s, %s) returning requestid",
        (charid, request_name, request_email),
    )
    requestid = cur.fetchone().requestid
    if requestid:
        g.db.commit()

        email = ""

        cur.execute(
            "select users.email from users, chars where chars.charid = %s and chars.creator = users.uid", (charid,)
        )
        email = cur.fetchone().email

        if email:
            body = app.config.get("REQUEST_MESSAGE") % charid

            if send_mail(mail, app.config.get("MAIL_SENDER_ADDRESS"), email, app.config.get("REQUEST_SUBJECT"), body):
                return render_template("success.html")
            else:
                return render_template("fail.html", message="Could not send email.")
        else:
            return render_template("fail.html", message="Could not get email address from database.")
    else:
        return render_template("fail.html", message="Could not insert request into database.")
コード例 #9
0
def run(uri_data, subject=None):
    """Validate the given URIs then print and email the results.

    @param uri_data: List of rows of data which each row is a dictionary
        with the following format:
            {
                'title': str,
                'URI': str,
                'notify': str
            }
    @param subject: Message to use for the subject and heading of the
        mail. The current date will be added to the end of the subject.
        Leave the subject set to None to prevent sending of a mail.

    @return: None
    """
    # Clean the data first.
    uri_schema = UriData()
    cleaned_data = []
    for row in uri_data:
        try:
            cleaned_row = uri_schema.to_python(row)
        except Invalid as e:
            # Print a brief error message and show the problem row, which
            # should not be prettified in case that raises an error. Then exit.
            print("{error}. {message} \n".format(error=type(e).__name__,
                                                 message=str(e)))
            print("Input row: \n {0}".format(row))
            sys.exit(1)

        cleaned_data.append(cleaned_row)

    # Perform the main validation logic which this app is based around.
    for row in cleaned_data:
        row['result'] = validate_uri(row['URI'])

    # Handle printing of plain text report of all rows.
    template = "{result:10} {title:20} {uri}"
    header = template.format(result="Result", title="Title", uri="URI")
    plain_text_rows = [
        template.format(result=row['result'],
                        title=row['title'],
                        uri=row['URI']) for row in cleaned_data
    ]
    print(header)
    print("=" * len(header))
    for row in plain_text_rows:
        print(row)

    if subject:
        # Handle mailing an HTML report, for rows matching
        # notification conditions.
        matched_rows = []
        for data in cleaned_data:
            if (data['notify'] == 'always'
                    or (data['result'] == 'OK' and data['notify'] == 'valid')
                    or
                (data['result'] == 'Invalid' and data['notify'] == 'invalid')):
                matched_rows.append(data)

        if matched_rows:
            count = len(matched_rows)
            print("Sending mail with {count} matched row{plural}.".format(
                count=count, plural="s" if count != 1 else ""))

            subject_with_date = "{subject} {date}".format(
                subject=subject, date=str(datetime.date.today()))
            matched_rows_as_text = [
                template.format(result=row['result'],
                                title=row['title'],
                                uri=row['URI']) for row in cleaned_data
            ]
            plain_text = [header, "=" * len(header)] + matched_rows_as_text
            html = build_html(mail_title=subject_with_date,
                              uri_data=matched_rows)

            send_mail(subject=subject_with_date,
                      plain_text="\n".join(plain_text),
                      html=html)
            print("Sent mail.")
        else:
            print("Zero rows matched, so no mail was sent.")
コード例 #10
0
ファイル: main.py プロジェクト: msirovy/flask-guest-portal
def register(lang="cs"):
    if lang == 'cs':
        _form = Enroll_cz(request.form)
        msg_mail = "Zpráva byla odeslána vašemu ručiteli. " + \
            "Jakmile potvrdí vámi zaslaný email, budete moci " + \
            "využívat síť <strong>FZU-GUEST</strong>."

    else:
        _form = Enroll(request.form)
        msg_mail = "Message has sent to your garant. " + \
            "After garant confirm that mail you will be able " + \
            "to use <strong>FZU-GUEST</strong> network."

    try:
        if request.method == 'POST' and _form.validate():
            _data = {k: str(v) for k, v in _form.data.items()}
            _data['mac_addr'] = get_mac(request.remote_addr)
            _data['table_name'] = db['table']

            md5 = hashlib.md5()
            hash_str = str(_data['mac_addr'] +
                           _data['garant_mail'] +
                           str(time.time()))
            md5.update(hash_str.encode())

            _data['code_reg'] = md5.hexdigest()
            _data['mac_addr'] = get_mac(request.remote_addr)

            sql = "INSERT INTO {table_name} " + \
                        "(code_registration, " + \
                            "first_name, " + \
                            "last_name, " + \
                            "phone, " + \
                            "mail, " + \
                            "days, " + \
                            "garant_mail, " + \
                            "mac_addr) " + \
                        "VALUES (" + \
                            "'{code_reg}', " + \
                            "'{first_name}', " + \
                            "'{last_name}', " + \
                            "'{phone}', " + \
                            "'{mail}', " + \
                            "'{days}', " + \
                            "'{garant_mail}', " + \
                            " '{mac_addr}');".format_map(_data)

            """ send email to grant, save request to db
                and show enroll page
            """
            if send_mail(smtp=smtp,
                         template=CONF['confirm_mail'], data=_data):
                db_exec(db, sql, debug=True)
                return render_template(
                                    'layout.j2',
                                    message=msg_mail
                                )

        else:
            return render_template(
                            'enroll.j2',
                            form=_form,
                            lang=lang,
                        )

    except KeyError as err:
        return render_template(
                        'enroll.j2',
                        form=_form,
                        lang=lang,
                    )