Esempio n. 1
0
def edit(post_id):

    post = Post.query.get_or_404(post_id)
    post.permissions.edit.test(403)

    form = PostForm(obj=post)
    if form.validate_on_submit():

        form.populate_obj(post)
        db.session.commit()

        if g.user.id != post.author_id:
            body = render_template("emails/post_edited.html", post=post)

            message = Message(subject="Your post has been edited",
                              body=body,
                              recipients=[post.author.email])

            mail.send(message)

            flash(_("The post has been updated"), "success")

        else:
            flash(_("Your post has been updated"), "success")
        return redirect(url_for("post.view", post_id=post_id))

    return render_template("post/edit_post.html", post=post, form=form)
Esempio n. 2
0
def admin_send_reminder(payment_id):
    payment = BankPayment.query.get_or_404(payment_id)

    form = SendReminderForm()
    if form.validate_on_submit():
        if form.remind.data:
            app.logger.info(
                "%s sending reminder email to %s <%s> for payment %s",
                current_user.name, payment.user.name, payment.user.email,
                payment.id)

            if payment.reminder_sent:
                app.logger.error('Reminder for payment %s already sent',
                                 payment.id)
                flash("Cannot send duplicate reminder email for payment %s" %
                      payment.id)
                return redirect(url_for('admin_expiring'))

            msg = Message("Electromagnetic Field ticket purchase update",
                          sender=app.config['TICKETS_EMAIL'],
                          recipients=[payment.user.email])
            msg.body = render_template("tickets-reminder.txt", payment=payment)
            mail.send(msg)

            payment.reminder_sent = True
            db.session.commit()

            flash("Reminder email for payment %s sent" % payment.id)
            return redirect(url_for('admin_expiring'))

    return render_template('admin/payment-send-reminder.html',
                           payment=payment,
                           form=form)
Esempio n. 3
0
def delete(post_id):

    post = Post.query.get_or_404(post_id)
    post.permissions.delete.test(403)

    Comment.query.filter_by(post=post).delete()

    db.session.delete(post)
    db.session.commit()

    if g.user.id != post.author_id:
        body = render_template("emails/post_deleted.html", post=post)

        message = Message(subject="Your post has been deleted",
                          body=body,
                          recipients=[post.author.email])

        mail.send(message)

        flash(_("The post has been deleted"), "success")

    else:
        flash(_("Your post has been deleted"), "success")

    return jsonify(success=True, redirect_url=url_for('frontend.index'))
Esempio n. 4
0
def forgot_password():

    form = RecoverPasswordForm()

    if form.validate_on_submit():

        user = User.query.filter_by(email=form.email.data).first()

        if user:
            flash(
                _("Please see your email for instructions on "
                  "how to access your account"), "success")

            user.activation_key = str(uuid.uuid4())
            db.session.commit()

            body = render_template("emails/recover_password.html", user=user)

            message = Message(subject=_("Recover your password"),
                              body=body,
                              recipients=[user.email])

            mail.send(message)

            return redirect(url_for("frontend.index"))

        else:

            flash(_("Sorry, no user found for that email address"), "error")

    return render_template("account/recover_password.html", form=form)
Esempio n. 5
0
    def run(self):
        print "warning about expired Tickets"
        seen = {}
        expired = Ticket.query.filter(Ticket.expires <= datetime.utcnow(),
                                      Ticket.paid == False).all()
        for t in expired:
            # test that the ticket has a payment... not all do.
            if t.payment:
                if t.payment.id not in seen:
                    seen[t.payment.id] = True

        for p in seen:
            p = Payment.query.get(p)
            print "emailing %s <%s> about payment %d" % (p.user.name,
                                                         p.user.email, p.id)
            # race condition, not all ticket may of expired, but if any of
            # them have we will warn about all of them.
            # not really a problem tho.

            msg = Message("Electromagnetic Field ticket purchase update",
                          sender=app.config['TICKETS_EMAIL'],
                          recipients=[p.user.email])
            msg.body = render_template("tickets-expired-warning.txt",
                                       payment=p)
            mail.send(msg)
Esempio n. 6
0
def send_mail(account, subject, body):
    message = Message(subject,
                      recipients=[account.email],
                      body=body,
                      sender=(app.config['SITE_NAME'],
                              app.config['SITE_SENDER']))
    mail.send(message)
Esempio n. 7
0
def contact():

    if g.user:
        form = ContactForm(name=g.user.username,
                           email=g.user.email)

    else:
        form = ContactForm()

    if form.validate_on_submit():

        admins = current_app.config.get('ADMINS', [])

        from_address = "%s <%s>" % (form.name.data, 
                                    form.email.data)

        if admins:
            message = Message(subject=form.subject.data,
                              body=form.message.data,
                              recipients=admins,
                              sender=from_address)

            mail.send(message)
        
        flash(_("Thanks, your message has been sent to us"), "success")

        return redirect(url_for('frontend.index'))

    return render_template("contact.html", form=form)
Esempio n. 8
0
def register(year, eventname):
    form = RegisterForm()
    event = Event.query.filter_by(name=eventname, year=year).first()
    if form.validate_on_submit():
        participant = Participant()
        form.populate_obj(participant)
        participant.event_id = event.id
        participant.ipaddr = request.environ['REMOTE_ADDR']
        participant.useragent = request.user_agent.string
        participant.email_key = uuid4().hex
        db.session.add(participant)
        db.session.commit()
        if not participant.email_sent:
            msg = Message(subject="Geekup Confirmation",
                          recipients=[participant.email])
            msg.body = render_template("confirmemail.md",
                                       participant=participant)
            msg.html = markdown(msg.body)
            mail.send(msg)
            participant.email_sent = True
            db.session.commit()
        return render_template('regsuccess.html')
    else:
        if request.is_xhr:
            return render_template('regform.html',
                                   regform=form,
                                   ajax_re_register=True)
        else:
            flash("Please check your details and try again.", 'error')
            return eventpage(eventname, regform=form)
Esempio n. 9
0
def notification_del_detail(g_id, item, value):
    db = connect_db()
    group = db.notifications.find_one({'id': g_id})
    if not group:
        return 'unknown group ' + g_id
    # TODO handle restricted groups
    #if group.restricted:
    #    return 'restricted group'
    if item == 'emails':
        print value
        print group['active_emails']
        if value not in group['active_emails']:
            return 'Cannot complete this action'
        i = {
            'address':
            value,
            'type':
            'unsubscription',
            'token':
            sha1(''.join([chr(randint(32, 122))
                          for x in range(12)])).hexdigest(),
            'date':
            datetime.now()
        }
        group['actions'].append(i)
        msg = Message("Parltrack Notification Unsubscription Verification",
                      sender="*****@*****.**",
                      recipients=[value])
        msg.body = "Your verification key is %sactivate?key=%s\nNotification group url: %snotification/%s" % (
            request.url_root, i['token'], request.url_root, g_id)
        mail.send(msg)
        db.notifications.save(group)
    return 'OK'
Esempio n. 10
0
def send_message(user_id):

    user = User.query.get_or_404(user_id)
    user.permissions.send_message.test(403)

    form = MessageForm()

    if form.validate_on_submit():

        body = render_template("emails/send_message.html",
                               user=user,
                               subject=form.subject.data,
                               message=form.message.data)

        subject = _("You have received a message from %(name)s",
                    name=g.user.username)

        message = Message(subject=subject, body=body, recipients=[user.email])

        mail.send(message)

        flash(_("Your message has been sent to %(name)s", name=user.username),
              "success")

        return redirect(url_for("user.posts", username=user.username))

    return render_template("user/send_message.html", user=user, form=form)
Esempio n. 11
0
def notify(data,d):
    if not 'epdoc' in data: return
    m=db.notifications.find({'dossiers': data['epdoc']},['active_emails'])
    for g in m:
        if len(g['active_emails'])==0:
            continue
        msg = Message("[PT-Com] %s: %s" %
                      (data['committee'],
                       data['title']),
                      sender = "*****@*****.**",
                      bcc = g['active_emails'])
        msg.body = (u"Parltrack has detected %s%s on the schedule of %s \n"
                    u"\n  on %s"
                    u"\n%s"
                    u"%s"
                    u"\nsee the details here: %s\n"
                    u"\nYour Parltrack team" %
                    (u"a change on " if d else u'',
                     data['epdoc'],
                     data['committee'],
                     data['date'] if 'date' in data else 'unknown date',
                     ("\n  - %s" % u'\n  - '.join(data['list'])) if 'list' in data and len(data['list'])>0 else u"",
                     "\n %s" % (textdiff(d) if d else ''),
                     "%s/dossier/%s" % (ROOT_URL, data['epdoc']),
                    ))
        mail.send(msg)
Esempio n. 12
0
def notify(snipe, index):
    """ Notify this snipe that their course is open"""
    course = '%s:%s:%s' % (snipe.subject, snipe.course_number, snipe.section)

    if snipe.user.email:

        attributes = {
            'email': snipe.user.email,
            'subject': snipe.subject,
            'course_number': snipe.course_number,
            'section': snipe.section,
        }

        # build the url for prepopulated form
        url = 'http://sniper.rutgers.io/?%s' % (urllib.urlencode(attributes))

        register_url = 'https://sims.rutgers.edu/webreg/editSchedule.htm?login=cas&semesterSelection=92016&indexList=%s' % (index)

        email_text = 'A course (%s) that you were watching looks open. Its index number is %s. Click the link below to register for it!\n\n %s \n\n If you don\'t get in, visit this URL: \n\n %s \n\n to continue watching it.\n\n Send any feedback to [email protected]' % (course, index, register_url, url)

        # send out the email
        message = Message('[Course Sniper](%s) is open' %(course), sender=EMAIL_SENDER)
        message.body = email_text
        message.add_recipient(snipe.user.email)
        message.add_recipient(snipe.user.email)

        mail.send(message)

    db.session.delete(snipe)
    db.session.commit()

    app.logger.warning('Notified user: %s about snipe %s' % (snipe.user, snipe))
Esempio n. 13
0
def signup():
    if current_user.is_authenticated():
        return redirect(url_for('tickets'))
    form = SignupForm(request.form, next=request.args.get('next'))

    if request.method == 'POST' and form.validate():
        user = User(form.email.data, form.name.data)
        user.set_password(form.password.data)
        db.session.add(user)
        try:
            db.session.commit()
        except IntegrityError, e:
            app.logger.warn('Adding user raised %r, assuming duplicate email',
                            e)
            flash(
                "This email address %s is already in use. Please log in, or reset your password if you've forgotten it."
                % (form.email.data))
            return redirect(url_for('login'))
        login_user(user)

        # send a welcome email.
        msg = Message("Welcome to Electromagnetic Field",
                      sender=app.config['TICKETS_EMAIL'],
                      recipients=[user.email])
        msg.body = render_template("welcome-email.txt", user=user)
        mail.send(msg)

        return redirect(form.next.data or url_for('tickets'))
Esempio n. 14
0
def index():
    msg = Message('Hello',
                  sender='*****@*****.**',
                  recipients=['recipient@recipient_domain.com'])
    msg.body = "This is the email body"
    mail.send(msg)
    return "Sent"
Esempio n. 15
0
def report_abuse(comment_id):

    comment = Comment.query.get_or_404(comment_id)
    form = CommentAbuseForm()
    if form.validate_on_submit():

        admins = current_app.config['ADMINS']

        if admins:

            body = render_template("emails/report_abuse.html",
                                   comment=comment,
                                   complaint=form.complaint.data)

            message = Message(subject="Report Abuse",
                              body=body,
                              sender=g.user.email,
                              recipients=admins)

            mail.send(message)

        flash(_("Your report has been sent to the admins"), "success")

        return redirect(comment.url)

    return render_template("comment/report_abuse.html",
                           comment=comment,
                           form=form)
Esempio n. 16
0
def forgotpass():
    form = RecoverPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            # generate activation_key and save it in database
            user.activation_key = str(uuid.uuid4())
            user.save()

            # send recover email
            if setting.MAIL_ENABLE:
                body = render_template("emails/forgotpass.html", user=user)
                message = Message(subject=u"找回密码",
                                  body=body,
                                  sender=setting.ADMIN_MAIL,
                                  recipients=[user.email])
                mail.send(message)
                flash(u"邮件已发出", "successfully")
            else:
                flash(u"邮件服务器未开启,请联系管理员", "error")

            return redirect(url_for("account.forgotpass"))
        else:
            flash(u"对不起,没找到你的邮件", "error")
    return render_template("account/forgotpass.html", form=form)
Esempio n. 17
0
def send_email(to, subject, template):
    msg = Message(
        subject,
        recipients=[to],
        html=template,
        sender=app.config["MAIL_DEFAULT_SENDER"],
    )
    mail.send(msg)
Esempio n. 18
0
def your_view():
    subject = "Mail with PDF"
    receiver = "*****@*****.**"
    mail_to_be_sent = Message(subject=subject, recipients=[receiver])
    mail_to_be_sent.body = "This email contains PDF."
    pdf = create_pdf(render_template('your/template.html'))
    mail_to_be_sent.attach("file.pdf", "application/pdf", pdf.getvalue())
    mail_ext.send(mail_to_be_sent)
    return redirect(url_for('other_view'))
Esempio n. 19
0
def mark_complete():
    """
    Checks to see if a group exists in FAS for the given project and marks the
    project complete if it does. We do this this way so that we don't have to
    send FAS credentials to this app.
    """
    fas = fedora.client.AccountSystem(app.config['FAS_SERVER'],
                                      username=app.config['FAS_USERNAME'],
                                      password=app.config['FAS_PASSWORD'],
                                      insecure=app.config['FAS_INSECURE_SSL'])
    hosted_request = HostedRequest.query.filter_by(id=request.args.get('id'))
    if hosted_request.count() > 0:
        project = hosted_request[0]
        if project.completed:
            return jsonify(error="Request was already marked as completed.")

        group_name = project.scm + project.name
        try:
            group = fas.group_by_name(group_name)
        except:
            return jsonify(error="No such group: " + group_name)

        project.completed = datetime.now()
        db.session.commit()
        message = Message("Your Fedora Hosted request has been processed")
        message.body = """Hi there,

You're receiving this message because the Fedora Hosted project:
  %s
has been set up.

To access to your new repository, do the following:
  $ %s

If you've requested a Trac instance, you can visit it at:
  https://fedorahosted.org/%s

If you've requested any mailing lists, you should have received separate
emails which contain instructions on how to administrate them.

Sincerely,
Fedora Hosted""" % (project.name, scm_push_instructions(project), project.name)

        message.sender = \
            "Fedora Hosted <*****@*****.**>"

        if 'PROJECT_OWNER_EMAIL_OVERRIDE' in app.config:
            message.recipients = [app.config['PROJECT_OWNER_EMAIL_OVERRIDE']]
        else:
            message.recipients = ["*****@*****.**" % project.owner]

        if not app.config['TESTING']:
            mail.send(message)

        return jsonify(success="Request marked as completed.")
    else:
        return jsonify(error="No hosted request with that ID could be found.")
Esempio n. 20
0
def verify_domain(org):
    porg = get_object_or_404(PendingOrganization, org)
    
    email = request.args.get('e')
    sig = request.args.get('s')
    if all([sig, email]):
        # Generate a unique slug from name
        base_slug = slugify(porg.name)
        slug = base_slug
        i = 1
        while Organization.objects.exists(slug):
            slug = '%s-%s' % (base_slug, i)
            i += 1
    
        org = Organization.objects.create(
            pk=slug,
            name=porg.name,
            lang=porg.lang,
            domain=porg.domain,
            owned_by=porg.created_by,
        )
        
        OrganizationMember.objects.create(
            org=org.pk,
            user=porg.created_by,
        )
        
        flash("Your organization was created successfully!")
        
        return redirect(url_for('list_snippets', org=org.pk))
    
    form = VerifyDomainForm()
    if form.validate_on_submit():
        email = '%s@%s' % (form.email_username.data, porg.domain)
        sig = hashlib.md5(email)
        sig.update(app.config['SECRET_KEY'])
        sig = sig.hexdigest()
        
        app.logger.info("Sending domain verification to %s", email)

        body = render_template('organizations/mail/verify_domain.txt', **{
            'verify_url': '%s?e=%s&s=%s' % (url_for('verify_domain', org=porg.pk, _external=True), quote(email), quote(sig)),
        })
        
        msg = Message("Codebox Domain Verification",
                      recipients=[email],
                      body=body)
        mail.send(msg)
        
        flash("An email has been sent to %s to validate domain ownership." % email)

    return render_template('organizations/verify_domain.html', **{
        'porg': porg,
        'form': form,
    })
    return redirect('/')
Esempio n. 21
0
def save(data, stats):
    if not data: return stats
    src = data['meta']['source']
    res = db.dossiers2.find_one({'meta.source': src}) or {}
    d = diff(
        dict([(k, v) for k, v in res.items()
              if not k in ['_id', 'meta', 'changes']]),
        dict([(k, v) for k, v in data.items() if not k in [
            '_id',
            'meta',
            'changes',
        ]]))
    #logger.warn(pprint.pformat(d))
    if d:
        now = datetime.datetime.utcnow().replace(microsecond=0).isoformat()
        if not res:
            logger.info(('adding %s - %s' %
                         (data['procedure']['reference'],
                          data['procedure']['title'])).encode('utf8'))
            data['meta']['created'] = data['meta']['timestamp']
            del data['meta']['timestamp']
            sys.stdout.flush()
            stats[0] += 1
        else:
            logger.info(('updating  %s - %s' %
                         (data['procedure']['reference'],
                          data['procedure']['title'])).encode('utf8'))
            data['meta']['updated'] = data['meta']['timestamp']
            del data['meta']['timestamp']
            sys.stdout.flush()
            stats[1] += 1
            data['_id'] = res['_id']
            logger.info(jdump(d))
        if not NOMAIL:
            m = db.notifications.find(
                {'dossiers': data['procedure']['reference']},
                ['active_emails'])
            for g in m:
                if len(g['active_emails']) == 0:
                    continue
                msg = Message("[PT] %s %s" % (data['procedure']['reference'],
                                              data['procedure']['title']),
                              sender="*****@*****.**",
                              bcc=g['active_emails'])
                #msg.html = htmldiff(data,d)
                msg.body = makemsg(data, d)
                mail.send(msg)
        #logger.info(htmldiff(data,d))
        #logger.info(makemsg(data,d))
        data['changes'] = res.get('changes', {})
        data['changes'][now] = d
        db.dossiers2.save(data)
    return stats
Esempio n. 22
0
def manual_reconcile():
    if current_user.admin:
        if request.method == "POST":
            form = ManualReconcileForm()
            if form.validate():
                if form.yes.data == True:
                    payment = BankPayment.query.get(int(form.payment.data))
                    app.logger.info("%s Manually reconciled payment %s (%s)",
                                    current_user.name, payment.id,
                                    payment.bankref)
                    for t in payment.tickets:
                        t.paid = True
                        app.logger.info("ticket %s (%s, for %s) paid", t.id,
                                        t.type.name, payment.user.name)
                    payment.state = "paid"
                    db.session.commit()

                    msg = Message(
                        "Electromagnetic Field ticket purchase update",
                        sender=app.config['TICKETS_EMAIL'],
                        recipients=[payment.user.email])
                    msg.body = render_template(
                        "tickets-paid-email-banktransfer.txt",
                        user=payment.user,
                        payment=payment)
                    mail.send(msg)

                    flash("Payment ID %s now marked as paid" % (payment.id))
                    return redirect(url_for('manual_reconcile'))
                elif form.no.data == True:
                    return redirect(url_for('manual_reconcile'))
                elif form.reconcile.data == True:
                    payment = BankPayment.query.get(int(form.payment.data))
                    ynform = ManualReconcileForm(payment=payment.id,
                                                 formdata=None)
                    return render_template(
                        'admin/admin_manual_reconcile_yesno.html',
                        ynform=ynform,
                        payment=payment)

        payments = BankPayment.query.filter(
            BankPayment.state == "inprogress").order_by(
                BankPayment.bankref).all()
        paymentforms = {}
        for p in payments:
            paymentforms[p.id] = ManualReconcileForm(payment=p.id,
                                                     formdata=None)
        return render_template('admin/admin_manual_reconcile.html',
                               payments=payments,
                               paymentforms=paymentforms)
    else:
        return (('', 404))
Esempio n. 23
0
def email():
    try:
        msg = Message('Message from Hat Team Generator',
                      body='From ' + request.form['name'] + ', message is:\n' +
                      request.form['message'],
                      sender=request.form['email'],
                      recipients=[email_address])

        mail.send(msg)
    except Exception:
        print 'Something went wrong sending an email:', sys.exc_info()[0]

    return ''
Esempio n. 24
0
    def run(self):
        query = text("""select distinct "user".id from "user", ticket 
                        where ticket.user_id = "user".id and ticket.paid = true"""
                     )

        for row in db.engine.execute(query):
            user = User.query.filter_by(id=row[0]).one()
            msg = Message("Your Electromagnetic Field Ticket",
                          sender=app.config['TICKETS_EMAIL'],
                          recipients=[user.email])
            user.create_receipt()
            msg.body = render_template("ticket.txt", user=user)
            print "Sending to", user.email, "..."
            mail.send(msg)
Esempio n. 25
0
def notification_add_detail(g_id, item, value):
    db = connect_db()
    group = db.notifications.find_one({'id': g_id})
    if not group:
        return 'unknown group ' + g_id
    # TODO handle restricted groups
    #if group.restricted:
    #    return 'restricted group'
    if item == 'emails':
        if value in group['active_emails']:
            return 'already subscribed to this group'
        item = 'actions'
        # TODO validation
        addr = db.notifications.find_one({
            'actions.address': value,
            'id': g_id
        })
        if addr:
            # or just return with OK?! -> more privacy but harder debug
            return 'Already subscribed'
        i = {
            'address':
            value,
            'type':
            'subscription',
            'token':
            sha1(''.join([chr(randint(32, 122))
                          for x in range(12)])).hexdigest(),
            'date':
            datetime.now()
        }
        msg = Message("Parltrack Notification Subscription Verification",
                      sender="*****@*****.**",
                      recipients=[value])
        msg.body = "Your verification key is %sactivate?key=%s\nNotification group url: %snotification/%s" % (
            request.url_root, i['token'], request.url_root, g_id)
        mail.send(msg)

    else:
        #if db.notifications.find({'dossiers': value}).count():
        #    return 'OK'
        i = db.dossiers.find_one({'procedure.reference': value})
        if not i:
            return 'unknown dossier - ' + value
        i = i['procedure']['reference']

    group[item].append(i)
    db.notifications.save(group)
    return 'OK'
Esempio n. 26
0
def remind_password():
    form = PasswordReminder()
    if request.method == "POST":
        if form.validate():
            # get the project
            project = Project.query.get(form.id.data)

            # send the password reminder
            mail.send(Message("password recovery",
                body=render_template("password_reminder.%s" % get_locale().language,
                    project=project),
                recipients=[project.contact_email]))
            flash(_("a mail has been sent to you with the password"))

    return render_template("password_reminder.html", form=form)
Esempio n. 27
0
def ajaxtest():
    result = {
        'success': test(),
    }

    if not result['success']:
        from cron import EMAIL_SENDER
        from flaskext.mail import Message

        message = Message('Sniper tests are failing', sender=EMAIL_SENDER)
        message.body = 'FIX IT'
        message.add_recipient('*****@*****.**')
        mail.send(message)

    return json.dumps(result)
Esempio n. 28
0
def mailall():
    "Sends an email to all users"

    subject = prompt("Subject")
    message = prompt("Message")
    from_address = prompt("From", default="*****@*****.**")
    if prompt_bool("Are you sure ? Email will be sent to everyone!"):
        with mail.connect() as conn:
            for user in User.query:
                message = Message(subject=subject,
                                  body=message,
                                  sender=from_address,
                                  recipients=[user.email])

                conn.send(message)
Esempio n. 29
0
def create_project():
    form = ProjectForm()
    if request.method == "GET" and 'project_id' in request.values:
        form.name.data = request.values['project_id']

    if request.method == "POST":
        # At first, we don't want the user to bother with the identifier
        # so it will automatically be missing because not displayed into the form
        # Thus we fill it with the same value as the filled name, the validation will
        # take care of the slug
        if not form.id.data:
            form.id.data = form.name.data
        if form.validate():
            # save the object in the db
            project = form.save()
            db.session.add(project)
            db.session.commit()

            # create the session object (authenticate)
            session[project.id] = project.password
            session.update()

            # send reminder email
            g.project = project

            message_title = _("You have just created '%(project)s' to share your expenses",
                    project=g.project.name)

            message_body = render_template("reminder_mail.%s" % get_locale().language)

            msg = Message(message_title,
                body=message_body,
                recipients=[project.contact_email])
            try:
                mail.send(msg)
            except SMTPRecipientsRefused:
                msg_compl = 'Problem sending mail. '
                # TODO: destroy the project and cancel instead?
            else:
                msg_compl = ''

            # redirect the user to the next step (invite)
            flash(_("%(msg_compl)sThe project identifier is %(project)s",
                msg_compl=msg_compl, project=project.id))
            return redirect(url_for(".invite", project_id=project.id))

    return render_template("create_project.html", form=form)
Esempio n. 30
0
def delete(post_id):
    post = Post.query.get_or_404(post_id)
    post.permissions.delete.test(403)
    post.delete()
    if current_user.id != post.author_id:
        if setting.MAIL_ENABLE:
            body = render_template("emails/postdeleted.html", post=post)
            message = Message(subject=u"你提交的条目已删除",
                              body=body,
                              recipients=[post.author.email])

            mail.send(message)
            flash(u"条目已被删除", "successfully")
        else:
            flash(u"邮件服务器未开启,请联系管理员", "error")
    else:
        flash(u"你的条目成功删除", "successfully")
    return jsonify(success=True, redirect_url=url_for('home.index'))