Esempio n. 1
0
 def send_test_email(cls):
     return requests.post(
         env('API_BASE_URL'),
         auth=("api", env('API_KEY')),
         data={"from": env('EMAIL_FROM'),
               "to": ["*****@*****.**", "*****@*****.**"],
               "subject": "Hello",
               "text": "Testing some Mailgun awesomness!"})
Esempio n. 2
0
    def send_sms(cls, from_name, to_name, to_phone, text):
        try:
            client = Client(
                env('ACCOUNT_SID'),
                env('AUTH_TOKEN'))

            message = client.messages.create(
                body='\nFrom: {}\nTo: {}\n{}'.format(from_name, to_name, text),
                from_=env('FROM_PHONE'),
                to=to_phone)
            return message.sid
        except TwilioRestException as ex:
            logging.getLogger('root').error('Error sending email to users using SMTP server.\n{}'.format(str(ex)))

        return False
Esempio n. 3
0
 def find_needing_update(cls,
                         minutes_since_last_update=env(
                             'ALERT_CHECK_INTERVAL', default=10)):
     last_update_limit = datetime.datetime.utcnow() - datetime.timedelta(
         minutes=int(minutes_since_last_update))
     return cls.query.filter(
         AlertModel.active == True,
         AlertModel.last_checked <= last_update_limit).all()
Esempio n. 4
0
def edit_alert(alert_id):
    alert = AlertModel.find_by_id(alert_id)

    if not alert:
        flash("Alert not found", category='error')
        return redirect(url_for('users.user_alerts'))

    curr_url = alert.item.url
    form = AlertForm(request.form)

    if request.method == 'POST' and form.validate():
        form.populate_obj(alert)
        alert.item.url = curr_url
        alert.save_to_db()

        user = UserModel.find_one(username=current_user.username)

        subject = "ALERT MODIFIED from Pricing Alert Service <{}>".format(
            env('EMAIL_FROM')),
        message = "New Price Alert has been updated for {}.<br>"
        "{} <{}> have setup this email address ({}) to receive alerts regarding prices"
        "drops over this product. <br/>"
        "You can now seat down and let us do "
        "the hard work".format(alert.item.name, user.name, user.username,
                               alert.contact_email)

        if not NotificationDispatcher.send_email(user.name,
                                                 user.username,
                                                 alert.contact_email,
                                                 subject=subject,
                                                 message=message):
            flash('Error sending email to {}. A notification has been '
                  'emitted to the system administrator'.format(
                      alert.contact_emaiil),
                  category='error')

        if alert.contact_phone is not None and alert.contact_phone != "":
            if not NotificationDispatcher.send_sms(
                    from_name="Pricing Alert Service",
                    to_phone=alert.contact_phone,
                    to_name=user.name,
                    text='New Alert for {} and price limit {} was added.'.
                    format(alert.item.name, alert.price_limit)):

                flash('Error sending SMS to {}. A notification has been '
                      'emitted to the system administrator'.format(
                          alert.contact_phone),
                      category='error')

        return redirect(url_for('users.user_alerts'))

    return render_template('store/edit_alert.html',
                           username=current_user.username
                           if current_user.username is not None else 'Buyer',
                           alert=alert)
Esempio n. 5
0
    def send_email_if_price_limit_reached(self):
        if self.item.price < self.price_limit:
            subject = "NEW ALERT FOR PRICE DROP from TechFitU <{}>".format(
                env('SMTP_USER')),
            message = "!Congratulations {}, you have a chance to save money !<br/>"
            "The product {} has dropped its price. "
            "Got to the product <a href='{}'>link</a> to see its currrent status"
            " You are a truly awesome prices hunter!".format(
                self.contact_email, self.item.name, self.item.url)

            return NotificationDispatcher.send_email(self.user.name,
                                                     self.user.username,
                                                     self.contact_email,
                                                     subject=subject,
                                                     message=message)

        return False
Esempio n. 6
0
from pricealerts import create_app
from pricealerts.db import db
from pricealerts.models import AlertModel
from apscheduler.schedulers.blocking import BlockingScheduler

from pricealerts.settings import env

sched = BlockingScheduler()


@sched.scheduled_job('interval',
                     seconds=env('ALERT_CHECK_INTERVAL', default=10))
def job():
    app = create_app()
    with app.app_context():
        db.init_app(app)
        alerts_needing_update = AlertModel.find_needing_update()

        for alert in alerts_needing_update:
            alert.load_price_change()
            alert.send_email_if_price_limit_reached()


sched.start()
Esempio n. 7
0
    def send_email(cls, user_name, user_email, to_email, subject, message, secure=None,
                   timeout=env('EMAIL_SEND_TIMEOUT', default=10)):
        """
        Send emails with Mailgun Rest API
        If Mailgun fails, this method use SMTP server mail.techfitu.com for sending emails
        Docs: http://blog.tecladocode.com/learn-python-send-emails/

        """
        response = requests.post(
            env('API_BASE_URL'),
            auth=("api", env('API_KEY')),
            data={"from": "{} <{}>".format(env('BRAND_NAME') + " - " + env('PRODUCT_NAME'), env('EMAIL_FROM')),
                  "to": [to_email, "{} <{}>".format(user_name, user_email)],
                  "subject": subject,
                  "html": message,
                  "text": "Testing some Mailgun awesomness!"
                  })

        # You can see a record of this email in your logs: https://app.mailgun.com/app/logs
        if response.status_code != 200:
            msg = EmailMessage()
            msg['From'] = "{} <{}>".format(env('BRAND_NAME') + " - " + env('PRODUCT_NAME'), env('EMAIL_FROM'))
            msg['To'] = ','.join([to_email, "{} <{}>".format(user_name, user_email)])
            msg['Subject'] = subject
            msg['Date'] = email.utils.localtime()
            msg.set_content(message)

            username = env('SMTP_USER', default=None)
            password = env('SMTP_PASS', default=None)
            port = int(env('SMTP_PORT', default=None))
            if not port:
                port = smtplib.SMTP_PORT

            try:
                if bool(env('SMTP_SSL', default=True)) == True:
                    smtp = smtplib.SMTP_SSL(env('SMTP_SERVER'), port, timeout=int(timeout))

                else:
                    smtp = smtplib.SMTP(env('SMTP_SERVER'), port, timeout=int(timeout))

                if username:
                    if secure is not None:
                        smtp.ehlo()
                        smtp.starttls(*secure)
                        smtp.ehlo()
                    smtp.login(username, password)
                smtp.send_message(msg)
                smtp.quit()
            except Exception as ex:
                logging.getLogger('root').error('Error sending email to users using SMTP server.\n{}'.format(str(ex)))
                return False



        return True
Esempio n. 8
0
def create_alert():
    form = AlertForm()

    if request.method == 'GET':
        return render_template('store/new_alert.html', form=form)

    validate = form.validate_on_submit(
    )  # This is a shortcut for form.is_submitted() and form.validate().
    if validate:

        # Request method is POST
        prod_url = form.url.data
        # store_id = int(request.form['store_id'])
        price_limit = float(form.data['price_limit'])
        check_frequency = int(form.data['check_frequency'])
        alert_email = form.data['alert_email']
        alert_phone = form.data['alert_phone']

        active = bool(form.data['active'])

        user = UserModel.find_one(username=current_user.username)

        try:
            store = StoreModel.find_by_url(prod_url)
        except StoreNotFoundError:
            only_title = SoupStrainer('title')
            # Find the store on Internet
            from urllib.parse import urlparse
            o = urlparse(prod_url)

            if o.netloc is None:
                location = o.path.split('/')[0]
            else:
                location = o.netloc

            store_url = o.scheme + "://" + location
            req = requests.get(store_url)
            html_doc = req.content
            soup = BeautifulSoup(html_doc,
                                 'html.parser',
                                 parse_only=only_title)

            store = StoreModel(soup.title.string, store_url).save_to_db()

        # Create the item
        item = ItemModel(prod_url, store_id=store.id)

        try:
            item.name, item.price, item.image = item.load_item_data()
        except ItemNotLoadedError as ex:
            flash(ex.message, category='error')
            return redirect(url_for('users.user_alerts'))

        item.save_to_db()

        # Create the alert
        alert = AlertModel(price_limit,
                           item.id,
                           user.id,
                           check_every=check_frequency,
                           contact_email=alert_email,
                           contact_phone=alert_phone,
                           active=active).save_to_db()

        subject = "NEW ALERT CREATED from Pricing Alert Service <{}>".format(
            env('SMTP_USER')),
        message = "New Price Alert has been created for {}.<br>{} <{}> have setup this email address ({})" \
                  "to receive alerts regarding prices drops over this product. <br/>You can now seat down" \
                  "and let us do the hard work".format(item.name, user.name, user.username, alert_email)

        if not NotificationDispatcher.send_email(user.name,
                                                 user.username,
                                                 alert.contact_email,
                                                 subject=subject,
                                                 message=message):
            flash('Error sending email to {}. A notification has been '
                  'emitted to the system administrator'.format(
                      alert.contact_email),
                  category='error')

        if alert.contact_phone is not None and alert.contact_phone != "":
            if not NotificationDispatcher.send_sms(
                    from_name="Pricing Alert Service",
                    to_phone=alert.contact_phone,
                    to_name=user.name,
                    text='New Alert for {} and price limit {} was added.'.
                    format(alert.item.name, alert.price_limit)):

                flash('Error sending SMS to {}. A notification has been '
                      'emitted to the system administrator'.format(
                          alert.contact_phone),
                      category='error')

        # After saving all data redirect to user alerts page
        return redirect(url_for('users.user_alerts'))

    return render_template('store/new_alert.html', form=form)