Exemplo n.º 1
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)
Exemplo n.º 2
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=92015&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))
Exemplo n.º 3
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)
Exemplo n.º 4
0
def admin_txn_reconcile(txn_id, payment_id):
    txn = BankTransaction.query.get_or_404(txn_id)
    payment = BankPayment.query.get_or_404(payment_id)

    form = ManualReconcilePaymentForm()
    if form.validate_on_submit():
        if form.reconcile.data:
            app.logger.info("%s manually reconciling against payment %s (%s) by %s",
                            current_user.name, payment.id, payment.bankref, payment.user.email)

            if txn.payment:
                app.logger.error("Transaction already reconciled")
                flash("Transaction %s already reconciled" % txn.id)
                return redirect(url_for('admin_txns'))

            if payment.state == 'paid':
                app.logger.error("Payment has already been paid")
                flash("Payment %s already paid" % payment.id)
                return redirect(url_for('admin_txns'))

            txn.payment = payment
            payment.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 marked as paid" % payment.id)
            return redirect(url_for('admin_txns'))

    return render_template('admin/txn-reconcile.html', txn=txn, payment=payment, form=form)
Exemplo n.º 5
0
    def send(self):
        if not self.recipients:
            raise Exception("No email recipients set.")
        if not self.subject:
            raise Exception("No email subject set.")
        if not self.content:
            raise Exception("No email content set.")

        if app.config["MAIL_ENABLED"]:
            if not app.config["MAIL_SENDER"]:
                raise Exception("No email sender set in config (MAIL_SENDER).")

            with mail.connect() as connection:
                for recipient in self.recipients:
                    msg = Message(self.subject, recipients = [recipient], sender = app.config["MAIL_SENDER"])
                    msg.html = self.content
                    connection.send(msg)
        else:
            print "Sending mail to: "
            for p in self.recipients:
                print "  - " + p
            print "=" * 40
            print "Mail Content:"
            print "=" * 40
            print self.content
            print "=" * 40
Exemplo n.º 6
0
def send_test_email(recipient):
    mail = Mail(app)
    msg = Message("Test Message -- Candidates Emailer app",
                  [recipient],
                  sender="*****@*****.**")
    msg.body = "This is a test message from the Candidates Emailer App"
    mail.send(msg)
Exemplo n.º 7
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.")
Exemplo n.º 8
0
def send_notify(notify_type, data, status=NOT_PROCESSES):
    """
    Отсылает администации уведомления о каких-либо событиях.
    В админку всегда, а на почту.
    """

    # пока поддреживаем только один тип нотификаций (о новых видосах)
    if notify_type != 0:
        raise NotImplemented(u'%s notify does not support yet')

    # notice = app.connection.Notice()
    # notice.update({'notice_type': notify_type, 'data': data, 'status': status})
    # notice.save()

    if not Message or not mail or status != NOT_PROCESSES: return
    
    msg = Message(u'Новое видео', recipients=app.config['ADMINS'])
    msg.html = u"""
    <p>Пользователь %(username)s добавил новое видео по трюку %(trickname)s:</p>
    <a href="%(video_url)s" target="_blank">%(video_url)s</a>
    <p>Отмодерировать это дело можно в админке: <a href="%(admin_url)s" target="_blank">%(admin_url)s</a></a>
    """ % {
        'username'  : app.db.user.find_one({"_id": data["user"]})['nick'],
        'trickname' : data['trickname'],
        'video_url' : data['video_url'],
        'admin_url' : app.config['HOST'] + '/#admin/videos/'
    }
    msg.body = ""

    mail.send(msg)
Exemplo 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"
Exemplo n.º 10
0
def register():
    if get_current_user():
        flash("You are already logged in.")
        return redirect(url_for("index"))

    error = None
    form = ParticipantRegistration()
    if form.validate_on_submit():
        username = form.username.data.strip()
        password = form.password.data
        email = form.email.data
        receive_emails = form.receive_emails.data
        new_participant = Participant(username,
                password,
                email,
                False, # no admin
                False,  # is verified
                receive_emails)

        msg = Message("Welcome to Bacon Game Jam, " + username,
            recipients=[email],
            sender=("bgj","*****@*****.**"))

        msg.html = render_template("emails/verification.html",
                                   recipient=new_participant)
        msg.recipients = [new_participant.email]
        mail.send(msg)

        db.session.add(new_participant)
        db.session.commit()

        flash("Your account has been created, confirm your email to verify.")
        return redirect(url_for('verify_status', username=username))

    return render_template('register.html', form=form, error=error)
Exemplo n.º 11
0
def verify_send():
    if request.method == 'GET':
        return redirect(url_for('index'))

    username = request.form.get('username', "")
    print('username = '******'s account is already validated." % participant.username.capitalize())
        return redirect(url_for('index'))


    msg = Message("Welcome to Bacon Game Jam, " + username,
                  recipients=[participant.email],
                  sender=("bgj","*****@*****.**"))

    msg.html = render_template("emails/verification.html",
                               recipient=participant)

    msg.recipients = [participant.email]
    mail.send(msg)

    flash('Verification has been resent, check your email')
    return redirect(url_for('verify_status', username=username))
Exemplo n.º 12
0
    def post(self):
        if request.json:
            try:
                email = request.json['email']
            except IndexError, e:
                return self.send_400("%s is required" % e)
            try:
                user = User.select(User.q.email==email)[0]
            except:
                return self.send_200({"success": True})
            token = ResetToken(user=user)
            msg = Message("Password Reset",
                          sender=(SITE_NAME, "no-reply@%s" % SITE_URL),
                          recipients=[email])
            message = """
            Hello!
            You (hopefully) have requested a password reset for your account at
            {site_name}. In order to complete this reset, please visit:

            {site_url}/reset/?{enc_token}
            """

            msg.body = message.format(site_name=SITE_NAME, site_url=SITE_URL,
                                      enc_token=quote(token.token))
            g.mail.send(msg)
Exemplo n.º 13
0
def new_jam():
    require_admin()

    form = NewJam()
    if form.validate_on_submit():
        title = form.title.data
        new_slug = get_slug(title)
        if Jam.query.filter_by(slug = new_slug).first():
            flash('A jam with a similar title already exists.')
        else:
            start_time = form.start_time.data
            new_jam = Jam(title, get_current_user(), start_time)
            new_jam.theme = form.theme.data
            new_jam.end_time = start_time + timedelta(hours = form.duration.data)
            new_jam.team_jam = form.team_jam.data
            db.session.add(new_jam)
            db.session.commit()
            flash('New jam added.')

            # Send out mails to all interested users.
            with mail.connect() as conn:
                participants = Participant.query.filter_by(receive_emails=True).all()
                for participant in participants:
                    msg = Message("BaconGameJam: Jam \"%s\" announced" % title)
                    msg.html = render_template("emails/jam_announced.html", jam = new_jam, recipient = participant)
                    msg.recipients = [participant.email]
                    conn.send(msg)
                flash("Email notifications have been sent.")

            #return render_template("emails/jam_announced.html", jam = new_jam, recipient = get_current_user())
            return redirect(new_jam.url())
    return render_template('new_jam.html', form = form)
Exemplo n.º 14
0
def sendmail():
    task = Task.query.order_by(Task.created).first()
    msg = Message("Get things done!",
                  sender=("GTD", "*****@*****.**"),
                  recipients=["*****@*****.**"])
    if not task:
        return
    msg.body = "Hey,\n how about doing '" + task.title + "'?\n"
    msg.body += "It has been waiting for " + task.waited_text()
    if task.postponed_count > 0:
        msg.body += " and you have postponed it "
        msg.body += str(task.postponed_count) + " already"
    msg.body += ".\n"
    msg.body += "Here is some more information:\n"
    if len(task.desc.strip()) > 0:
        msg.body += "Description: " + task.desc_text() + "\n"
    if task.tags != "":
        msg.body += "Tags: " + task.tags + "\n"
    if task.due_text():
        msg.body += "Due: " + task.due_text() + "\n"
    if task.duration_text():
        msg.body += "Duration: " + task.duration_text() + "\n"
    if len(task.text.strip()) > 0:
        msg.body += "Text:\n" + task.text + "\n"
    msg.body += "\nMark task done: " + conf.SITE_URL + "do/" + str(task.id)+"/\n"
    msg.body += "Postpone to later: " + conf.SITE_URL + "postpone/" + str(task.id) + "/"
    mail.send(msg)
Exemplo n.º 15
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))
Exemplo n.º 16
0
def warn_admin(req, mail):
    """
    emails the request information to the admin
    """
    message = {
            "subject": "WARNING: Bot attempted to access email form",
            "sender": "*****@*****.**",
            }
    msg = Message(message['subject'], sender=message['sender'],
            recipients=['*****@*****.**'])

    message['message'] =\
            """
A wannabe cracker (or loose bot) fell for the honeypot. Here are the
details from the req:\n
%(req)s 
            """ % {
                    "req": req,
                }
    msg.body = message['message']
    try:
        mail.send(msg)
        ret = dict(msg=msg,
                succ_code=0)
    except:
        ret = dict(msg=msg,
                succ_code=1)
    return ret
Exemplo n.º 17
0
def send_awaiting_confirm_mail(user):
  
    subject = "We're waiting for your confirmation!!"
    mail_to_be_sent = Message(subject=subject, recipients=[user['Members_Email']])
    confirmation_url = url_for('activate_user', user_id=user['_id'],
_external=True)
    mail_to_be_sent.body = "Dear %s, click here to confirm: %s" %
Exemplo n.º 18
0
 def test_sendto_properly_set(self):
     msg = Message(
         subject="subject", recipients=["*****@*****.**"], cc=["*****@*****.**"], bcc=["*****@*****.**"]
     )
     self.assertEqual(len(msg.send_to), 3)
     msg.add_recipient("*****@*****.**")
     self.assertEqual(len(msg.send_to), 3)
Exemplo n.º 19
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)
Exemplo n.º 20
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'
Exemplo n.º 21
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'
Exemplo n.º 22
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'))
Exemplo n.º 23
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)
Exemplo n.º 24
0
def index():
    msg = Message('Hello',
                  sender='*****@*****.**',
                  recipients=['recipient@recipient_domain.com'])
    msg.body = "This is the email body"
    mail.send(msg)
    return "Sent"
Exemplo n.º 25
0
def confirm(hashid):
    post = JobPost.query.filter_by(hashid=hashid).first()
    form = forms.ConfirmForm()
    if post is None:
        abort(404)
    elif post.status == POSTSTATUS.REJECTED:
        abort(410)
    elif post.status == POSTSTATUS.DRAFT:
        if post.edit_key not in session.get('userkeys', []):
            abort(403)
    else:
        # Any other status: no confirmation required (via this handler)
        return redirect(url_for('jobdetail', hashid=post.hashid), code=302)
    if 'form.id' in request.form and form.validate_on_submit():
        # User has accepted terms of service. Now send email and/or wait for payment
        if not post.email_sent:
            msg = Message(subject="Confirmation of your job listing at the HasGeek Job Board",
                recipients=[post.email])
            msg.body = render_template("confirm_email.md", post=post)
            msg.html = markdown(msg.body)
            mail.send(msg)
            post.email_sent = True
            post.status = POSTSTATUS.PENDING
            db.session.commit()
        session.get('userkeys', []).remove(post.edit_key)
        session.modified = True # Since it won't detect changes to lists
        session.permanent = True
        return render_template('mailsent.html', post=post)
    return render_template('confirm.html', post=post, form=form)
Exemplo n.º 26
0
def resetpassword():
    form = PasswordResetForm()
    if form.validate_on_submit():
        if form.username.data:
          user = Users.query.filter_by(username=form.username.data).first()
        elif form.email.data:
          user = Users.query.filter_by(email=form.email.data).first()
        else:
          flash("Username or password not in system")
        if user:
          if user.email:
            s = URLSafeSerializer('12fe454t')
            key = s.dumps([user.username, user.email])
            msg = Message("Password reset", sender="*****@*****.**", recipients=[user.email])
            msg.html = "<b>testing</b> \
                        #<a href='http://127.0.0.1:5000/passwordreset/" + key + "'>http://127.0.0.1:5000/passwordreset/" + key + "</a>"

            mail.send(msg)
            flash('Email sent to: ' + user.email)
            return redirect(url_for('resetpassword'))
          else:
            flash('No such user')
            return redirect(url_for('resetpassword'))
        else:
            flash('No such user')
            return redirect(url_for('resetpassword'))

    return render_template('general/reset_password.html', form=form)
Exemplo n.º 27
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)
Exemplo n.º 28
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)
Exemplo n.º 29
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'))
Exemplo n.º 30
0
def admin_approve(key):
    if key and key in app.config['ACCESSKEY_APPROVE']:
        p = Participant.query.get(request.form['id'])
        if not p:
            status = "No such user"
        else:
            if 'action.undo' in request.form:
                p.approved = False
                status = 'Undone!'
                # Remove from MailChimp
                if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']:
                    mc = MailChimp(app.config['MAILCHIMP_API_KEY'])
                    try:
                        mc.listUnsubscribe(
                            id = app.config['MAILCHIMP_LIST_ID'],
                            email_address = p.email,
                            send_goodbye = False,
                            send_notify = False,
                            )
                        pass
                    except MailChimpError, e:
                        status = e.msg
                db.session.commit()
            elif 'action.approve' in request.form:
                p.approved = True
                status = "Tada!"
                mailsent = False
                # 1. Make user account and activate it
                user = makeuser(p)
                user.active = True
                # 2. Add to MailChimp
                if MailChimp is not None and app.config['MAILCHIMP_API_KEY'] and app.config['MAILCHIMP_LIST_ID']:
                    mc = MailChimp(app.config['MAILCHIMP_API_KEY'])
                    try:
                        mc.listSubscribe(
                            id = app.config['MAILCHIMP_LIST_ID'],
                            email_address = p.email,
                            merge_vars = {'FULLNAME': p.fullname,
                                          'JOBTITLE': p.jobtitle,
                                          'COMPANY': p.company,
                                          'TWITTER': p.twitter,
                                          'PRIVATEKEY': user.privatekey,
                                          'UID': user.uid},
                            double_optin = False
                            )
                    except MailChimpError, e:
                        status = e.msg
                        if e.code == 214: # Already subscribed
                            mailsent = True
                # 3. Send notice of approval
                if not mailsent:
                    msg = Message(subject="Your registration has been approved",
                                  recipients = [p.email])
                    msg.body = render_template("approve_notice.md", p=p)
                    msg.html = markdown(msg.body)
                    with app.open_resource("static/doctypehtml5.ics") as ics:
                        msg.attach("doctypehtml5.ics", "text/calendar", ics.read())
                    mail.send(msg)
                db.session.commit()
Exemplo n.º 31
0
  def reconcile(self, ref, amount, t):
    if t.type.lower() == 'other' or t.type.upper() == "DIRECTDEP":
      if str(ref).startswith("GOCARDLESS LTD "):
        # ignore gocardless payments
        return
      try:
        payment = self.find_payment(ref)
      except Exception, e:
        if not self.quiet:
          print "Exception matching ref %s paid %.2f: %s" % (repr(ref), amount, e)
        self.badrefs.append([repr(ref), amount])
      else:
        user = payment.user
        #
        # so now we have the ref and an amount
        #

        if payment.state == "paid" and (Decimal(payment.amount_pence) / 100) == amount:
          # all paid up, great lets ignore this one.
          self.alreadypaid += 1
          return

        unpaid = payment.tickets.all()
        total = Decimal(0)
        for t in unpaid:
          if t.paid == False:
            total += Decimal(str(t.type.cost))
          elif not self.quiet:
            if payment.id not in self.overpays:
              print "attempt to pay for paid ticket: %d, user: %s, payment id: %d, paid: %.2f, ref %s" % (t.id, payment.user.name, payment.id, amount, ref)

        if total == 0:
          # nothing owed, so an old payment...
          return
          
        if total != amount and payment.id not in self.overpays:
          print "tried to reconcile payment %s for %s, but amount paid (%.2f) didn't match amount owed (%.2f)" % (ref, user.name, amount, total)
        else:
          # all paid up.
          if not self.quiet:
            print "user %s paid for %d (%.2f) tickets with ref: %s" % (user.name, len(unpaid), amount, ref)
          
          self.paid += 1
          self.tickets_paid += len(unpaid)
          if self.doit:
            for t in unpaid:
              t.paid = True
            payment.state = "paid"
            db.session.commit()
            # send email
            # tickets-paid-email-banktransfer.txt
            msg = Message("Electromagnetic Field ticket purchase update", \
                          sender=app.config.get('TICKETS_EMAIL'), \
                          recipients=[payment.user.email]
                         )
            msg.body = render_template("tickets-paid-email-banktransfer.txt", \
                          user = payment.user, payment=payment
                         )
            mail.send(msg)
Exemplo n.º 32
0
    def test_recipients_properly_initialized(self):

        msg = Message(subject="subject")
        self.assertEqual(msg.recipients, [])

        msg2 = Message(subject="subject")
        msg2.add_recipient("*****@*****.**")
        self.assertEqual(len(msg2.recipients), 1)
Exemplo n.º 33
0
 def send(self):
     msg = Message(
         self.subject.data,
         recipients=[app.config['DEFAULT_MAIL_SENDER']],
         sender=self.from_email.data if self.from_email.data else app.config['DEFAULT_MAIL_SENDER']
     )
     msg.body = "%s" % self.message.data
     mail.send(msg)
Exemplo n.º 34
0
    def test_cc(self):

        msg = Message(
            subject="testing", recipients=["*****@*****.**"], body="testing", cc=["*****@*****.**"]
        )

        response = msg.get_response()
        self.assertIn("Cc: [email protected]", str(response))
Exemplo n.º 35
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'))
Exemplo n.º 36
0
    def test_send_without_body(self):

        msg = Message(subject="testing", recipients=["*****@*****.**"])

        self.assertRaises(AssertionError, self.mail.send, msg)

        msg.html = "<b>test</b>"

        self.mail.send(msg)
Exemplo n.º 37
0
def send_email_verify_link(useremail):
    """
    Mail a verification link to the user.
    """
    msg = Message(subject="Confirm your email address",
        recipients=[useremail.email])
    msg.body = render_template("emailverify.md", useremail=useremail)
    msg.html = markdown(msg.body)
    mail.send(msg)
Exemplo n.º 38
0
def send_event_invitation(event):
    msg = Message(
        'Invitation',
        sender='*****@*****.**',
        recipients=
        event.attendees)
    msg.body = "Hello! We invite you to come to the event in Grid Dynamics company. More information about this event you can get if follow the link." +\
               "http://www.techent.ru:5002" +url_for('event.show_event', event_id = event.id)
    mail_ext.send(msg)
Exemplo n.º 39
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
Exemplo n.º 40
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))
Exemplo n.º 41
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)
Exemplo n.º 42
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'
Exemplo n.º 43
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)
Exemplo n.º 44
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)
Exemplo n.º 45
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)
Exemplo n.º 46
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)
Exemplo n.º 47
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)
Exemplo n.º 48
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)
Exemplo n.º 49
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'))
Exemplo n.º 50
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)
Exemplo n.º 51
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)
Exemplo n.º 52
0
def send_email(to, subject, template):
    msg = Message(
        subject,
        recipients=[to],
        html=template,
        sender=app.config["MAIL_DEFAULT_SENDER"],
    )
    mail.send(msg)
Exemplo n.º 53
0
def forgot_password():
    form = ForgotPasswordForm(request.form)
    if request.method == 'POST' and form.validate():
        if form._user:
            reset = PasswordReset(form.email.data)
            reset.new_token()
            db.session.add(reset)
            db.session.commit()
            msg = Message("EMF password reset",
                          sender=app.config['TICKETS_EMAIL'],
                          recipients=[form.email.data])
            msg.body = render_template("reset-password-email.txt",
                                       user=form._user,
                                       reset=reset)
            mail.send(msg)

        return redirect(url_for('reset_password', email=form.email.data))
    return render_template("forgot-password.html", form=form)
Exemplo n.º 54
0
def contact():
    form = ContactForm()
    if request.method == 'POST':
        if form.validate() == False:
            flash("all Field are required.")
            return render_template('form.html', form=form)
        else:
            msg = Message(form.subject.data,
                          sender='*****@*****.**',
                          recipients=[os.environ.get('DB_USER')])
            msg.body = """
            From: {} <{}>
            {}
            """.format(form.name.data, form.email.data, form.message.data)
            mail.send(msg)

    elif request.method == 'GET':
        return render_template('form.html', form=form)
Exemplo n.º 55
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('/')
Exemplo n.º 56
0
def stripe_payment_paid(payment):
    if payment.state == 'paid':
        logger.info('Payment is already paid, ignoring')
        return

    if payment.state != 'charged':
        logger.error('Current payment state is %s (should be charged)', payment.state)
        raise StripeUpdateConflict()

    logger.info('Setting payment %s to paid', payment.id)
    payment.paid()
    db.session.commit()

    msg = Message('Your EMF ticket payment has been confirmed',
        sender=app.config.get('TICKETS_EMAIL'),
        recipients=[payment.user.email])
    msg.body = render_template('tickets-paid-email-stripe.txt',
        user=payment.user, payment=payment)
    mail.send(msg)
Exemplo n.º 57
0
def stripe_payment_refunded(payment):
    if payment.state == 'cancelled':
        logger.info('Payment is already cancelled, ignoring')
        return

    logger.info('Setting payment %s to cancelled', payment.id)
    payment.cancel()
    db.session.commit()

    if not app.config.get('TICKETS_NOTICE_EMAIL'):
        app.logger.warning('No tickets notice email configured, not sending')
        return

    msg = Message('An EMF ticket payment has been refunded',
        sender=app.config.get('TICKETS_EMAIL'),
        recipients=[app.config.get('TICKETS_NOTICE_EMAIL')[1]])
    msg.body = render_template('tickets-refunded-email-stripe.txt',
        user=payment.user, payment=payment)
    mail.send(msg)
Exemplo n.º 58
0
    def send_activation_email(self):
        """Send the e-mail that allows a user to activate their account."""
        if not self.reg_code:
            self._gen_reg_code()
            db.session.commit()

        msg = Message("Account Activation", recipients=[self.email])

        print self.reg_code
        activate_url = url_for('frontend.activate',
                               user_id=self.id,
                               reg_code=self.reg_code,
                               _external=True)
        msg.html = render_template('email_activate.html',
                                   user=self,
                                   activate_url=activate_url)
        msg.body = render_template('email_activate.txt',
                                   user=self,
                                   activate_url=activate_url)
        mail.send(msg)
Exemplo n.º 59
0
def admin_txn_reconcile(txn_id, payment_id):
    txn = BankTransaction.query.get_or_404(txn_id)
    payment = BankPayment.query.get_or_404(payment_id)

    form = ManualReconcilePaymentForm()
    if form.validate_on_submit():
        if form.reconcile.data:
            app.logger.info(
                "%s manually reconciling against payment %s (%s) by %s",
                current_user.name, payment.id, payment.bankref,
                payment.user.email)

            if txn.payment:
                app.logger.error("Transaction already reconciled")
                flash("Transaction %s already reconciled" % txn.id)
                return redirect(url_for('admin_txns'))

            if payment.state == 'paid':
                app.logger.error("Payment has already been paid")
                flash("Payment %s already paid" % payment.id)
                return redirect(url_for('admin_txns'))

            txn.payment = payment
            payment.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 marked as paid" % payment.id)
            return redirect(url_for('admin_txns'))

    return render_template('admin/txn-reconcile.html',
                           txn=txn,
                           payment=payment,
                           form=form)