Exemple #1
0
def mail_message(subject, template, to, **kwargs):
    sender_email = '*****@*****.**'

    email = Message(subject, sender=sender_email, recipients=[to])
    email.body = render_template(template + ".txt", **kwargs)
    email.html = render_template(template + ".html", **kwargs)
    mail.send(email)
    def save(self):
        email = self.email.data
        site_name = current_app.config['PROJECT_SITE_NAME']
        site_url = current_app.config['PROJECT_SITE_URL']
        sender = current_app.config['MAIL_DEFAULT_SENDER']

        # create signed data
        s = get_signer()
        data = {
            'email': email,
            'signup': True
        }
        signed_data = s.dumps(data)

        # set context to template render
        context = dict(
            site_name=site_name,
            site_url=site_url,
            email=email,
            signed_data=signed_data
        )

        # load template
        html = render_template(
            'accounts/emails/signup.html', **context
        )

        # create and send message
        msg = Message(
            u'Confirm your account - {0}.'.format(site_name),
            sender=sender,
            recipients=[email]
        )
        msg.html = html
        mail.send(msg)
Exemple #3
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)
Exemple #4
0
def send_mail(
        subject,
        sender,
        recipients,
        plain_template_path=None,
        html_template_path=None,
        **context):

    if type(recipients) is not list:
        recipients = [recipients]

    msg = Message(subject,
                  sender=sender,
                  recipients=recipients)

    if plain_template_path:
        msg.body = render_template(plain_template_path, **context)

    if html_template_path:
        msg.html = render_template(html_template_path, **context)

    logger.debug("Sending email",
        subject=subject, sender=sender, recipients=recipients,
        plain_template_path=plain_template_path,
        html_template_path=html_template_path)

    mail.send(msg)
def signup_mail(user, path=None):
    config = current_app.config
    msg = Message(
        "欢迎注册使用{}".format(config['SITE_TITLE']),
        recipients=[user.email],
    )
    reply_to = config.get('MAIL_REPLY_TO', None)
    if reply_to:
        msg.reply_to = reply_to

    host = config.get('SITE_URL', '')
    dct = {
        'host': host.rstrip('/'),
        'token': create_auth_token(user)
    }
    if path:
        dct['path'] = path
    else:
        dct['path'] = url_for('account.signup')
    # link = '%(host)s%(path)s?token=%(token)s' % dct
    link = '%(host)s/?next=%(path)s?token=%(token)s' % dct
    html = render_template('email/signup.html', user=user, link=link)
    msg.html = html
    send_mail(current_app, msg)
    return msg
    def post(self):
        """
		Method to ask for a Password recovery
		:return:
		"""
        # Entries
        try:
            email = api.payload['email']
        except:
            raise ParameterException('email')
        # if the user is not existing, we return a standard error
        if User.get_by_email(email) is None:
            return {
                "message": 'request for recovery successful'
            }
        # mail creation
        user = User.query.filter_by(email=email).first()
        link = constants.CLIENT_URL + "/recover;token_recover=" + generate_confirmation_token(email)
        msg = Message()
        msg.add_recipient(email)
        msg.subject = 'Password recovery for the HotMaps toolbox'
        msg.body = 'Hello ' + user.first_name + ' ' + user.last_name + ' you asked for a password recovery ' \
                                                                       'on your HotMaps account,\n to reset your password, please click on the following link: ' \
                                                                       '\n' + link + '\n if you haven\'t ask for this modification, please delete this email.'
        try:
            mail.send(msg)
        except Exception as e:
            raise RequestException(str(e))

        output = 'request for recovery successful'
        # output
        return {
            "message": output
        }
Exemple #7
0
    def test_msgid_header(self):
        msg = Message(sender="*****@*****.**", subject="subject", recipients=["*****@*****.**"], body="hello")

        # see RFC 5322 section 3.6.4. for the exact format specification
        r = re.compile(r"<\S+@\S+>").match(msg.msgId)
        self.assertIsNotNone(r)
        self.assertIn("Message-ID: " + msg.msgId, msg.as_string())
Exemple #8
0
def mainsite():
    """This function renders the main website.

    The function evaluates the contact form and gets poem data for both current and archive display from a database
    when loading the site.
    """

    # define standard display
    contact_form = ContactForm()
    contact_form_success = False
    jump_to_contact = False

    if request.method == 'POST':
        if not contact_form.validate():
            # contact form validation failed
            jump_to_contact = True
        else:
            # contact form validation succeeded, send email
            msg = Message('Neue Nachricht von Tagespoet.de!', sender=app.config['MAIL_USERNAME'],
                          recipients=[app.config['MAIL_RECIPIENT']])
            msg.body = """
            Von: %s <%s>
            %s
            """ % (contact_form.name.data, contact_form.email.data, contact_form.message.data)
            mail.send(msg)
            contact_form_success = True
            jump_to_contact = True

    # get poem of the day
    cur_poem = mongo.db.poems.find_one({}, sort=[('date', flask_pymongo.DESCENDING)])
    if cur_poem is not None:
        # poem found
        cur_poem_ret = make_poem_html(cur_poem['poem'], 'poemline')
        cur_poem_render_ret = 1
    else:
        # no poem found, return empty values
        # TODO: Implement error handling (logging, sending out maintenance request email)
        cur_poem_ret = ''
        cur_poem_render_ret = 0

    # organize archive
    first_poem = mongo.db.poems.find_one({}, sort=[('date', flask_pymongo.ASCENDING)])

    now = datetime.now()
    yesterdays_date = datetime(now.year, now.month, now.day, 0, 0, 1) + timedelta(hours=6) - timedelta(days=1)
    last_poem = mongo.db.poems.find_one({'date': {'$lte': yesterdays_date}}, sort=[('date', flask_pymongo.DESCENDING)])

    todays_date = datetime.today() + timedelta(hours=6)

    return render_template('index.htm', todays_date=todays_date.strftime("%d.%m.%YYYY"),
                           cur_poem_render=cur_poem_render_ret,
                           cur_poem=cur_poem_ret,
                           first_poem_date=first_poem['date'].strftime('%d.%m.%Y'),
                           last_poem_date=last_poem['date'].strftime('%d.%m.%Y'),
                           last_poem_date_heading=last_poem['date'].strftime("%Y-%m-%dT%H:%M:%S"),
                           last_poem=make_poem_html(last_poem['poem'], 'poemarchiveline'),
                           last_keywords=make_keyword_html(last_poem['keywords']),
                           contact_form=contact_form,
                           contact_form_success=contact_form_success,
                           jump_to_contact=jump_to_contact)
def email_screenplay():
    resource_id = request.form['resource_id']
    title_page = request.form['title_page']
    subject = request.form['subject']
    body_message = request.form['body_message']
    recipients = request.form['recipients'].split(',')

    # Build email body and html
    body = body_message + "\n\n\n    	"
    body += "--- This screenplay written and sent from RawScripts.com."
    body += " Check it out---"
    with app.open_resource('static/text/email.txt') as f:
        html_template = f.read()
    html = html_template.replace("FILLERTEXT", body_message)

    # get pdf file to attach
    include_title_page = title_page == '1'
    export_file = Screenplay.export_to_file(resource_id, 'pdf', include_title_page)
    _file, title, content_type = export_file
    filename = title + '.pdf'

    msg = Message(subject, recipients=recipients, body=body, html=html)
    msg.attach(filename, content_type, _file.getvalue())
    mail.send(msg)

    return Response('sent', mimetype='text/plain')
Exemple #10
0
    def test_bad_header_sender(self):
        msg = Message(subject="testing",
                      sender="[email protected]\n\r",
                      recipients=["*****@*****.**"],
                      body="testing")

        self.assertIn('From: [email protected]', msg.as_string())
Exemple #11
0
 def test_extra_headers(self):
     msg = Message(sender="*****@*****.**",
                   subject="subject",
                   recipients=["*****@*****.**"],
                   body="hello",
                   extra_headers={'X-Extra-Header': 'Yes'})
     self.assertIn('X-Extra-Header: Yes', msg.as_string())
Exemple #12
0
def forgotpassword():
    accounts = app.data.driver.db["people"]
    user = accounts.find_one({"email": request.json["email"]})
    user_name = user["username"]
    user_randome_string = user["random_string"]

    if not user:
        response = jsonify(error="Your Email does not exist in our database")
        response.status_code = 401
        return response
    else:
        msg = Message("Password Link", sender="*****@*****.**", recipients=[request.json["email"]])
        msg.html = (
            "<p>Please click on the link:<br>\
                        <br><p style='color:red;border:1px solid #dcdcdc;padding:10px;"
            "width:800px;text-align:center;font-size:14px;'>"
            "<a href='http://www.youpep.com/#/users/"
            + user_name
            + "/change_password_link/"
            + user_randome_string
            + "'>Click Here</a></p>\
                        <br><br><br><br>\
                        Thanks,<br>The Youpep Team\
                        </p>"
        )
        mail.send(msg)
        return "Recovery email link has been sent to providing email address"
Exemple #13
0
def signup_mail(user):
    """Send signup email"""
    token = hashlib.sha1(user.name).hexdigest()
    url = config.SITE_DOMAIN + url_for('.activate', user_id=user.id, token=token)
    msg = Message("欢迎来到西窗烛", recipients=[user.email])
    msg.html = render_template('email/signup.html', url=url)
    mail.send(msg)
Exemple #14
0
def sendfeedback():
    data = request.args.to_dict()
    msg = Message("FeedBack", sender="FeedBack User", recipients=["*****@*****.**"])
    msg.html = "<b>" + data["feedback_data"] + "</b>"
    if mail.send(msg):
        return jsonify({"data": True})
    return jsonify({"data": False})
Exemple #15
0
def resendActivationLink():
    accounts = app.data.driver.db["people"]
    user = accounts.find_one({"email": request.json["resend_email"]})
    if not user:
        response = jsonify(error="Your Email does not Exist")
        response.status_code = 401
        return response

    create_random_number = id_generator()
    update_user = accounts.update({"username": user["username"]}, {"$set": {"random_string": create_random_number}})
    user_id = str(user["_id"])
    msg = Message(
        "Re Confirm your Youpep account", sender="*****@*****.**", recipients=[request.json["resend_email"]]
    )
    msg.html = (
        '<div style="min-height:100px;border:1px solid #dcdcdc;">'
        "<h5>Thanks for registering with us, To complete your Youpep registration, Follow this link:</h5>"
        '<div style="padding:20px 5px">'
        '<a href="http://www.youpep.com/#/confirm_account/users/'
        + user_id
        + "/confirm/"
        + create_random_number
        + '">Click Here</a></div></div>'
    )
    mail.send(msg)
    response = jsonify(data="Activation link has been sent to your email")
    response.status_code = 200
    return response
Exemple #16
0
def send_Mail():
	with app.app_context():
	# with mail.connect() as conn:
 #    	for user in users:
 #        	message = '...'
 #        	subject = "hello, %s" % user.name
 #        	msg = Message(recipients=[user.email],
 #            	body=message,
 #                subject=subject)

 #        	conn.send(msg)

		msg = Message("Mail Test",
			sender = '*****@*****.**',
			recipients = ['*****@*****.**'])
	
		g.db = connect_db()
		cur = g.db.execute('select * from entries order by id desc')
		data = cur.fetchall()
		for row in data:
			entries = dict(food=row[1],attributes=row[2])
		cur.close()
		toSend =', '.join("{!s}={!r}".format(key,val) for (key,val) in entries.items())
		
		cur1 = g.db.execute('select email from users')
		data1 = cur1.fetchall()
		
		for row in data1:
			print(row[0])
			message = Message(sender = '*****@*****.**',
				recipients=[row[0]],body=toSend)
			message.body = toSend
			mail.send(message)
Exemple #17
0
def 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("emails/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_email(self, register_user):
     """
         Method for sending the registration Email to the user
     """
     try:
         from flask_mail import Mail, Message
     except:
         log.error("Install Flask-Mail to use User registration")
         return False
     mail = Mail(self.appbuilder.get_app)
     msg = Message()
     msg.subject = self.email_subject
     url = url_for('.activation', _external=True, activation_hash=register_user.registration_hash)
     msg.html = render_template(self.email_template,
                                url=url,
                                username=register_user.username,
                                first_name=register_user.first_name,
                                last_name=register_user.last_name)
     msg.recipients = [register_user.email]
     try:
         mail.send(msg)
     except Exception as e:
         log.error("Send email exception: {0}".format(str(e)))
         return False
     return True
Exemple #19
0
def send_message():
    msg = Message('A message frome ' + request.form['name'] + ': '
                  + request.form['email'],
                  sender="*****@*****.**",
                  recipients=["*****@*****.**"])
    msg.body = request.form['message']
    mail.send(msg)
Exemple #20
0
def send_announcement(protocol_id):
    if not g.user.can_create_ballot():
        abort(403)

    protocol = db.session.query(BallotProtocol).get(protocol_id)

    if protocol is None:
        abort(404)

    if app.config["USE_SMTP"]:
        ballot_type = u"volby" if protocol.ballot.type == "ELECTION" \
                      else u"hlasování"
        msg = Message(u"Oznámení výsledku {0}".format(ballot_type),
                      sender=(u"Volební komise", "*****@*****.**"),
                      recipients=app.config["ANNOUNCE_RESULTS_RECIPIENTS"])
        msg.body = render_template('protocol_announcement.txt',
                                   protocol=protocol)
        mail.send(msg)
        
        protocol.announced = True
        db.session.commit()

        #TODO: pass via api directly to registry

        flash(u"Výsledek volby oznámen.", "success")
    else:
        flash(u"Oznámení nebylo odesláno na %s." % ", ".join(app.config["ANNOUNCE_RESULTS_RECIPIENTS"]), "danger")
    
    return redirect(url_for("ballot_protocol_list",
                            ballot_id=protocol.ballot_id))
Exemple #21
0
def signup():
	if request.method == 'GET':
		return render_template('signup.html')
	elif request.method == 'POST':
		try:
			username = request.form.get('username')
			password = request.form.get('password')
			confirm_password = request.form.get('confirm_password')
			email = request.form.get('email')
			confirm_email = request.form.get('confirm_email')
			if password != confirm_password:
				flash('Passwords do not match!')
			elif email != confirm_email:
				flash('Email address does not match')
			else:
				user = User.create(username, password, email)
				token = user.gentoken()
				link = 'http://*****:*****@gmail.com', recipients=[email])
				msg.body = link
				mail.send(msg)
				flash('Email Sent.')
		except IntegrityError:
			flash('That username is taken, please try again')
			db_rollback()
			return redirect('/signup')
		except InvalidRequestError:	
			db_rollback()
			return redirect('/signup')
		return redirect('/')
def share():
    if request.method=='POST':
        sid = request.form['sid']
        addresslist = request.form['addresslist'].replace(' ','').split(',')
        logging.info("sid = "+ str(sid))
        logging.info("addresses = "+ str(addresslist))
        # do some crazy smtp stuff
        msg = Message("Course Instructor Survey",
                    sender = ("Course Instructor Survey","*****@*****.**"),
                    recipients=addresslist)
        msg.body = """Hello,
                    You have been nomitated to take the following survey at Course Instructor Survey.
                    Please use the link below to complete the survey.

                    sasrusha.pythonanywhere.com/view?sid=%s

                    We appreciate your time and effort.
                    --Course Instructor Survey.""" % (str(sid))
        mail.send(msg)

        return redirect('/surveys')
    else:
        sid = request.args.get('sid','')
        return render_template('share.pt', logged_in = True,user = session['uname'],
                        sid = sid)
Exemple #23
0
def send_alert_created_mail(subject, recipient, **kwargs):
    msg = Message(alert_app.config['ALERT_WEB_MAIL_SUBJECT_PREFIX'] + subject,
                  sender=alert_app.config['MAIL_USERNAME'],
                  recipients=[recipient])
    msg.body = render_template('rescue/create_rescue_mail' + '.txt', **kwargs)
    msg.html = render_template('rescue/create_rescue_mail' + '.html', **kwargs)
    mail.send(msg)
Exemple #24
0
def send_email(sender, recipients, subject, message):
    logger.debug('Sending mail '+sender+':'+subject)
    msg = Message(_prefix_subject_line(subject),
                  sender=sender,
                  recipients=recipients)
    msg.body = message
    mail.send(msg)
def index():
   msg = Message('Hello', sender = '*****@*****.**', recipients = ['*****@*****.**'])
   msg.body = "Hello Flask message sent from Flask-Mail"
   with app.open_resource("Notes.txt") as fp:
      msg.attach("Notes.txt","txt", fp.read())
   mail.send(msg)
   return "Sent"
Exemple #26
0
def send(subject, recipients, template_base, **kwargs):
    '''
    Send a given email to multiple recipients.

    User prefered language is taken in account.
    To translate the subject in the right language, you should ugettext_lazy
    '''
    sender = kwargs.pop('sender', None)
    if not isinstance(recipients, (list, tuple)):
        recipients = [recipients]

    debug = current_app.config.get('DEBUG', False)
    send_mail = current_app.config.get('SEND_MAIL', not debug)
    connection = send_mail and mail.connect or dummyconnection

    with connection() as conn:
        for recipient in recipients:
            lang = i18n._default_lang(recipient)
            with i18n.language(lang):
                log.debug(
                    'Sending mail "%s" to recipient "%s"', subject, recipient)
                msg = Message(subject, sender=sender,
                              recipients=[recipient.email])
                msg.body = theme.render(
                    'mail/{0}.txt'.format(template_base), subject=subject,
                    sender=sender, recipient=recipient, **kwargs)
                msg.html = theme.render(
                    'mail/{0}.html'.format(template_base), subject=subject,
                    sender=sender, recipient=recipient, **kwargs)
                conn.send(msg)
Exemple #27
0
def send_html_email(subject, recipients, text_body, html_body):
    msg = Message(_prefix_subject_line(subject),
                  sender=DEFAULT_SENDER,
                  recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    mail.send(msg)
Exemple #28
0
def send_email(to, subject, template, **kwargs):
    msg = Message(config.MAIL_SUBJECT_PREFIX + ' ' + subject,
                  sender=config.MAIL_SENDER, recipients=to)
    msg.to = to
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    mail.send(msg)
Exemple #29
0
def send_abstainer_confirmation(abstainer_id):
    abstainer = db.session.query(Abstainer).get(abstainer_id)
    ballot = abstainer.ballot
    body = render_template(
        'abstainer_email.txt',
        ballot=ballot,
        abstainer=abstainer,
        timestamp=int(time.mktime(abstainer.created_at.timetuple())),
    )

    if app.config["USE_SMTP"]:
        msg = Message(u"Potvrzení o zdržení se hlasování",
                      sender=(u"Volební komise", "*****@*****.**"),
                      recipients=[abstainer.email])
        msg.body = body
        logger.info(u"Sending abstainer confirmation {0} {1}"
                    .format(abstainer.name, abstainer.email))
        mail.send(msg)
        logger.info(u"Abstainer confirmation sent {0} {1}"
                    .format(abstainer.name, abstainer.email))
    else:
        # Only SMTP supported here
        logger.warning(u"Not sending abstainer confirmation {0} {1}"
                       .format(abstainer.name, abstainer.email))

    abstainer.confirmation_sent = True
Exemple #30
0
def users():
    form = NewUserForm()

    if form.validate_on_submit():
        email, name = form.email.data, form.name.data
        user = User(email, name)

        db.session.add(user)
        db.session.commit()
        app.logger.info('%s manually created new user with email %s and id: %s',
                        current_user.id, email, user.id)

        code = user.login_code(app.config['SECRET_KEY'])
        msg = Message('Welcome to the EMF website',
                      sender=app.config['CONTACT_EMAIL'],
                      recipients=[email])
        msg.body = render_template('emails/manually-added-user.txt',
                                   user=user, code=code)
        mail.send(msg)

        flash('Created account for: %s' % name)
        return redirect(url_for('.users'))

    users = User.query.order_by(User.id).options(joinedload(User.permissions)).all()
    return render_template('admin/users/users.html', users=users, form=form)
Exemple #31
0
def test_email():
    msg = Message('Flask项目测试邮件',
                  recipients=['*****@*****.**'],
                  body='Hello, 这是一封测试邮件,这是邮件的正文')
    mail.send(msg)
    return 'success'
Exemple #32
0
def contact_form_post():

    form = ContactForm(request.form)

    if not form.validate():
        return jsonify({'status': 'error', 'errors': form.errors})

    name = form.first_name.data + " " + form.last_name.data
    email_content = html_contact_form(name=name,
                                      email=form.email.data,
                                      phone_num=form.phone_num.data,
                                      subject=form.subject.data,
                                      association=form.association.data,
                                      unit=form.unit.data,
                                      msg=form.msg.data)

    try:
        receivers = Roles.query.filter_by(role_name='Contact Form').one()
    except:
        return jsonify({
            'status':
            'error',
            'msg':
            'Something went wrong. Please refresh the page and try again.'
        })

    # recipients = receivers.emails
    recipients = [r.email for r in receivers.emails]

    msg = Message('"{}" Contact Form Submission'.format(name),
                  sender=app.config['MAIL_USERNAME'],
                  recipients=recipients)
    msg2 = Message('Contact Form Submission Receipt',
                   sender=app.config['MAIL_USERNAME'],
                   recipients=[form.email.data])
    msg.html = email_content
    msg2.html = "Thank you for contacting Huntington West Properties. Someone will be in contact with you shortly.<br><br>{}".format(
        email_content)
    # print(msg2.html)
    try:
        new_history = History('contact_form', None)
        db.session.add(new_history)
        db.session.flush()

        id_content = HistoryContent(new_history.history_id, 'Identifier',
                                    'Contact Form Submission')
        name_content = HistoryContent(new_history.history_id, 'Name', name)
        email_content = HistoryContent(new_history.history_id, 'Email',
                                       form.email.data)
        phone_content = HistoryContent(new_history.history_id, 'Phone Number',
                                       form.phone_num.data)
        regarding_content = HistoryContent(new_history.history_id, 'Subject',
                                           form.subject.data)
        acn_content = HistoryContent(new_history.history_id, 'Association',
                                     form.association.data)
        unit_content = HistoryContent(new_history.history_id, 'Unit',
                                      form.unit.data)
        msg_content = HistoryContent(new_history.history_id, 'Message',
                                     form.msg.data)
        db.session.add(id_content)
        db.session.add(name_content)
        db.session.add(email_content)
        db.session.add(phone_content)
        db.session.add(regarding_content)
        db.session.add(acn_content)
        db.session.add(unit_content)
        db.session.add(msg_content)
        db.session.commit()

        mail.send(msg)
        mail.send(msg2)
    except:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'msg': 'Form failed to send. Please try again.'
        })
    return jsonify({
        'status':
        'success',
        'msg':
        'Contact form was successfully sent! Someone will contact you soon.'
    })
Exemple #33
0
def processRequest(request):
    print("Processing a request:")
    print(request)
    # Can do anything here. E.g., publish a message to the error handler when processing fails.

    # resultstatus = bool(random.getrandbits(1)) # simulate success/failure with a random True or False
    # result = {'status': resultstatus, 'message': 'Simulated random  result.', 'reservation': reservation}
    # resultmessage = json.dumps(result, default=str) # convert the JSON object to a string

    # ---------------------------need to be confirmed------------------------------------
    tutor_id = request['tutor_id']
    tutee_id = request['tutee_id']
    booking_id = request['booking_id']
    print(request)
    # ---------------------------need to be confirmed------------------------------------
    if 'status' in list(request.keys()) and request['status'] == 'accept':
        hostname = "localhost"  # default hostname
        port = 5672  # default port
        # connect to the broker and set up a communication channel in the connection
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=hostname, port=port))
        # Note: various network firewalls, filters, gateways (e.g., SMU VPN on wifi), may hinder the connections;
        # If "pika.exceptions.AMQPConnectionError" happens, may try again after disconnecting the wifi and/or disabling firewalls
        channel = connection.channel()
        # set up the exchange if the exchange doesn't exist
        exchangename = "tutee_topic"
        channel.exchange_declare(exchange=exchangename, exchange_type='topic')

        email = tutee_id
        text = "Your request with booking id " + str(
            booking_id) + " has been accepted!"

    elif 'status' in list(request.keys()) and request['status'] == 'reject':
        hostname = "localhost"  # default hostname
        port = 5672  # default port
        # connect to the broker and set up a communication channel in the connection
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=hostname, port=port))
        # Note: various network firewalls, filters, gateways (e.g., SMU VPN on wifi), may hinder the connections;
        # If "pika.exceptions.AMQPConnectionError" happens, may try again after disconnecting the wifi and/or disabling firewalls
        channel = connection.channel()
        # set up the exchange if the exchange doesn't exist
        exchangename = "tutee_topic"
        channel.exchange_declare(exchange=exchangename, exchange_type='topic')

        email = tutee_id
        text = "Your request with booking id " + str(
            booking_id) + " has been rejected!"
    else:
        hostname = "localhost"  # default hostname
        port = 5672  # default port
        # connect to the broker and set up a communication channel in the connection
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=hostname, port=port))
        # Note: various network firewalls, filters, gateways (e.g., SMU VPN on wifi), may hinder the connections;
        # If "pika.exceptions.AMQPConnectionError" happens, may try again after disconnecting the wifi and/or disabling firewalls
        channel = connection.channel()
        # set up the exchange if the exchange doesn't exist
        exchangename = "tutor_topic"
        channel.exchange_declare(exchange=exchangename, exchange_type='topic')

        email = tutor_id
        text = "You have received a request with booking id " + str(
            booking_id) + " !"

    with app.app_context(
    ):  #enable application context to access global variable
        msg = Message(
            '[' + booking_id + '] Tuition request update from Tutor Labs',
            sender='*****@*****.**',
            recipients=[email],
            body="Dear user,\n\n\t" + text + "\n\nBest wishes,\nTutor Labs")
        mail.send(msg)
        result = 'Message Sent!'
    return result
Exemple #34
0
def send():
   msg = Message('Hello', sender = '*****@*****.**', recipients = ['*****@*****.**'])
   msg.body = "yo quinton"
   mail.send(msg)
   return "Sent"
Exemple #35
0
def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    Thread(target=send_async_email, args=(app, msg)).start()
Exemple #36
0
def webhook():
    # Get request parameters
    req = request.get_json(silent=True, force=True)
    action = req.get('result').get('action')

    # CommonBalanceBot - welcome
    if action == "commonbalancebot-welcome":
        req_for_uid = functions_SEB.check_for_logs(req)["payload"]
        ourspeech = functions_SEB.welcome_response(req_for_uid)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - create log
    elif action == "commonbalancebot-create_log":
        ourspeech = functions_SEB.create_log(req)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - switch log button clicked
    elif action == "commonbalancebot-switch_log_button":
        req_for_uid = functions_SEB.check_for_logs(req)["payload"]
        ourspeech = functions_SEB.switch_log_response(req_for_uid)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - switch log
    elif action == "commonbalancebot-switch_log":
        ourspeech = functions_SEB.switch_log(req)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - delete log
    elif action == "commonbalancebot-delete_log":
        req_for_uid = functions_SEB.check_for_logs(req)["payload"]
        ourspeech = functions_SEB.delete_log_response(req_for_uid, req['result']['contexts'])
        res = functions_SEB.commonbalancebot_speech(ourspeech["payload"], action, ourspeech["contexts"])

    # CommonBalanceBot - delete log - deletion confirmed
    elif action == "commonbalancebot-delete_log-do_it":
        ourspeech = functions_SEB.delete_log(req)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - add new user
    elif action == "commonbalancebot-add_user":
        ourspeech = functions_SEB.add_user(req)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - remove user
    elif action == "commonbalancebot-delete_user":
        ourspeech = functions_SEB.delete_user(req)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - add new payment OR modify existing payment
    elif action == "commonbalancebot-add_payment":
        result = functions_SEB.add_payment(req)
        if result["status"] != "error":
            functions_SEB.update_balance(req)
            ourspeech = functions_SEB.balance(req)["payload"]
        else:
            ourspeech = result["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - delete payment
    elif action == "commonbalancebot-delete_payment":
        ourspeech = functions_SEB.delete_payment(req)["payload"]
        functions_SEB.update_balance(req)
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - modify payment (display payment to be modified)
    elif action == "commonbalancebot-modify_payment":
        ourspeech = functions_SEB.display_payment2modify(req)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - show balance
    elif action == "commonbalancebot-balance":
        functions_SEB.update_balance(req)
        user = req.get('result').get('parameters').get('user')
        if user == "":
            user = "******"
        ourspeech = functions_SEB.balance(req, user)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - show statement
    elif action == "commonbalancebot-statement":
        ourspeech = functions_SEB.statement(req)["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - get json
    elif action == "commonbalancebot-getjson":
        ourspeech = 'hello'
        #print(str(req))
        res = functions_SEB.commonbalancebot_speech2(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - taking user back to conversation
    elif action == "commonbalancebot-besidethepoint":
        ourspeech = functions_SEB.besidethepoint()["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - sending statement to email
    elif action == "commonbalancebot-statement_to_email":
        print("Sending email!")
        email = req.get("result").get("parameters").get("email")
        current_datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        statement2mail = functions_SEB.statement(req)["payload"]["rich_messages"][0]["speech"].replace("\n","<br>")
        msg = Message("SharedExpensesBot: Statement as of {}".format(current_datetime), sender="*****@*****.**", recipients=[email])
        msg.html = "{}<br><br>Thanks for using SharedExpensesBot!<br>Iurii Dziuban - March 2018 / <a href='https://iuriid.github.io/'>iuriid.github.io</a>".format(statement2mail)
        mail.send(msg)

        ourspeech = {"speech": "Statemen was successfully sent to your email", "rich_messages": [{"platform": "telegram", "type": 0, "speech": "Statemen was successfully sent to your email"}]}
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    # CommonBalanceBot - display FAQ
    elif action == "commonbalancebot-faq":
        ourspeech = functions_SEB.faq()["payload"]
        res = functions_SEB.commonbalancebot_speech(ourspeech, action, req['result']['contexts'])

    else:
        # If the request is not of our actions throw an error
        res = {
            'speech': 'Something wrong happened',
            'displayText': 'Something wrong happened'
        }

    return make_response(jsonify(res))
Exemple #37
0
def send_email(email_obj, to):
    
    msg = Message(subject = email_obj['email_subject'], body= email_obj['email_body'], recipients= [to] )
    mail.send(msg)
Exemple #38
0
def index():
    if request.method == "POST":
        if 'signupBVN' in request.form:
            sql = "SELECT * FROM CUSTOMER WHERE BVN = ?"
            stmt = ibm_db.prepare(conn, sql)
            param = request.form["signupBVN"],
            ibm_db.execute(stmt, param)
            if ibm_db.fetch_row(stmt) == False:
                sql = "SELECT * FROM CUSTOMER ORDER BY ID DESC fetch first 1 row only"
                stmt = ibm_db.exec_immediate(conn, sql)
                customer = 1
                while ibm_db.fetch_row(stmt) != False:
                    customer = customer + int(ibm_db.result(stmt, "ID"))
                # Save new customer info
                sql = "INSERT INTO CUSTOMER (ID, BVN, FIRSTNAME, LASTNAME, DATEOFBIRTH, PHONENUMBER, EMAIL, PASSWORD, CITY, DOC) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
                stmt = ibm_db.prepare(conn, sql)
                param = customer, request.form["signupBVN"], request.form["inputFName"], request.form["inputLName"], request.form["inputDOB"], request.form["inputPhone"], request.form["inputEmail"], request.form["inputPassword"], request.form["inputLocation"], datetime.date.today(),
                ibm_db.execute(stmt, param)
                # Save security info for new customer
                sql = "INSERT INTO SECURITY (ID, BVN, SQ1, SA1, SQ2, SA2, SQ3, SA3) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
                stmt = ibm_db.prepare(conn, sql)
                param = customer, request.form["signupBVN"], request.form["inputSQ1"], request.form["inputSA1"], request.form["inputSQ2"], request.form["inputSA2"], request.form["inputSQ3"], request.form["inputSA3"],
                ibm_db.execute(stmt, param)
                msg = Message('Welcome to CASBA', sender = '*****@*****.**', recipients = [str(request.form["inputEmail"])])
                msg.body = "Thank you for registering to use of Cognitive Banking (CogniBank) service. Enjoy the experience of using artifical intelligence to organise your finances."
                mail.send(msg)
                flash('You were successfully registered!')
                return redirect(url_for('index'))
            else:
                flash('You were already registered!')
                return redirect(url_for('index'))
        elif 'loginBVN' in request.form:
            sql = "SELECT * FROM CUSTOMER WHERE BVN = ?"
            stmt = ibm_db.prepare(conn, sql)
            param = request.form["loginBVN"],
            ibm_db.execute(stmt, param)
            if ibm_db.fetch_row(stmt) != False:
                # check if user credentials match
                if request.form["inputPassword"] == ibm_db.result(stmt, "PASSWORD"):
                    session['logged_in'] = True
                    user.update({'bvn': str(request.form["loginBVN"]), 'fName': str(ibm_db.result(stmt, "FIRSTNAME")), 'lName': str(ibm_db.result(stmt, "LASTNAME")), 'email': str(ibm_db.result(stmt, "EMAIL")) })
                    # sql = "SELECT * FROM ACCOUNT WHERE BVN = ?"
                    # stmt = ibm_db.prepare(conn, sql)
                    # param = request.form["loginBVN"],
                    # ibm_db.execute(stmt, param)
                    sql1 = "".join(["SELECT * FROM ACCOUNT WHERE BVN = ", str(request.form["loginBVN"])])
                    stmt1 = ibm_db.exec_immediate(conn, sql1)
                    userAccountDF = pandas.read_sql(sql1 , pconn)
                    sql2 = "".join(["SELECT * FROM CARD WHERE BVN = ", str(user['bvn'])])
                    stmt2 = ibm_db.exec_immediate(conn, sql2)
                    userCardDF = pandas.read_sql(sql2 , pconn)
                    if userAccountDF.empty:
                        user.update({'accountIn': 0})
                        if userCardDF.empty:
                            user.update({'#Card': 0})
                        return redirect(url_for('chat'))
                    else:
                        user.update({'accountIn': len(userAccountDF.index)})
                        userAccount = {}
                        for i in range(0, user["accountIn"]):
                            userAccount[i] = userAccountDF.iloc[i].tolist()
                        user.update({'Account': userAccount})
                        #print user["Account"][0][0]
                        if userCardDF.empty:
                            user.update({'#Card': 0})
                            return redirect(url_for('chat'))
                        else:
                            user.update({'#Card': len(userCardDF.index)})
                            userCard = {}
                            for i in range(0, user["#Card"]):
                                userCard[i] = userCardDF.iloc[i].tolist()
                            user.update({'Card': userCard})
                            #print user["Account"][0][0]
                            return redirect(url_for('chat'))
                else:
                    flash('Wrong credentials, please try again or create an account!')
                    return redirect(url_for('index'))
            else:
                flash('Wrong credentials, please try again or create an account!')
                return redirect(url_for('index'))
        elif 'passwordBVN' in request.form:
            sql = "SELECT * FROM SECURITY WHERE BVN = ?"
            stmt = ibm_db.prepare(conn, sql)
            param = request.form["passwordBVN"],
            ibm_db.execute(stmt, param)
            # check if security questions match
            if ibm_db.fetch_row(stmt) != False:
                if str(ibm_db.result(stmt, "SQ1")) == str(request.form["inputSQ1"]) and str(ibm_db.result(stmt, "SA1")) == str(request.form["inputSA1"]):
                    if str(ibm_db.result(stmt, "SQ2")) == str(request.form["inputSQ2"]) and str(ibm_db.result(stmt, "SA2")) == str(request.form["inputSA2"]):
                        if str(ibm_db.result(stmt, "SQ3")) == str(request.form["inputSQ3"]) and str(ibm_db.result(stmt, "SA3")) == str(request.form["inputSA3"]):
                            new_password = gen_random_string(password_charset, 6)
                            sql = "UPDATE CUSTOMER SET PASSWORD = ? WHERE BVN = ?"
                            stmt = ibm_db.prepare(conn, sql)
                            param = new_password, request.form["passwordBVN"],
                            ibm_db.execute(stmt, param)
                            sql = "SELECT * FROM CUSTOMER WHERE BVN = ?"
                            stmt = ibm_db.prepare(conn, sql)
                            param = request.form["passwordBVN"],
                            ibm_db.execute(stmt, param)
                            if ibm_db.fetch_row(stmt) != False:
                                msg = Message('Password Reset', sender = '*****@*****.**', recipients = [str(ibm_db.result(stmt, "EMAIL"))])
                                msg.body = ' '.join(["Here is your new password", new_password])
                                mail.send(msg)
                                flash('Your password has been reset! Please check your email.')
                                return redirect(url_for('index'))
                            else:
                                flash('You are not registered! Please try again or create an account.')
                                return redirect(url_for('index'))
                        else:
                            flash('Incorrect Security Question & Answer')
                            return redirect(url_for('index'))
                    else:
                        flash('Incorrect Security Question & Answer')
                        return redirect(url_for('index'))
                else:
                    flash('Incorrect Security Question & Answer')
                    return redirect(url_for('index'))
            else:
                flash('You are not a registered user! Please create an account.')
                return redirect(url_for('index'))
    else:
        return render_template('index.html')
Exemple #39
0
def send_email(user_email, username): #to know where to send it and write the username in the email
	msg = Message('Thank you for signing up!', #title of the email.
		  sender = app.config['MAIL_USERNAME'], 
		  recipients = [user_email])
	msg.html = render_template('email.html', username = username)
	mail.send(msg) #here we actually send the message
Exemple #40
0
def send_email(subject, sender, recipients, text_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    # separate thread to send emails
    Thread(target=send_async_email,
           args=(current_app._get_current_object(), msg)).start()
Exemple #41
0
def send_email_with_reset_password_token(user_email, token):
    msg = Message("Solicitud de cambio de contraseña",
                  recipients=[user_email],
                  body='Hola! Este es tu codigo: {0}'.format(token))
    mail.send(msg)
Exemple #42
0
def chat():
    # check if user is logged in
    if not session.get('logged_in'):
        return render_template('index.html')
    else:
        user_ip = request.remote_addr
        user_agent = request.headers.get('User-Agent')
        session['unique_conversation_id'] = str(user_ip) + "__" + str(user_agent)
        context["conversation_id"] = str(hashlib.sha256(session['unique_conversation_id'].encode('utf-8')).hexdigest())
        if request.method == "POST":
            if 'cardNo' in request.form:
                sql = "SELECT * FROM CARD WHERE CARDNO = ?"
                stmt = ibm_db.prepare(conn, sql)
                param = request.form["cardNo"],
                ibm_db.execute(stmt, param)
                if ibm_db.fetch_row(stmt) == False:
                    sql = "SELECT * FROM CARD ORDER BY ID DESC fetch first 1 row only"
                    stmt = ibm_db.exec_immediate(conn, sql)
                    card = 1
                    while ibm_db.fetch_row(stmt) != False:
                        card = card + int(ibm_db.result(stmt, "ID"))
                    # Save new customer card info
                    sql = "INSERT INTO CARD (ID, BVN, ACCNO, CARDNO, CARDVENDOR, CARDTYPE, CVC, EXPIRY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
                    stmt = ibm_db.prepare(conn, sql)
                    param = card, user["bvn"], request.form["cardAccountNo"], request.form["cardNo"], request.form["cardVendor"], request.form["cardType"], request.form["cvc"], request.form["cardExpiry"],
                    ibm_db.execute(stmt, param)
                    msg = Message('CASBA: New Card', sender = '*****@*****.**', recipients = [str(user["email"])])
                    msg.body = "You have added a new card"
                    mail.send(msg)
                    flash('You have successfully added a card!')
                    sql2 = "".join(["SELECT * FROM CARD WHERE BVN = ", str(user['bvn'])])
                    stmt2 = ibm_db.exec_immediate(conn, sql2)
                    userCardDF = pandas.read_sql(sql2 , pconn)
                    if userCardDF.empty:
                        user.update({'#Card': 0})
                        return redirect(url_for('chat'))
                    else:
                        user.update({'#Card': len(userCardDF.index)})
                        userCard = {}
                        for i in range(0, user["#Card"]):
                            userCard[i] = userCardDF.iloc[i].tolist()
                        user.update({'Card': userCard})
                        #print user["Account"][0][0]
                        return redirect(url_for('chat'))
                    return render_template('chat.html', userJS=json.dumps(user), user=user, async_mode=socketio.async_mode)
                else:
                    flash('You have card already registered!')
                    return render_template('chat.html', userJS=json.dumps(user), user=user, async_mode=socketio.async_mode)
            elif 'accountNo' in request.form:
                sql = "SELECT * FROM ACCOUNT WHERE ACCNO = ?"
                stmt = ibm_db.prepare(conn, sql)
                param = request.form["accountNo"],
                ibm_db.execute(stmt, param)
                if ibm_db.fetch_row(stmt) == False:
                    sql = "SELECT * FROM ACCOUNT ORDER BY ID DESC fetch first 1 row only"
                    stmt = ibm_db.exec_immediate(conn, sql)
                    account = 1
                    while ibm_db.fetch_row(stmt) != False:
                        account = account + int(ibm_db.result(stmt, "ID"))
                    # Save new customer info
                    sql = "INSERT INTO ACCOUNT (ID, BVN, ACCNO, ACCBANK, ACCNAME, ACCTYPE, ACCBALANCE) VALUES (?, ?, ?, ?, ?, ?, ?)"
                    stmt = ibm_db.prepare(conn, sql)
                    param = account, user["bvn"], request.form["accountNo"], request.form["accountBank"], request.form["accountName"], request.form["accountType"], request.form["accountBalance"],
                    ibm_db.execute(stmt, param)
                    msg = Message('CASBA: New Account', sender = '*****@*****.**', recipients = [str(user["email"])])
                    msg.body = "You have added a new account"
                    mail.send(msg)
                    flash('You were successfully setup an account!')
                    sql1 = "".join(["SELECT * FROM ACCOUNT WHERE BVN = ", str(user['bvn'])])
                    stmt1 = ibm_db.exec_immediate(conn, sql1)
                    userAccountDF = pandas.read_sql(sql1 , pconn)
                    if userAccountDF.empty:
                        user.update({'accountIn': 0})
                        return redirect(url_for('chat'))
                    else:
                        user.update({'accountIn': len(userAccountDF.index)})
                        userAccount = {}
                        for i in range(0, user["accountIn"]):
                            userAccount[i] = userAccountDF.iloc[i].tolist()
                        user.update({'Account': userAccount})
                        #print user["Account"][0][0]
                        return redirect(url_for('chat'))
                    return render_template('chat.html', userJS=json.dumps(user), user=user, async_mode=socketio.async_mode)
                else:
                    flash('You have account already registered!')
                    return render_template('chat.html', userJS=json.dumps(user), user=user, async_mode=socketio.async_mode)
            else:
                flash('Unsuccessful account setup!')
                return render_template('chat.html', userJS=json.dumps(user), user=user, async_mode=socketio.async_mode)
        else:
            return render_template('chat.html', userJS=json.dumps(user), user=user, async_mode=socketio.async_mode)
Exemple #43
0
def send_email(subject, sender, recipients, text_body, html_body):
	msg = Message(subject, sender=sender, recipients=recipients)
	msg.body = text_body
	msg.html = html_body
	mail.send(msg)
Exemple #44
0
def create_gc_payment(payment):
    try:
        logger.info("Creating GC payment for %s (%s)", payment.id,
                    payment.mandate)
        gc_payment = gocardless_client.payments.create(
            params={
                "amount": payment.amount_int,
                "currency": payment.currency,
                "links": {
                    "mandate": payment.mandate
                },
                "metadata": {
                    "payment_id": str(payment.id)
                },
            },
            headers={"Idempotency-Key": str(payment.id)},
        )

        payment.gcid = gc_payment.id
        payment.state = "inprogress"

    except gocardless_pro.errors.ValidationFailedError as exc:
        currency_errors = [e for e in exc.errors if e["field"] == "currency"]
        if currency_errors:
            # e['message'] will be one of:
            #   'must be GBP for a bacs mandate'
            #   'must be EUR for a sepa_core mandate'
            logger.error("Currency exception %r confirming payment", exc)
            flash("Your account cannot be used for {} payments".format(
                payment.currency))
        else:
            logger.error("Exception %r confirming payment", exc)
            flash("An error occurred with your payment, please contact {}".
                  format(app.config["TICKETS_EMAIL"][1]))

        return redirect(url_for("users.purchases"))

    except Exception as e:
        logger.error("Exception %r confirming payment", e)
        flash("An error occurred with your payment, please contact {}".format(
            app.config["TICKETS_EMAIL"][1]))
        return redirect(url_for("users.purchases"))

    # We need to make sure of a 5 working days grace
    # for gocardless payments, so push the payment expiry forwards
    payment.expires = datetime.utcnow() + timedelta(
        days=app.config["EXPIRY_DAYS_GOCARDLESS"])
    for purchase in payment.purchases:
        purchase.set_state("payment-pending")

    db.session.commit()
    logger.info("Reset expiry for payment %s", payment.id)

    # FIXME: determine whether these are tickets or generic products
    msg = Message(
        "Your EMF ticket purchase",
        sender=app.config["TICKETS_EMAIL"],
        recipients=[payment.user.email],
    )
    msg.body = render_template(
        "emails/tickets-purchased-email-gocardless.txt",
        user=payment.user,
        payment=payment,
    )
    mail.send(msg)

    return redirect(url_for(".gocardless_waiting", payment_id=payment.id))
Exemple #45
0
def register():
    form_dict = {}
    errors = []
    success = []

    try:
        user = session['user_hash']
        if user:
            return redirect(url_for('home'))
    except Exception as e:
        pass

    if request.method == 'POST':
        # Get data from form
        form_dict = loadForm(form_dict)
        # Make sure fields are not empty
        empty = checkEmptyForm(form_dict)
        if not empty:
            email = form_dict['email']
            first_name = form_dict['first_name']
            last_name = form_dict['last_name']
            password = generate_password_hash(form_dict['password'])
            confirm_password = form_dict['confirm_password']

            perm = 1
            position_id = 1

            user_hash = generate_password_hash(
                str(email) + str(first_name) + str(last_name) + str(password))
            organization = generate_password_hash(str(user_hash))

            # Validate As Needed
            if form_dict['password'] != confirm_password:
                errors.append("Passwords do not Match.")

            if alreadyAnUser(email):
                errors.append(
                    "There is already an user with that email address.")
            # If no errors, proceed with database interaction
            if len(errors) == 0:
                sql = "INSERT INTO users (email, first_name, last_name, password, permission_id, position_id, user_hash, verified, organization) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
                data = [
                    email, first_name, last_name, password, perm, position_id,
                    user_hash, 0, organization
                ]
                db, cursor = connect()
                try:
                    cursor.execute(sql, data)
                    db.commit()
                    db.close()
                    registration = "<p>Thank you for signing up. Please click the link to verify.</p><br>"
                    registration += "<p><a href='" + str(
                        site_url) + "confirm?user="******"'>Verify</a></p>"
                    msg = Message(subject='Verify Email - CSC 394',
                                  html=registration,
                                  sender="*****@*****.**",
                                  recipients=[
                                      str(email)
                                  ])  # ENTER YOUR EMAIL IN recipients
                    mail.send(msg)
                    success.append(
                        "You have been signed up. Please check your Email to verify your account."
                    )
                except Exception as e:
                    errors.append("Exception found: " + str(e))
            else:
                print("There Was an Error.")
        else:
            errors.append('There are empty fields in the form.')
    return render_template('register.html',
                           current_data=None,
                           errors=errors,
                           success=success)
Exemple #46
0
def send_confirmation_mail(to, subject, template, mail_sender):
    msg = Message(subject,
                  recipients=[to],
                  html=template,
                  sender=MAIL_DEFAULT_SENDER)
    mail_sender.send(msg)
def emaildetail():
    user = User.query.filter_by(username=current_user.username).first()
    dayalt = datetime.datetime.strptime(session['day'],'%Y-%m-%d').strftime('%A %B %d, %Y')
    month = datetime.datetime.strptime(session['day'],'%Y-%m-%d').month
    weekday = datetime.datetime.strptime(session['day'],'%Y-%m-%d').weekday()
    if month in [4,5,6,7,8,9,10]:
        if weekday > 4:
            hours = "8am - 2pm"
        else:
            hours = "Noon - 6pm"
    elif month in [11,12]:
        if weekday > 4:
            hours = "9am - 2pm"
        else:
            hours = "Noon - 6pm"
    else:
        if weekday > 4:
            hours = "10am - 2pm"
        else:
            hours = "Noon - 6pm"

    q = (db.session.query(
        OrderTbl.quantity,
        OrderTbl.wishlist,
        Available.offerprice,
        Product.description,
        Product.unit,
        (OrderTbl.quantity * Available.offerprice).label('itemtotal'),
        User.name)
        .join(Available, OrderTbl.offerID==Available.offerID)
        .join(Product, Available.productID==Product.productID)
        .join(User, OrderTbl.custID==User.id)
        .filter(Available.sellerID==user.id, OrderTbl.isDeleted==False, Available.day==session['day'])
        .all())

    msg = Message(recipients=[user.email])
    msg.subject = "Blacksburg Farmers Market Reservation Details - " + dayalt

    msg.html = "<img src='http://fmportal.pythonanywhere.com/static/img/fmLogo.png' /> &nbsp; <img src='http://fmportal.pythonanywhere.com/static/img/fmMailBanner.png' /><br><br>"

    msg.html = msg.html + "Hi " + user.name + ",<br><br>"
    msg.html = msg.html + "Here is a detailed list of all the customers who have made reservations for your items and what they have<br>"
    msg.html = msg.html + "reserved for <strong>" + dayalt + "</strong><br><br>"
    msg.html = msg.html + "<table style='border: 1px solid black; border-collapse: collapse;'>"
    msg.html = msg.html + "<tr style='border: 1px solid black; border-collapse: collapse;'>"
    msg.html = msg.html + "<th style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>Customer</th>"
    msg.html = msg.html + "<th style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>Product</th>"
    msg.html = msg.html + "<th style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>Sell-by unit</th>"
    msg.html = msg.html + "<th style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>Reserved quantity</th>"
    msg.html = msg.html + "<th style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>Wish list quantity</th>"
    msg.html = msg.html + "<th style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>Unit price</th>"
    msg.html = msg.html + "<th style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>Total</th></tr>"

    for item in q:
        itemtotal = item.quantity * item.offerprice

        msg.html = msg.html + "<tr style='border: 1px solid black; border-collapse: collapse;'>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + item.name + "</td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + item.description + "</td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + item.unit + "</td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + str(item.quantity) + "</td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + str(item.wishlist) + "</td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + "${:.2f}".format(item.offerprice) + "</td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + "${:.2f}".format(itemtotal) + "</td></tr>"

    msg.html = msg.html + "</table><br>"
    msg.html = msg.html + "We look forward to having you sell on " + dayalt + ". Remember that our hours that<br>"
    msg.html = msg.html + "day are  <strong>" + hours + "</strong>.<br><hr><br>"
    msg.html = msg.html + "<a href='http://blacksburgfarmersmarket.com/'>Blacksburg Farmers Market</a> - <a href='https://www.google.com/maps/d/viewer?mid=1MX2R9crBm_cUD8yoACS_z_K-uCU&ll=37.22836360418549%2C-80.41460575000002&z=19'>100 Draper Rd NW, Blacksburg, VA 24060</a>"

    mail.send(msg)

    return redirect(url_for('emailsuccessdet'))
Exemple #48
0
def send_email(subject='ewen blog mail send system',
               recipients='*****@*****.**',
               body='Email captcha test'):
    message = Message(subject=subject, recipients=[recipients], body=body)
    mail.send(message)
    return 'Success'
Exemple #49
0
 def userRegisterRemind():
     mail = Mail(api_server)
     with api_server.app_context():
         message = Message(subject='AlanChat新用户注册提醒!', recipients=[api_server.config.get('MAIL_USERNAME'), ],
                           body='有新用户注册啦!')
         mail.send(message=message)
Exemple #50
0
def signup():
    if request.method == "GET":
        return render_template('index.html')
    name = request.form['name']
    surname = request.form['surname']
    username = request.form['username']
    email = request.form['email']
    password = request.form['password']
    passrep = request.form['passwordrepeat']
    bday = request.form['bday']
    if (name == '' or surname == '' or username == '' or email == ''
            or password == '' or passrep == '' or bday == ''):
        return render_template('index.html', error=-2)
    bday2 = re.search("([12]\\d{3}/(0[1-9]|1[0-2])/(0[1-9]|[12]\\d|3[01]))",
                      bday)
    if bday2:
        today = date.today()
        age = today.year - int(bday[0:4]) - ((today.month, today.day) <
                                             (int(bday[5:7]), int(bday[8:10])))
        if age > 17:
            result = col.find_one({"username": username})
            if result == None:
                result = col.find_one({"Email": email})
                if result == None:
                    if (re.match("[^@]+@[^@]+\\.[^@]+", email)):
                        matches = re.search(
                            "(?=^.{8,}$)((?=.*\\d)(?=.*\\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$",
                            password)
                        if (matches):
                            if password == passrep:
                                query = {
                                    "Pref": "0",
                                    "Verify": "0",
                                    "Matches": "",
                                    "Chats": "",
                                    "NewMessage": False,
                                    "Likes": "",
                                    "Dislikes": "",
                                    "Popularity": 0,
                                    "Blocked": "",
                                    "ProfileViews": "",
                                    "ProfileLikes": "",
                                    "ConnectionStatus": "",
                                    "Noti": "1",
                                    "Images": "",
                                    "Name": name,
                                    "Surname": surname,
                                    "Age": age,
                                    "Email": email,
                                    "username": username,
                                    "Password": hash_password(password)
                                }
                                col.insert_one(query)
                                msg = Message("Matcha Verification",
                                              sender="*****@*****.**",
                                              recipients=[email])
                                msg.body = "Hello {0}!\n\nYou have successfully signed up for Matcha!\nPlease click the link below to verify your account.\n\nhttp://localhost:5000/verify/{0}.\n\nThank you.\n".format(
                                    username)
                                mail.send(msg)
                            else:
                                return render_template('index.html', error=1)
                        else:
                            return render_template('index.html', error=4)
                    else:
                        return render_template('index.html', error=5)
                else:
                    return render_template('index.html', error=6)
            else:
                return render_template('index.html', error=7)
        else:
            return render_template('index.html', error=8)
    else:
        return render_template('index.html', error=9)
    return render_template('index.html', error=-1)
Exemple #51
0
def send_mail(subject, recipients, body):
    message = Message(subject=subject, recipients=recipients, body=body)
    mail.send(message)
def emailcart():
    user = User.query.filter_by(username=current_user.username).first()
    dayalt = datetime.datetime.strptime(session['day'],'%Y-%m-%d').strftime('%A %B %d, %Y')
    month = datetime.datetime.strptime(session['day'],'%Y-%m-%d').month
    weekday = datetime.datetime.strptime(session['day'],'%Y-%m-%d').weekday()
    if month in [4,5,6,7,8,9,10]:
        if weekday > 4:
            hours = "8am - 2pm"
        else:
            hours = "Noon - 6pm"
    elif month in [11,12]:
        if weekday > 4:
            hours = "9am - 2pm"
        else:
            hours = "Noon - 6pm"
    else:
        if weekday > 4:
            hours = "10am - 2pm"
        else:
            hours = "Noon - 6pm"

    q = (db.session.query(OrderTbl, Available, Product, User)
        .join(Available, OrderTbl.offerID==Available.offerID)
        .join(Product, Available.productID==Product.productID)
        .join(User, Available.sellerID==User.id)
        .filter(OrderTbl.custID==user.id, OrderTbl.isDeleted==False, Available.day==session['day'])
        .all())
    # above returns a list of tuples of the table row objects
    # e.g. [(<OrderTbl 1>, <Available 1>, <Product 2>, <User 1>), (<OrderTbl 3>, <Available 6>, <Product 3>, <User 2>), ... ]

    msg = Message(recipients=[user.email])
    msg.subject = "Blacksburg Farmers Market Order - " + dayalt

    msg.html = "<img src='http://fmportal.pythonanywhere.com/static/img/fmLogo.png' /> &nbsp; <img src='http://fmportal.pythonanywhere.com/static/img/fmMailBanner.png' /><br><br>"

    msg.html = msg.html + "Hi " + user.name + ",<br><br>"
    msg.html = msg.html + "Thanks for ordering items at the Blacksburg Farmers Market on <strong>" + dayalt + "</strong><br><br>"
    msg.html = msg.html + "Here is a summary of your order.<br><br>"
    msg.html = msg.html + "<table style='border: 1px solid black; border-collapse: collapse;'>"

    carttotal = 0
    for item in q:
        itemtotal = item[0].quantity * item[1].offerprice
        carttotal = carttotal + itemtotal
        if item[2].unit.lower()[:2] == "ea":
            s = ""
            per = ""
        else:
            s = "s"
            per = "per "

        msg.html = msg.html + "<tr style='border: 1px solid black; border-collapse: collapse;'>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse;'><img src='http://fmportal.pythonanywhere.com/static/img/P" + str(item[2].productID) + ".png' onerror='http://fmportal.pythonanywhere.com/static/img/defaultproduct.png' /></td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + item[2].description + "</td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'>" + str(item[0].quantity) + " " + item[2].unit + s + "@ " + "${:.2f}".format(item[1].offerprice) + " " + per + item[2].unit + "<br><br>"
        msg.html = msg.html + "Item total = <strong>" + "${:.2f}".format(itemtotal) + "</strong></td>"
        msg.html = msg.html + "<td style='border: 1px solid black; border-collapse: collapse; padding: 15px;'><strong>" + item[3].boothname + "</strong><br>" + item[3].name + "<br>" + item[3].telephone + "</td></tr>"

    msg.html = msg.html + "</table><br>"
    msg.html = msg.html + "Your total for all ordered items is <strong>" + "${:.2f}".format(carttotal) + "</strong><br><br>"
    msg.html = msg.html + "We look forward to seeing you on " + dayalt + ". Remember that our hours that day are <strong>" + hours + "</strong>.<br>"
    msg.html = msg.html + "When you arrive, please look for vendor's names on the signs on the front of their tables or above their booths.<br><hr><br>"
    msg.html = msg.html + "<a href='http://blacksburgfarmersmarket.com/'>Blacksburg Farmers Market</a> - <a href='https://www.google.com/maps/d/viewer?mid=1MX2R9crBm_cUD8yoACS_z_K-uCU&ll=37.22836360418549%2C-80.41460575000002&z=19'>100 Draper Rd NW, Blacksburg, VA 24060</a>"

    mail.send(msg)

    return redirect(url_for('emailsuccess'))
Exemple #53
0
def send_registration_token(email):
    s = Serializer(secret_key=current_app.config['SECRET_KEY'], expires_in=1800)
    token = s.dumps({"email": email}).decode("utf-8")
    msg = Message("Registration Request", sender=email, recipients=[email])
    msg.body = f"To confirm the registration process click the url gievn below: {url_for('users.register', token=token, _external=True)}"
    mail.send(msg)
Exemple #54
0
def charge_stripe(payment):
    logger.info("Charging Stripe payment %s, token %s", payment.id,
                payment.token)
    # If we fail to go from charging to charged, we won't have the charge ID,
    # so can't process the webhook. The payment will need to be manually resolved.
    # Test this with 4000000000000341.

    payment.state = 'charging'
    db.session.commit()
    payment = get_user_payment_or_abort(
        payment.id,
        'stripe',
        valid_states=['charging'],
    )

    # max 15 chars, appended to company name
    description = 'Tickets {}'.format(event_start().year)
    try:
        try:
            charge = stripe.Charge.create(
                amount=payment.amount_int,
                currency=payment.currency.lower(),
                card=payment.token,
                description=payment.description,
                statement_description=description,
            )
        except stripe.CardError as e:
            error = e.json_body['error']
            logger.warn('Card payment failed with exception "%s"', e)
            flash('Unfortunately your card payment failed with the error: %s' %
                  (error['message']))
            raise

        except Exception as e:
            logger.warn("Exception %r confirming payment", e)
            flash('An error occurred with your payment, please try again')
            raise

    except Exception:
        # Allow trying again
        payment.state = 'captured'
        db.session.commit()
        return redirect(url_for('.stripe_tryagain', payment_id=payment.id))

    payment.chargeid = charge.id
    if charge.paid:
        payment.paid()
    else:
        payment.state = 'charged'
        payment.expires = datetime.utcnow() + timedelta(
            days=app.config['EXPIRY_DAYS_STRIPE'])

    db.session.commit()

    logger.info('Payment %s completed OK (state %s)', payment.id,
                payment.state)

    # FIXME: determine whether these are tickets or generic products
    msg = Message("Your EMF ticket purchase",
                  sender=app.config.get('TICKETS_EMAIL'),
                  recipients=[payment.user.email])

    already_emailed = set_tickets_emailed(payment.user)
    msg.body = render_template("emails/tickets-purchased-email-stripe.txt",
                               user=payment.user,
                               payment=payment,
                               already_emailed=already_emailed)

    if feature_enabled('ISSUE_TICKETS') and charge.paid:
        attach_tickets(msg, payment.user)

    mail.send(msg)
    db.session.commit()

    return redirect(url_for('.stripe_waiting', payment_id=payment.id))
Exemple #55
0
def compress():

    #loads file from html
    videoFile = request.files['filename']

    #retrieve scale down/up factor
    resize_frame = int(request.form.get("scale_factor"))

    #retrieves email ID from html
    recipient_id = str(request.form.get("email"))

    #if invalid email is provided
    if not (re.search(regex, recipient_id)):
        return render_template("compress.html", text="Invalid Email Id")

    #contains filename
    fn = os.path.basename(videoFile.filename)

    #saving file in specified directory
    videoFile.save(
        os.path.join(app.config['UPLOAD_FOLDER'],
                     secure_filename(videoFile.filename)))

    #contains path where file is saved
    videoFile = os.path.join(app.config['UPLOAD_FOLDER']) + fn

    #dividing the file location into its filename and extension
    name, ext = os.path.splitext(videoFile)

    #checking whether the file is videofile or not
    allowed_extensions = [".mp4", ".mov", ".avi", ".webm", ".wmv", ".flv"]
    if (ext.lower() in allowed_extensions) == False:
        return render_template("compress.html",
                               text="not a video file extension")

    #capturing the vedio
    cap = cv2.VideoCapture(videoFile)

    #output file name
    output_vedio_file = "compressed_" + time.strftime("%Y%m%d_%H%M%S") + ext

    #making mp4 output vedio file
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')

    #Get frame per second of the vedio
    frame_per_second = cap.get(cv2.CAP_PROP_FPS)

    #get frame size
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    print(output_vedio_file)
    #scaling down/up the frame
    new_width = int(width * resize_frame / 100)
    new_height = int(height * resize_frame / 100)
    size = (new_width, new_height)

    #Initialize VedioWriter
    out = cv2.VideoWriter(output_vedio_file, fourcc, frame_per_second, size,
                          True)

    while (1):
        ret, frame = cap.read()
        if ret == False:
            break
        resizeFrame = cv2.resize(frame, size)
        out.write(resizeFrame)

    cap.release()
    out.release()

    try:
        return send_file(output_vedio_file, as_attachment=True)

        #Message Content that is to be emailed
        msg = Message(subject='Compressed video file',
                      recipients=[recipient_id],
                      body='Below is your required Compressed video File')

        #attaching gray scale video file
        with app.open_resource(output_vedio_file) as output_file:
            msg.attach(output_vedio_file, 'video/mp4', output_file.read())

        #sending mail
        mail.send(msg)

        return render_template(
            "compress.html",
            text=
            "Successfully mailed the Compressed videofile to your provided email id"
        )

    except Exception:
        return render_template(
            "compress.html",
            text=
            "Sorry!!! Unable to send to mail... Gmail have protections to avoid their service being used to deliver spam"
        )
Exemple #56
0
def sendamail(subjectformail, recipientslist, messagetosend):
    message = Message(subjectformail, recipients=recipientslist)
    message.html = messagetosend
    mail.send(message)
def send_email(to, subject, template):
    msg = Message(subject,
                  recipients=[to],
                  html=template,
                  sender=app.config['MAIL_DEFAULT_SENDER'])
    mail.send(msg)
Exemple #58
0
def _send_mail_task(**kwargs: str):
    mail.send(Message(**kwargs))
Exemple #59
0
def transfer(ticket_id):
    try:
        ticket = current_user.owned_purchases.filter_by(id=ticket_id).one()
    except NoResultFound:
        abort(404)

    if not ticket.is_paid_for:
        flash("Unpaid tickets cannot be transferred")
        return redirect(url_for('users.purchases'))

    if not ticket.product.get_attribute('is_transferable'):
        flash("This purchase cannot be transferred")
        return redirect(url_for('users.purchases'))

    form = TicketTransferForm()

    if form.validate_on_submit():
        email = form.email.data

        if not User.does_user_exist(email):
            new_user = True

            # Create a new user to transfer the ticket to
            to_user = User(email, form.name.data)
            db.session.add(to_user)
            db.session.commit()

        else:
            new_user = False
            to_user = User.get_by_email(email)

        ticket = Ticket.query.with_for_update().get(ticket_id)
        assert ticket.owner_id == current_user.id

        ticket.transfer(from_user=current_user, to_user=to_user)
        db.session.commit()

        app.logger.info('Ticket %s transferred from %s to %s', ticket,
                        current_user, to_user)

        # Alert the users via email
        code = to_user.login_code(app.config['SECRET_KEY'])

        msg = Message("You've been sent a ticket to EMF!",
                      sender=app.config.get('TICKETS_EMAIL'),
                      recipients=[to_user.email])
        msg.body = render_template('emails/ticket-transfer-new-owner.txt',
                                   to_user=to_user,
                                   from_user=current_user,
                                   new_user=new_user,
                                   code=code)

        if feature_enabled('ISSUE_TICKETS'):
            attach_tickets(msg, to_user)

        mail.send(msg)
        db.session.commit()

        msg = Message("You sent someone an EMF ticket",
                      sender=app.config.get('TICKETS_EMAIL'),
                      recipients=[current_user.email])
        msg.body = render_template('emails/ticket-transfer-original-owner.txt',
                                   to_user=to_user,
                                   from_user=current_user)

        mail.send(msg)

        flash("Your ticket was transferred.")
        return redirect(url_for('users.purchases'))

    return render_template('ticket-transfer.html', ticket=ticket, form=form)
Exemple #60
0
def send_mail(to, subject, template, **kwargs):
    msg = Message(subject, recipients=[to], sender=app.config['MAIL_USERNAME'])
    # print (msg)
    msg.html = render_template(template + '.html', **kwargs)
    mailobject.send(msg)