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)
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'))
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)
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)
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)
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'
def index(): msg = Message('Hello', sender='*****@*****.**', recipients=['recipient@recipient_domain.com']) msg.body = "This is the email body" mail.send(msg) return "Sent"
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"
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)
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" %
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)
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'))
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)
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)
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))
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))
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'
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)
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.")
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)
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)
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)
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
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()
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)
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)
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.")
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)
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'))
def index(): msg = Message( 'Hello', sender='*****@*****.**', recipients= ['recipient@recipient_domain.com']) msg.body = "This is the email body" mail.send(msg) return "Sent"
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)
def mailer(): msg = Message("client test") msg.add_recipient("*****@*****.**") msg.body = "Yo, shoot me a message" base_app.mailer.send(msg) return default_view()
def send(pic, to=app.config.get('ME')): msg = Message( 'Hello', sender=app.config.get('MAIL_USERNAME'), recipients=to) msg.body = "This is the email body" with app.open_resource(os.path.join(directory, pic)) as fp: msg.attach(pic, "image/jpg", fp.read()) mail.send(msg) return '<script type="text/javascript">window.close();</script>'
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
def 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. 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}, double_optin = False ) except MailChimpError, e: status = e.msg if e.code == 214: # Already subscribed mailsent = True # 2. 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) mail.send(msg) db.session.commit()
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))
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)
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.get('TICKETS_EMAIL'), recipients=[user.email] ) user.create_receipt() msg.body = render_template("ticket.txt", user = user) print "Sending to", user.email, "..." print msg.body
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'
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)
def sendmail(mailtype, data=None): ''' Mail dispatcher :param mailtype: can be 'error', 'rating' or 'mailreminder' :param data: data for mail-forming, depends on mailtype ''' if data: if mailtype is 'mailreminder': msg = Message('[einfachJabber.de] Jabber-Konto Registrierung') msg.body = u''' einfachJabber.de Du hast eben über http://einfachjabber.de einen neuen Jabber-Account registriert. Die Benutzerdaten dazu lauten: Benutzername: %s Passwort: %s Auf http://einfachjabber.de findest du Anleitungen für verschiedene Client-Programme. ''' % (data[1], data[2]) msg.recipients = [data[0]] if mailtype is 'rating': msg = Message('[einfachJabber.de] Tutorialbewertung') msg.body = u''' einfachJabber.de Tutorialbewertung Bewertung: %s Vorschlag: %s Tutorial: %s ''' % (data[0], data[1], data[2]) msg.recipients = ['*****@*****.**'] mail.send(msg)
def save(data): data["activities"] = makeActivities(data) # print json.dumps(data,default=dateJSONhandler) # pprint.pprint(data) # return src = data["meta"]["source"] res = db.dossiers.find_one({"meta.source": src}) or {} d = diff( dict([(k, v) for k, v in data.items() if not k in ["_id", "meta", "changes"]]), dict([(k, v) for k, v in res.items() if not k in ["_id", "meta", "changes"]]), ) if d: now = datetime.datetime.utcnow().replace(microsecond=0).isoformat() if not res: print("\tadding %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: print("\tupdating %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"] # print >> sys.stderr, (d) m = db.notifications.find({"dossiers": data["procedure"]["reference"]}, ["active_emails"]) for g in m: if len(g["active_emails"]) == 0: continue msg = Message( "Parltrack Notification for %s" % data["procedure"]["reference"], sender="*****@*****.**", bcc=g["active_emails"], ) # msg.body = "Parltrack has detected a change in %s %s on OEIL.\nfollow this URL: %s to see the dossier\n\nchanges below\n%s" % (data['procedure']['reference'], data['procedure']['title'],'%s/dossier/%s' % (ROOT_URL,data['procedure']['reference']), json.dumps(d,indent=1,default=dateJSONhandler)) msg.body = "Parltrack has detected a change in %s %s on OEIL.\nfollow this URL: %s to see the dossier\n" % ( data["procedure"]["reference"], data["procedure"]["title"], "%s/dossier/%s" % (ROOT_URL, data["procedure"]["reference"]), ) mail.send(msg) data["changes"] = res.get("changes", {}) data["changes"][now] = d db.dossiers.save(data) return stats
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.get('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)
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)
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)
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)
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)
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)
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)
def gocardless_bill_paid(resource, action, data): for bill in data['bills']: gcid = bill['id'] try: payment = GoCardlessPayment.query.filter_by(gcid=gcid).one() except NoResultFound: logger.warn("Payment for bill %s not found, skipping", gcid) continue logger.info("Received paid action for gcid %s, payment %s", gcid, payment.id) if bill['status'] != 'paid': logger.warn("Bill status is %s (should be paid), failing", bill['status']) abort(409) if payment.state == 'paid': logger.info('Payment is already paid, skipping') continue if payment.state != 'inprogress': logger.warning( "Current payment state is %s (should be inprogress), failing", payment.state) abort(409) 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['TICKETS_EMAIL'], recipients=[payment.user.email]) msg.body = render_template("tickets-paid-email-gocardless.txt", user=payment.user, payment=payment) mail.send(msg) return ('', 200)
def transfer_start(): payment = add_payment_and_tickets(BankPayment) if not payment: logging.warn('Unable to add payment and tickets to database') flash( 'Your session information has been lost. Please try ordering again.' ) return redirect(url_for('tickets')) logger.info("Created bank payment %s (%s)", payment.id, payment.bankref) payment.state = "inprogress" db.session.commit() msg = Message("Your EMF ticket purchase", sender=app.config['TICKETS_EMAIL'], recipients=[current_user.email]) msg.body = render_template("tickets-purchased-email-banktransfer.txt", user=current_user, payment=payment) mail.send(msg) return redirect(url_for('transfer_waiting', payment_id=payment.id))
def stripe_charge_updated(type, charge_data): payment = get_payment_or_abort(charge_data['id']) logging.info('Received %s message for charge %s, payment %s', type, charge_data['id'], payment.id) charge = stripe.Charge.retrieve(charge_data['id']) if not charge.paid: logger.error('Charge object is not paid') abort(501) if charge.refunded: logger.error('Charge object has been refunded') abort(501) if payment.state == 'paid': logger.info('Payment is already paid, ignoring') return ('', 200) if payment.state != 'charged': logger.error('Current payment state is %s (should be charged)', payment.state) abort(409) logger.info('Setting payment %s to paid', payment.id) for t in payment.tickets.all(): t.paid = True payment.state = '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) return ('', 200)
def register(): form = RegistrationForm() if form.validate_on_submit(): profile = RegistrationProfile() profile.first_name = unicode(form.first_name.data) profile.last_name = unicode(form.last_name.data) profile.email = unicode(form.email.data) profile.password = unicode(generate_password_hash(form.password.data)) profile.ip_address = unicode(request.remote_addr) profile.dob = form.dob.data profile.identifier_id= unicode(form.identifier_id.data) profile.country = unicode(form.country.data) profile.zipcode = unicode(form.zipcode.data) profile.city = unicode(form.city.data) profile.street = unicode(form.street.data) profile.username = profile.email db_session.add(profile) db_session.commit() # TODO, send email! with mail.record_messages() as outbox: msg = Message("IALT Registration", sender=("IALT Registration", "*****@*****.**"), recipients=[profile.email]) msg.body = "Please activate your Profile under {0}".format(profile.activation_key) mail.send(msg) assert len(outbox) == 1 assert outbox[0].subject == "IALT Registration" assert profile.email in outbox[0].recipients flash("Registration completed. We've sent you an E-Mail with your activation key.") print profile.activation_key return redirect(url_for('index')) return render_template("auth/register.html", form=form)
t.paid = True else: payment.state = 'charged' for t in payment.tickets: t.expires = datetime.utcnow() + timedelta(days=app.config['EXPIRY_DAYS_STRIPE']) logger.info("Set expiry for ticket %s", t.id) db.session.commit() logger.info('Payment %s completed OK (state %s)', payment.id, payment.state) msg = Message("Your EMF ticket purchase", sender=app.config.get('TICKETS_EMAIL'), recipients=[payment.user.email]) msg.body = render_template("tickets-purchased-email-stripe.txt", user=payment.user, payment=payment) mail.send(msg) return redirect(url_for('stripe_waiting', payment_id=payment.id)) class StripeAuthorizeForm(Form): token = HiddenField('Stripe token') forward = SubmitField('Continue') @app.route("/pay/stripe/<int:payment_id>/capture", methods=['GET', 'POST']) @login_required def stripe_capture(payment_id): payment = get_user_payment_or_abort( payment_id, 'stripe', valid_states=['new'],
def run(self, doit): txns = BankTransaction.query.filter_by(payment_id=None, suppressed=False) paid = 0 failed = 0 for txn in txns: if txn.type.lower() not in ('other', 'directdep'): raise ValueError('Unexpected transaction type for %s: %s', txn.id, txn.type) if txn.payee.startswith("GOCARDLESS "): app.logger.info('Suppressing GoCardless transfer %s', txn.id) if doit: txn.suppressed = True db.session.commit() continue if txn.payee.startswith("STRIPE PAYMENTS EU "): app.logger.info('Suppressing Stripe transfer %s', txn.id) if doit: txn.suppressed = True db.session.commit() continue app.logger.info("Processing txn %s: %s", txn.id, txn.payee) payment = txn.match_payment() if not payment: app.logger.warn("Could not match payee, skipping") failed += 1 continue app.logger.info("Matched to payment %s by %s for %s %s", payment.id, payment.user.name, payment.amount, payment.currency) if txn.amount != payment.amount: app.logger.warn( "Transaction amount %s doesn't match %s, skipping", txn.amount, payment.amount) failed += 1 continue if txn.account.currency != payment.currency: app.logger.warn( "Transaction currency %s doesn't match %s, skipping", txn.account.currency, payment.currency) failed += 1 continue if payment.state == 'paid': app.logger.error("Payment %s has already been paid", payment.id) failed += 1 continue if doit: 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) app.logger.info("Payment reconciled") paid += 1 app.logger.info('Reconciliation complete: %s paid, %s failed', paid, failed)
# We need to make sure of a 5 working days grace # for gocardless payments, so push the ticket expiry forwards t.expires = datetime.utcnow() + timedelta( days=app.config['EXPIRY_DAYS_GOCARDLESS']) logger.info("Reset expiry for ticket %s", t.id) db.session.commit() logger.info("Payment %s completed OK", payment.id) # should we send the resource_uri in the bill email? msg = Message("Your EMF ticket purchase", sender=app.config['TICKETS_EMAIL'], recipients=[payment.user.email]) msg.body = render_template("tickets-purchased-email-gocardless.txt", user=payment.user, payment=payment) mail.send(msg) return redirect(url_for('gocardless_waiting', payment_id=payment.id)) class GoCardlessCancelForm(Form): yes = SubmitField('Cancel payment') @app.route("/pay/gocardless/<int:payment_id>/cancel", methods=['GET', 'POST']) @login_required def gocardless_cancel(payment_id): payment = get_user_payment_or_abort( payment_id,
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_int) / 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.get_price(payment.currency))) 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['TICKETS_EMAIL'], recipients=[payment.user.email]) msg.body = render_template( "tickets-paid-email-banktransfer.txt", user=payment.user, payment=payment) mail.send(msg)
def gocardless_webhook(): """ handle the gocardless webhook / callback callback: https://gocardless.com/docs/web_hooks_guide#response we mostly want 'bill' GoCardless limits the webhook to 5 secs. this should run async... """ json_data = simplejson.loads(request.data) data = json_data['payload'] if not gocardless.client.validate_webhook(data): logger.error("Unable to validate gocardless webhook") return ('', 403) logger.info("Webhook resource type %s action %s", data.get('resource_type'), data.get('action')) if data['resource_type'] != 'bill': logger.warn('Resource type is not bill') return ('', 501) if data['action'] not in ['paid', 'withdrawn', 'failed', 'created']: logger.warn('Unknown action') return ('', 501) # action can be: # # paid -> money taken from the customers account, at this point we concider the ticket paid. # created -> for subscriptions # failed -> customer is broke # withdrawn -> we actually get the money for bill in data['bills']: gcid = bill['id'] try: payment = GoCardlessPayment.query.filter_by(gcid=gcid).one() except NoResultFound: logger.warn('Payment %s not found, ignoring', gcid) continue logger.info("Processing payment %s (%s) for user %s", payment.id, gcid, payment.user.id) if data['action'] == 'paid': if payment.state != "inprogress": logger.warning("Old payment state was %s, not 'inprogress'", payment.state) for t in payment.tickets.all(): t.paid = True payment.state = "paid" db.session.commit() msg = Message("Your EMF ticket payment has been confirmed", sender=app.config['TICKETS_EMAIL'], recipients=[payment.user.email]) msg.body = render_template("tickets-paid-email-gocardless.txt", user=payment.user, payment=payment) mail.send(msg) else: logger.debug('Payment: %s', bill) return ('', 200)