Пример #1
0
def route_paypal():
    
    verify_string = '&'.join(('%s=%s' % (param, value) for param, value in request.form.iteritems()))
    verify_string = verify_string + '&%s=%s' % ('cmd', '_notify-validate')
    
    status = urlopen('https://www.paypal.com/cgi-bin/webscr', data=verify_string).read()
    
    if status == 'VERIFIED':
        
        id = ''.join([chr(i) for i in [random.randrange(97, 122) for _ in xrange(25)]])
        
        keys = os.path.join(os.path.split(__file__)[0], 'purchases')
        with open(keys, 'a') as keyfile:
            keyfile.write(datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')+' '+id+'\n')
        
        msg = Message("Build Your Own Lisp - eBook Download",
            sender="*****@*****.**",
            recipients=[request.form.get('payer_email')],
            
            body="Hello,\n"
                 "\n"
                 "Many thanks for purchasing the eBook for Build Your Own Lisp. "
                 "I really appreciate your contribution and support!\n"
                 "\n"
                 "Please follow these download links to download "
                 "the ebook in each of the different formats.\n"
                 "\n"
                 "http://buildyourownlisp.com/download/%s/BuildYourOwnLisp.epub\n"
                 "http://buildyourownlisp.com/download/%s/BuildYourOwnLisp.mobi\n"
                 "http://buildyourownlisp.com/download/%s/BuildYourOwnLisp.pdf\n"
                 "\n"
                 "If you need it in a different format to these, or "
                 "need any help using these files don't hesitate to "
                 "get in contact.\n"
                 "\n"
                 "This e-mail should be considered a proof of purchase. "
                 "These links will expire in 60 days, so if you want an "
                 "updated version of the eBook please contact this address, "
                 "with a copy of this e-mail. I will supply you with new "
                 "links to an updated version. If you have any other "
                 "problems or questions, please contact this address "
                 "and I will try to resolve them as soon as possible.\n"
                 "\n"
                 "Thanks again, and I hope you enjoy the book!\n"
                 "\n"
                 "* Dan\n" % (id, id, id))
        
        mail.send(msg)
        
    else:
        app.logger.error('Paypal IPN string %s did not validate' % verify_string)

    return jsonify({'status': 'complete'})
Пример #2
0
def send_notification(message):
    logger.info(u"sending notification mail: %s" % message)
    msg = Message("plexivity notification",
                  recipients=[config.MAIL_RECIPIENT],
                  sender=config.MAIL_FROM)
    msg.body = message
    if mail.send(msg):
        logger.info(u"Notification mail successfully send")
        return True
    else:
        logger.error(u"unable to send mail notification")
        return False
Пример #3
0
def create_project():
    form = ProjectForm()
    if request.method == "GET" and 'project_id' in request.values:
        form.name.data = request.values['project_id']

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

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

            # send reminder email
            g.project = project

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

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

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

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

    return render_template("create_project.html", form=form)
Пример #4
0
def send(recipient, subject, body):
    '''
    Send a mail to a recipient. The body is usually a rendered HTML template.
    The sender's credentials has been configured in the config.py file.
    '''
    return
    sender = app.config['ADMINS'][0]
    message = Message(subject, sender=sender, recipients=[recipient])
    message.html = body
    # Create a new thread
    thr = Thread(target=send_async, args=[app, message])
    thr.start()
Пример #5
0
def forgotusername():
    form = ForgotUserForm()
    if form.validate_on_submit():
        user = form.user
        msg = Message('Password Reset', sender = ADMINS[0], recipients = [user.email])
        msg.body = "Your username is: " + user.nickname + " (Remember case matters)"
	mail.send(msg)
        flash('Username Email Sent')
        return redirect(url_for('login'))
    return render_template('forgotUsername.html',
        title = 'Forgot Username',
        form = form)
Пример #6
0
def order():

    form = OrderForm()

    # render template if page load 
    if request.method == 'GET':
        return render_template('order.html', form=form)

    # if user is submitting an order 
    if 'order' in request.form:
        print "going here"
        # if user submitted every field 
        if form.validate_on_submit():

            orders = Order.query.all()
            num = len(orders)
            # possibly cbeck user hasnt submitted an item 
            # possibly parse database making sure item is in stock
            order = Order(id=num+1, email=g.user.email, dormHall=g.user.dormHall, dormNum=g.user.dormNum, time=form.time.data, item1=form.item1.data, item2=form.item2.data, item3=form.item3.data, item4=form.item4.data, item5=form.item5.data, item6=form.item6.data, item7=form.item7.data, date=datetime.now()) 
            db.session.add(order)
            db.session.commit()

            msg = Message('resqU Order Confirmation  ', sender=ADMINS[0], recipients=[g.user.email])
            body = 'Hey! We just got note of your order. This email is to confirm your order, \
            and to request payment. Your order is as follows: {}, {}, {}, {}, {}, {}. It will be delivered to {} {} at {}.\
              Your total comes out to $21.96. Once you are on your mobile phone, clicking the link below will launch your Venmo app with all payment information \
              preloaded. If you are on a desktop, switch to your mobile device. You are then one click away from payment! You will then get a confirmation email. Thanks for using ResqU!'.format(order.item1, order.item2, order.item3, order.item4, order.item5, order.item6, order.dormNum, order.dormHall, order.time)
            link = "venmo://paycharge?txt=pay&amount={}&note=Your Resqu Delivery Order&recipients=PrincetonResqu".format("21.96")
            msg.html = '<p> {} </p> <a href="{}"> Click here to pay! </a> <br> <br> <br> <p> If there is an error in your order, \
            simply go back to the order page, click delete your order, and then place it again.'.format(body, link)

            mail.send(msg)
            return redirect(url_for('thankyou'))
        else: 
            return render_template('order.html', form=form)

    # if user wants to cancel their order 
    elif 'cancelorder' in request.form:
        user = g.user 

        # final all orders by this user 
        orders = user.orders.all()

        # delete their most recent order 
        db.session.delete(orders[len(orders)-1])
        db.session.commit()
        flash("order canceled successfully")

        form = OrderForm()
        return render_template('order.html', form=form)

    print "just returning here"
    return render_template('order.html', form=form)
Пример #7
0
    def sender_email(traceback):
        from flask.ext.mail import Mail, Message

        mail = Mail(app)
        senders = app.config.get("SENDERS", [])
        if not senders:
            return
        msg = Message(subject=u"%s %s时遇到异常" % (request.method, request.url),
                      html=traceback.render_summary(),
                      sender="*****@*****.**",
                      recipients=senders)
        mail.send(msg)
Пример #8
0
def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                  sender=app.config['ADMIN_EMAIL'],
                  recipients=[to])
    print("New Message:\n subject:%s recipients=%s\n" %
          (app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject, to))
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr
Пример #9
0
def confirm_mail(email):
    """
    Send the awaiting for confirmation mail to the user.
    """
    print email
    subject = "We're waiting for your confirmation!!"
    message = Message(subject=subject, recipients=[email])
    #confirmation_url = url_for('activate_user', user_id=email, _external=True)
    #print confirmation_url
    #message.body = "Dear %s, Please click here to complete your registration process %s" %(email, confirmation_url)
    from runserver import mail
    mail.send(message)
Пример #10
0
def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
    app.config['FLASKY_MAIL_SENDER'] = 'Flask Admin <*****@*****.**>'
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
        sender=app.config['FLASKY_MAIL_SENDER'],recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
 
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr
Пример #11
0
def user_create():

    if 'username' in session:
        system = System()
        login_user = system.getUser(session.get('username'))
        error = None

        if request.method == 'POST':

            firstname = request.form['firstname']
            lastname = request.form['lastname']
            email_cust = request.form['email_cust'] or None
            origin = request.form['number']

            if len(firstname) < 1:
                abort(400, 'Enter firstname')
            elif len(lastname) < 1:
                abort(400, 'Enter lastname')
            elif len(origin) < 1:
                abort(400, 'Enter phone number')

            email = session.get('username')
            response = User(email).createCustomer(firstname, lastname,
                                                  email_cust, origin)
            if response == 0:

                error = firstname + ' ' + lastname + ' is added Successfully'
                flash("Customer added Successfully")
                if email_cust is not None:

                    msg = Message(
                        "Registration successfull, your registration details ",
                        sender=app.config["DEFAULT_MAIL_SENDER"],
                        recipients=[email_cust])
                    msg.html = render_template("reg-email.html",
                                               firstname=firstname,
                                               lastname=lastname,
                                               email=email_cust)
                    thr = Thread(target=send_async_email_test, args=[app, msg])
                    thr.start()
                return render_template('user-create.html',
                                       login_user=login_user,
                                       error=error)

            if response == 1:

                error = origin + ' already exist, so no record created'
                return render_template('user-create.html',
                                       login_user=login_user,
                                       error=error)

        return render_template('user-create.html', login_user=login_user)
    return redirect('/')
Пример #12
0
def notify_mail(alert, html, new_state, app):
    recipients = [s.email for s in alert.subscribers()]
    logger.debug("Notifying: %s", recipients)
    try:
        with app.app_context():
            message = Message(recipients=recipients,
                              subject="[{1}] {0}".format(
                                  alert.name, new_state.upper()),
                              html=html)
            mail.send(message)
    except:
        logger.exception("mail send ERROR.")
Пример #13
0
def notify(name, email, btc):
    """Notifies the user at the provided email, using the body of the message determined by the comparing function"""
    print("Creating a message object...")
    print(email)
    msg = Message('Bitcoin Price Alert!',
                  sender='*****@*****.**',
                  recipients=[email])
    msg.body = "Hello, %s. The price of bitcoin has just passed $%s. \nWe wish you happy trading and hope you have a great day! \nSincerely, \nCoinworth team. " % (
        name, btc)
    print("Passing to the mailbox...")
    mailbox.send(msg)
    print('Sent!')
Пример #14
0
def send_email(subject, recipients, html=None, text=None):
    with app.app_context(), mail.connect() as conn:
        for recipient in recipients:
            msg = Message(subject,
                          sender=app.config['EMAIL_FROM'],
                          recipients=[
                              recipient,
                          ])
            msg.html = html
            msg.text = text

            conn.send(msg)
Пример #15
0
def sendEmail(From, To, Subject, Body, Html, Attachments):
    '''To:must be a list'''
    msg = Message(Subject, sender = From, recipients = To)
    msg.body = Body
    msg.html = Html
    for f in Attachments:
        with app.open_resource(f) as fp:
            msg.attach(filename=os.path.basename(f), data=fp.read(),
                               content_type='application/octet-stream')
    mail = Mail(app)
    with app.app_context():
        mail.send(msg)
Пример #16
0
def index():
    msg = Message('这是题目',
                  sender='*****@*****.**',
                  recipients=['*****@*****.**'])
    msg.body = '文本 body'
    msg.html = '<b>这是HTML测试</b> body'
    #mail.send(msg)

    thread = Thread(target=send_async_email, args=[app, msg])
    thread.start()

    return '<h1>邮件发送成功</h1>'
Пример #17
0
def send_mail(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(subject,
                  sender=os.environ.get('MAIL_USERNAME'),
                  recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)

    thr = Thread(target=send_mail_async, args=[app, msg])
    thr.start()

    return thr
Пример #18
0
def order_pizza_for_everybody():
    """
    Orders pizza for every user and sedns him an e-mail.
    """
    new_event = Pizza()
    new_event.who_created = current_user.username
    new_event.pizza_ordering_is_allowed = True
    new_event.users_already_ordered = ""
    db.session.add(new_event)
    db.session.commit()
    new_event = Pizza.query.all()[-1]
    new_event_id = new_event.id
    event_url = server_url() + url_for(
        "pizza_time_view",
        happening=new_event_id,
    )
    stop_url = server_url() + url_for(
        "pizza_time_stop",
        happening=new_event_id,
    )
    users = User.query.filter(User.active).all()
    emails = [user.email for user in users]
    text = 'You succesfully orderd pizza for all You can check who wants' \
           ' what here:\n{}\n to finish the pizza orgy click here\n{}\n ' \
           'than order pizza!'.format(event_url, stop_url)
    msg = Message(
        'Lunch app PIZZA TIME',
        recipients=emails,
    )
    msg.body = '{} ordered pizza for everyone ! \n order it here:\n\n' \
               '{}\n\n and thank him!'.format(current_user.username, event_url)
    mail.send(msg)
    msg = Message(
        'Lunch app PIZZA TIME',
        recipients=[current_user.username],
    )
    msg.body = text
    mail.send(msg)
    flash(text)
    return redirect(url_for("pizza_time_view", happening=new_event_id))
Пример #19
0
def send_ready_for_review(build_id, release_name, release_number):
    """Sends an email indicating that the release is ready for review."""
    build = models.Build.query.get(build_id)

    if not build.send_email:
        logging.debug(
            'Not sending ready for review email because build does not have '
            'email enabled. build_id=%r', build.id)
        return

    ops = operations.BuildOps(build_id)
    release, run_list, stats_dict, _ = ops.get_release(release_name,
                                                       release_number)

    if not run_list:
        logging.debug(
            'Not sending ready for review email because there are '
            ' no runs. build_id=%r, release_name=%r, release_number=%d',
            build.id, release.name, release.number)
        return

    title = '%s: %s - Ready for review' % (build.name, release.name)

    email_body = render_template('email_ready_for_review.html',
                                 build=build,
                                 release=release,
                                 run_list=run_list,
                                 stats_dict=stats_dict)

    recipients = []
    if build.email_alias:
        recipients.append(build.email_alias)
    else:
        for user in build.owners:
            recipients.append(user.email_address)

    if not recipients:
        logging.debug(
            'Not sending ready for review email because there are no '
            'recipients. build_id=%r, release_name=%r, release_number=%d',
            build.id, release.name, release.number)
        return

    message = Message(title, recipients=recipients)
    message.html = email_body

    logging.info(
        'Sending ready for review email for build_id=%r, '
        'release_name=%r, release_number=%d to %r', build.id, release.name,
        release.number, recipients)

    return render_or_send(send_ready_for_review, message)
def contact():
    form = ContactForm()

    #If the user clicks the submit button on the form
    if request.method == 'POST':
        #If the form has not had all their fields entered correctly e.g. missing a username
        if form.validate() == False:
            #Flash an error message reinforcing the fact that all fields are required
            flash('All fields are required.')
            #Pull these error messages from the contact.html page, which will then pull this from the forms.py
            return render_template('contact.html', form=form)
            #Otherwise
        else:
            #Execute order 66, I'm joking, submit the request and send the e-mail with the following crednetials
            msg = Message(subject='CPS Access Request',
                          sender='*****@*****.**',
                          recipients=['*****@*****.**', form.email.data])
            #Declare the message body here. This uses three sets of quotations to give multiple lines of e-mail content. The %s calls each value from the contact.html page using flask and prints them in the order specified below in brackets.
            msg.html = """\
	<html>
 	 <head></head>
  		<body>
    	<h2>You Have A New CPS Request</h2>
    	Hi 24/7, please action the following request for CPS access.<br>
      ------------------------------------------------------------<br>
      The Users name: %s<br>
      The Username: %s<br>
      Request From: %s <br>
      Email: %s<br>
       		How are you?<br>
       		Have an issue with this request? Send us an e-mail on: <a href="http://www.python.org">link</a> you wanted. %s
   		 </p>
  		</body>
		</html>
		
      """ % (form.usersname.data, form.username.data, form.name.data,
             form.email.data, form.message.data)
            #Pass in the msg value and send it off
            mail.send(msg)

            #Return the values from contact.html and verify this process has been completed.
            return render_template('contact.html',
                                   success=True,
                                   usersname=form.usersname.data,
                                   username=form.username.data,
                                   name=form.name.data,
                                   email=form.email.data,
                                   message=form.message.data)
    #ElseIf this has worked
    elif request.method == 'GET':
        #Return the contact.html page for the user to see their confirmation page
        return render_template('contact.html', form=form)
Пример #21
0
def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()

    msg = Message(subject, sender=app.config['MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)

    mail.send(msg)

    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()

    return thr
Пример #22
0
def reminder():
    now = datetime.datetime.now()
    lounges = Lounge.query.filter(Lounge.date_time > now).all()

    for lounge in lounges:
        interval = lounge.date_time - now
        if interval < datetime.timedelta(days=4):
            message = Message(
                "Reminder to remind your loungers: lounge on {0}".format(
                    lounge.formatted_local_date_time),
                recipients=[lounge.host.email])
            message.body = render_template('remind_host.mail', lounge=lounge)
            mail.send(message)
Пример #23
0
def user_forgot_route():
    username = request.form.get("username")
    cur = mysql.connection.cursor()
    cur.execute('SELECT email FROM User WHERE username="******"'%username)
    email = cur.fetchone()
    if email==None:
        flash("Account not exist!", "error")
        return render_template("login.html", type="login")
    token = hashlib.md5(username).hexdigest()
    msg = Message("Siemens SPDS: Reset your password!",recipients=[email[0]],html=render_template("email_forgot.html",username=username,token=token,host=request.host))
    mail.send(msg)
    flash("An email was sent to the address you provided during registration process. Please follow the link to reset password!", "success")
    return render_template("login.html", type="login")
Пример #24
0
def send_mail(to, subject, template, **kw):
    """to: email recesiver
        subject: email subject
        template: without endpoint
    """
    app = current_app._get_current_object()
    msg = Message(app.config['FLASK_MAIL_SUBJECT_PREFIX']+subject, sender=app.config['FLASK_MAIL_SENDER']
                  , recipients=[to])
    msg.body = render_template(template+'.txt', **kw)
    msg.html = render_template(template+".html", **kw)
    thr = Thread(target=send_mail_async, args=[app, msg])
    thr.start()
    return thr
Пример #25
0
def remind(self, pk):
    reminder = Reminder.query.get(pk)
    msg = MIMEText(reminder.text)

    msg = Message("Your reminder",
                  sender="*****@*****.**",
                  recipients=[reminder.email])
    msg.body = reminder.text

    try:
        mail.send(msg)
    except Exception, e:
        self.retry(exc=e)
Пример #26
0
def send_mail(title, content, sender, recipient):
    """Sends an email using Flask-Mail extension via GMail SMTP server

    Mail configuration is in app config file.

    Raises BadHeaderError (and some others perhaps)
    """
    message = Message(title,
                      sender=sender,
                      recipients=[recipient],
                      charset='UTF8')
    message.html = content
    mail.send(message)
Пример #27
0
def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    # 永远尝试选择一个合适的发送端。如果你有一个发出信号的类,把 self 作为发送端。如果你从一个随机的函数发出信号,把 current_app._get_current_object() 作为发送端。
    # 永远不要向信号传递 current_app 作为发送端,使用 current_app._get_current_object() 作为替代。这样的原因是, current_app 是一个代理,而不是真正的应用对象。
    msg = Message(app.config['FLASK_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                  sender=app.config['FLASK_MAIL_SENDER'],
                  recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)

    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr
Пример #28
0
def send_mail(to, subject, html, text):
    from redash.wsgi import app

    try:
        with app.app_context():
            message = Message(recipients=to,
                              subject=subject,
                              html=html,
                              body=text)

            mail.send(message)
    except Exception:
        logger.exception('Failed sending message: %s', message.subject)
Пример #29
0
    def send(self):
        msg = Message(self.subject,
                      recipients=list(self.recipients),
                      body=self.text_body,
                      html=self.html_body)
        if self.attachments:
            for file_id in self.attachments:
                file_instance = FileModel.find_one(id=file_id)
                msg.attach(file_instance.name, file_instance.image.contentType,
                           file_instance.image.read())

        mail.send(msg)
        self.delete()
Пример #30
0
def send_email(to, subject, template, **kwargs):
    print '#' * 15, 'send_email start'
    app = current_app._get_current_object()
    print '#' * 15, 'send_email _get_current_object'
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'],
                  recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)

    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr