Beispiel #1
0
def fetch(gse="GSE25935", gpl=None, email_addr):
  """Fetch GSE study, send email.

  Args:
    gse: str of GSE ID
    gpl: str of GPL ID
    email_addr: email address to which to send results
  """
  g = GSE(gse, platform_id=gpl)
  if gpl is None:
    gpl = g.platform.id
  filt2 = EQTLFilter(g)
  
  # Open output file
  filename = "%s.%s.tab.gzip" % (gse, gpl)
  fp = gzip.open("%s/%s" % (PATH, filename), "wb")

  # Write output file
  for row in filt2.get_rows():
    fp.write("\t".join(row) + "\n")
  fp.close()

  # Send email announcing results
  link = "http://www.automaticgradstudent.com/data/%s" % filename
  text = "Download study %s. %s" % (gse, link)
  subject = "%s ready for download." % gse
  emailer.send_email("*****@*****.**", [email_addr], subject, text)
 def execute_trade(self, volume, kask, kbid, weighted_buyprice, weighted_sellprice):
     self.last_trade = time.time()
     logging.info("Buy @%s %f BTC and sell @%s" % (kask, volume, kbid))
     send_email("Bought @%s %f BTC and sold @%s" % (kask, volume, kbid),
                "weighted_buyprice=%f weighted_sellprice=%f" % (weighted_buyprice, weighted_sellprice))
     self.clients[kask].buy(volume)
     self.clients[kbid].sell(volume)
Beispiel #3
0
def broadcast_ip():
    global config_data
    with open('/etc/arduino_log.json') as data_file:
        config_data = json.load(data_file)

    if config_data["broadcast_ip"]:
        while config_data["iface"] not in all_interfaces():
            print "`{0}' not found.".format(config_data["iface"])
            time.sleep(15)

        message = """
        <html>
          <head></head>
          <body>
            <img src=\"http://icons.iconarchive.com/icons/alecive/flatwoken/512/Apps-Dialog-Shutdown-icon.png\" height=\"64\" width=\"64\">
            <p>IP:""" + get_ip_address(str(config_data["iface"])) + """
            </p>
          </body>
        </html>
            """
        emailer.send_email(config_data["smtp_server"],
                           config_data["sender"],
                           config_data["eml_passwd"],
                           [config_data["recipients"][0]],
                           "Unit: " + config_data["unit"] + " booted.",
                           message)

    else:
        print("Not sending...")
Beispiel #4
0
def email_post():
    to = request.form['email_to']
    subject = request.form['email_subject']
    message = request.form['email_message']
    send_email(to, subject, message)
    flash("Email Sent Successfully")
    return render_template("email.html")
Beispiel #5
0
def mobile_register():
    if request.method == 'POST':
        hashed_password = bcrypt.hashpw(
            request.form['password'].encode('utf-8'),
            bcrypt.gensalt()).decode('utf-8')
        new_user = Users(displayname=request.form['displayname'],
                         email=request.form['email'],
                         password=hashed_password,
                         firstName=request.form['firstname'],
                         lastName=request.form['lastname'],
                         activated=0,
                         dateOfBirth=None,
                         dateCreated=datetime.utcnow())
        db.session.add(new_user)
        db.session.commit()
        token = generate_confirmation_token(new_user.email)

        confirm_url = 'https://wocpr.com/confirm/' + token
        html = render_template('confirmationEmail.html',
                               confirm_url=confirm_url)
        subject = "What's On Campus - Confirm your email"
        send_email(new_user.email, subject, html)

        access_token = create_access_token(identity=request.form['email'],
                                           expires_delta=False)
        return jsonify(access_token=access_token,
                       displayname=request.form['displayname']), 201
    else:
        return jsonify(response="Error has occured"), 500
Beispiel #6
0
    def command(self):
        self._load_config()
        log = logging.getLogger('ckanext.opendatani')

        log.info('Daily dataset update frequency check started...')

        def frequency_to_timedelta(frequency):
            frequency_periods = {
                "daily": dt.timedelta(
                    days=2
                ),  # 2 so as not to spam dataset maintainers every day
                "weekly": dt.timedelta(days=7),
                "fortnightly": dt.timedelta(days=14),
                "monthly": dt.timedelta(days=30),
                "quarterly": dt.timedelta(days=91),
                "annually": dt.timedelta(days=365),
            }
            if not frequency:
                pass
            else:
                return frequency_periods[frequency]

        data = toolkit.get_action('package_search')({
            'ignore_auth': True
        }, {
            'include_private': True,
            'rows': 10000000
        })
        if data['results']:
            for pkg in data['results']:
                if 'frequency' in pkg:
                    pkg['metadata_created'] = h.date_str_to_datetime(
                        pkg['metadata_created'])
                    pkg['metadata_modified'] = h.date_str_to_datetime(
                        pkg['metadata_modified'])
                    pkg['frequency'] = pkg.get('frequency', '')
                    if pkg['frequency']:
                        if pkg['frequency'] != 'irregular' and pkg[
                                'frequency'] != 'notPlanned':
                            if pkg['metadata_modified'].date(
                            ) != pkg['metadata_created'].date():
                                now = dt.datetime.now()
                                diff = now - pkg['metadata_modified']
                                if diff > frequency_to_timedelta(
                                        pkg['frequency']):
                                    try:
                                        content = "Dataset " + pkg[
                                            'title'] + " has not been updated in its planned update frequency (" + pkg[
                                                'frequency'] + ")."
                                        to = pkg['contact_email']
                                        subject = "Open Data NI: Update dataset notification"
                                        emailer.send_email(
                                            content, to, subject)
                                        log.info(
                                            'Package "' + pkg['title'] +
                                            '" has not been updated. Sending e-mail to maintainer.'
                                        )
                                    except Exception as e:
                                        log.error(e)
        log.info('Daily dataset update frequency check completed.')
def main():

    # Read email contents. Log.
    fp = open('/home/yates/app_logs/emails.txt', 'a')
    data = sys.stdin.read()
    fp.write(data)
    fp.close()

    # Parse email.
    msg = email.message_from_string(data)
    from_addr = msg['From']
    
    m = RX_GSE.search(data)
    if m is not None:
        gse = m.group(0)
    else:
        gse = None
        
    m = RX_GPL.search(data)
    if m is not None:
        gpl = m.group(0)
    else:
        gpl = None


    if gse:
        p = subprocess.Popen(['python2.7', '%s/fetch_geo.py' % APP_PATH, gse, "%s" % gpl, from_addr])
    else:
        emailer.send_email("*****@*****.**", [from_addr], "FETCH FAILED", "FAILED EMAIL: %s" % email)
Beispiel #8
0
def send_notice(send):
    global msg
    msg = ''
    for i in range(0, 5):
        msg += f'{notices["titles"][i]}\n'
        msg += f'{notices["contents"][i]}\n\n'
    if send == '1':
        for i in range(0, 5):
            print(colored(notices['titles'][i], 'green'))
            print(colored(notices['contents'][i], 'yellow'))
            print('\n')
            print(colored('Essas foram as notícias.', 'blue'))
    elif send == '2':
        txt = open('notícias.txt', 'w', encoding='utf-8')
        for i in range(0, 5):
            txt.write(f'{notices["titles"][i]}\n')
            txt.write(f'{notices["contents"][i]}\n\n')
            print(
                colored('As notícias foram salvas em "notícias.txt".', 'blue'))
    elif send == '3':
        email = input('Informe seu e-mail: ')
        send_email(email, msg, types[type_notice])
        print(colored('As notícias foram enviadas.', 'blue'))
    elif send == '4':
        link = link_gen('Notícias', msg)
        print('\nLink para acessar as notícias: ', end='')
        print(colored(link, 'blue'))
Beispiel #9
0
def JOHN_CENA(user_email):
    subject = f"Hello, {user_email}"
    message = ("Hello M8 :)")

    message = message.format(username=user_email)
    send_email(user_email, message, subject)
    return f"OKAY - email sent to {user_email}"
Beispiel #10
0
def run():
    print 'Running'
    _create_storage_dir()

    # gather data, odds and predictions
    print 'Gathering todays matchup data and odds'
    data_matchups = _get_data_matchups()
    odds_matchups = get_todays_odds()
    merged_matchups = _combine_matchup_sets(data_matchups, odds_matchups)
    predicted_matchups = _add_predictions_to_matchups(merged_matchups)
    ready_matchups = _process_matchups(predicted_matchups)
    print 'Saving todays matchups to json file'
    _save_matchups(datetime.date.today(), ready_matchups)

    # how did we do yesterday, add to results
    print 'Finding previous matchup data'
    previous_matchups = _get_previous_matchups()
    print 'Supplementing matchups with results'
    matchups_with_results = _add_results_to_matchups(previous_matchups)
    running_results = _include_in_results(matchups_with_results)
    print 'Overwriting matchups in previous json file'
    _overwrite_previous_results(matchups_with_results)

    # send an email to peeps who wanna know
    print 'Sending result email'
    send_email(ready_matchups, matchups_with_results, running_results,
               SETTINGS)
def send_reminder(employee, not_completed_trainings):
    name = f"{employee['First name']} {employee['Last name']}"
    recipient = employee["Email"]
    subject = "Remember to complete your training!"
    body = (
        f"Hi, {name}! "
        f"Remember to complete these trainings: {not_completed_trainings}.")
    emailer.send_email(recipient, subject, body)
Beispiel #12
0
def minecraft():
    to_address = "*****@*****.**"
    message = "{} IS THE BEST MINECRAFT CHARCATER EVER!!".format(
        os.environ.get('best_minecraft_character'))
    subject = "{}".format(os.environ.get('best_minecraft_character'))
    send_email(to_address, message, subject)
    return "CHECK UR EMAIL TO SEE WHO THE BEST MINECRAFT CHARACTER IS (IT'S {})".format(
        os.environ.get('best_minecraft_character'))
Beispiel #13
0
def email_post():
    firstname= request.form["firstname"]
    email = request.form["email"]
    exerhours=request.form["exerhours"]
    print(firstname)
    print(email)
    print(exerhours)
    send_email(email,firstname,exerhours)
    return render_template("sqlmailaddList.html")
Beispiel #14
0
def dailylog():
    account_body = ''
    email_subject = "FCB Daily Log | "+str(datetime.date.today())
    with open('accountlog.txt', 'r') as accountlog:
        account_body = accountlog.read()
    data_today = account_body

    data_body = account_body + 'Date: '+str(datetime.date.today())
    data_body = data_body.replace('\n', '|')
    data_body = data_body.replace(': ', ':')
    data_body = data_body.replace('$', '')
    data_body = data_body.replace(',', '')

    with open('datalog.txt', 'a+') as datalog:
        datalog.write(data_body+'\n')

    account_data = []
    with open('datalog.txt', 'r') as datalog:
        account_data = datalog.read().splitlines()

    num_days = sum(1 for line in account_data)

    account_dict = defaultdict(list)

    for day in account_data:
        day_data = day.split("|")
        for account_info in day_data:
            account_parse = account_info.split(':')
            account_dict[account_parse[0]].append(account_parse[1])

    dict_key = list(account_dict.keys()) #[0] is dates, rest is accounts

    dates = account_dict[dict_key[0]]
    x = [datetime.datetime.strptime(d,'%Y-%m-%d').date() for d in dates]

    for i in range(1, len(dict_key)):
        plt.clf()
        account_money = account_dict[dict_key[i]]

        plt.plot(x,account_money)
        # beautify the x-labels
        plt.title(dict_key[i])
        plt.ylabel('Amount Available ($)')
        plt.xlabel('Date (dd/mm/yyyy)')

        plt.gca().yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))

        plt.gca().xaxis.set_major_formatter(mpdates.DateFormatter('%d/%m/%Y'))
        plt.gca().xaxis.set_major_locator(mpdates.DayLocator())
        plt.gcf().autofmt_xdate()

        figname = "graphs/fig"+str(i)+".png"
        plt.savefig(figname, bbox_inches='tight')

    send_email(account_email, email_subject, data_today, True)
Beispiel #15
0
def build_email(template, success, config_file_path, **kwargs):
    #an email needs a host, port, subject, message, from, to, and maybe type (html/txt)
    if success:
        subject = 'Log for site {site} has been successfully processed'
    else:
        subject = 'Log for site {site} was unable to be processed'

    subject = subject.format(**kwargs)

    send_email(subject, template, config_file_path)
    print("Email sent\n")
Beispiel #16
0
def send_something(user_email):
    subject = f"Hello, {user_email}"
    message = """
    Hi, {username},


    Click <a href="http://127.0.0.1:33507/">this link</a> to return to our website.
  """
    message = message.format(username=user_email)
    send_email(user_email, message, subject)
    return f"OKAY - email sent to {user_email}"
Beispiel #17
0
def send_email(email):
    form = LoginForm()
    if email == "None":
        return render_template('login.html',
                               text='Пожалуйста, введите email',
                               form=form)
    if not users_base.get_by_email(email):
        return render_template(
            'login.html',
            text='Пользователь с введённой вами почтой не зарегистрирован',
            form=form,
            email=form.email.data)
    send_email(email, "Вау это работает")
Beispiel #18
0
def contactform():
    session['valid'] = True
    contactform = request.form
    sender_email = contactform['email']
    subject = contactform['subject'] + f" by: {sender_email}"
    msg = contactform['message']
    if email == "" or subject == "" or msg == "":
        session['valid'] = False
    else:
        email.send_email(subject, msg, '*****@*****.**', 'hackathon2020',
                         '*****@*****.**')
        session['email_sent'] = True
        return redirect('/#footer')
    return redirect('/#footer')
Beispiel #19
0
def log_errors(e, errors, max_errors, api, term, query, until_date, since_id,
               save_freq, local_filestore, num_iterations, testing_mode):
    """
    Log errors to file errors.log and prints them to screen.
    If called more 5 times, return break status for out of scope loop.
    """
    # Write to file
    with open(os.path.join(DIR_PATH, 'errors.log'), 'a+') as f:
        f.write('Exception raised in tweet_search.\n')
        f.write('Dumping vars:\n')
        for name, var in zip(
                'api, query, until_date, since_id, save_freq, local_filestore, num_iterations'
                .split(', '), [
                    api, query, until_date, since_id, save_freq,
                    local_filestore, num_iterations
                ]):
            f.write('{} = {}\n'.format(name, var))
        f.write('Dumping error:\n')
        f.write('{}\n'.format(e))
        f.write('-' * 25 + '\n')

    # Write to stdout
    print('Exception raised in tweet_search')
    msg = []
    for name, var in zip(
            'api, query, until_date, since_id, save_freq, local_filestore, num_iterations'
            .split(', '), [
                api, query, until_date, since_id, save_freq, local_filestore,
                num_iterations
            ]):
        msg.append('{}={}'.format(name, var))
    print('\n'.join(msg))
    print(e)

    # Send email
    send_email(
        subject='Exception raised in twitter_search.py',
        msg=('Exception raised in tweet_search function of twitter_search.py. '
             '<br><br><b>Date</b> = {}'
             '<br><br><b>Error:</b> <br>{}'
             '<br><br><b>Vars:</b> <br>{}'.format(datetime.datetime.now(), e,
                                                  '<br>'.join(msg))),
        destination_emails=['*****@*****.**'])

    # Break the loop if too many errors - to avoid infinite loops
    errors += 1
    if errors > max_errors:
        return 'break', errors

    return 'continue', errors
def send_email_for_completion(platform, email_est_time, prospect,
                              email_table_body, email_recipients):

    email_subject = EMAIL_SUBJECT_TEMPLATE.format(platform, prospect,
                                                  email_est_time)
    email_header = EMAIL_HEADER_TEMPLATE.format(platform, email_est_time,
                                                prospect)
    # email_body = email_table_body

    # print(email_header)
    # print(email_table_body)

    eml.send_email(prospect, email_subject, email_header, email_table_body,
                   email_recipients)
Beispiel #21
0
def resendActivation(token):
    email = getTokenEmail(token)
    user = db.session.query(Users).filter_by(email=email).first()

    if user:
        token = generate_confirmation_token(user.email)

        confirm_url = 'https://wocpr.com/confirm/' + token
        html = render_template('confirmationEmail.html',
                               confirm_url=confirm_url)
        subject = "What's On Campus - Confirm your email"
        send_email(user.email, subject, html)
        return jsonify(success=True, response="Activation email sent!"), 201
    else:
        return jsonify(success=False, response="Email doesn't exists"), 400
Beispiel #22
0
def notify(incident):
    if c.config.getVal('console.email_notification_enable', False):
        logger.debug('Email notifications enabled')
        addresses = c.config.getVal('console.email_notification_address', default=[])
        if c.config.getVal('console.mandrill_key', False):
            for address in addresses:
                logger.debug('Email sent to %s' % address)
                mandrill_send(to=address,
                              subject=incident.format_title(),
                              message=incident.format_report())
        else:
            from_ = c.config.getVal('console.email_from', default='*****@*****.**')
            server = c.config.getVal('console.email_host', default='')
            port = int(c.config.getVal('console.email_port', default=25))
            username = c.config.getVal('console.email_username', default='')
            password = c.config.getVal('console.email_password', default='')
            use_ssl = c.config.getVal('console.email_ssl', default='False') == 'True'
            starttls = c.config.getVal('console.email_starttls', default='False') == 'True'
            if len(addresses) > 0 and server:
                for address in addresses:
                    send_email(from_=from_,
                               to=address,
                               subject=incident.format_title(),
                               message=incident.format_report(),
                               server=server,
                               port=port,
                               username=username,
                               password=password,
                               use_ssl=use_ssl,
                               starttls=starttls)

    if c.config.getVal('console.sms_notification_enable', default=False):
        logger.debug('SMS notifications enabled')
        sms = SMS()
        sms_numbers = c.config.getVal('console.sms_notification_numbers', [])
        for to in sms_numbers:
            logger.debug('SMS sent to %s' % to)
            sms.send(to, incident.format_report_short())

    if c.config.getVal('console.slack_notification_enable', default=False):
        logger.debug('Slack notifications enabled')
        webhooks = c.config.getVal('console.slack_notification_webhook', default=[])
        for to in webhooks:
            response = requests.post(
                to, json={"text": incident.format_report_short()}
                )
            if response.status_code != 200:
                logger.error("Error %s sending Slack message, the response was:\n%s" % (response.status_code, response.text))
Beispiel #23
0
def driver(keywords_list, to_address):
    d_files = glob.glob("download_files/*.*")
    for d_file in d_files:
        print(d_file)
        try:
            d_file_text = textract.process(d_file)
        except:
            d_file_text = ""
        for keyword in keywords_list:
            with open("sent.json") as f:
                sent = json.load(f)
            if check_keyword(keyword, d_file_text) > 0 and d_file not in sent:
                print("Match found. Sending email.")
                add_sent(d_file)
                send_email(d_file, to_address, keyword)
            sent = sent["done"]
def monitor_stocks(tickers,
                   sender,
                   recipients,
                   notify_percent_increase=0.01,
                   notify_percent_decrease=-0.01,
                   sleep_time=30 * 5):
    """
    Monitor stock prices over the course of a day.
    :param tickers: list of tickers to monitor.
    :param sender: Email sender
    :param recipients: Email list of recipients
    :param notify_percent_increase: Max increase to notify at.
    :param notify_percent_decrease: Max decrease to notify at.
    :param sleep_time: Time between stock price checks.
    """
    ticker_map = {
        ticker: {
            'open': 0,
            'close_prices': [],
            'notify_percent_increase': notify_percent_increase,
            'notify_percent_decrease': notify_percent_decrease
        }
        for ticker in tickers
    }
    print('Staring monitoring for {0}'.format(', '.join(tickers)))
    get_open_price(ticker_map)
    time.sleep(10)
    while True:
        email = ''
        for ticker in ticker_map.keys():
            print('#' * 15, '\n', 'Checking {0}'.format(ticker.upper()))
            try:
                close = float(download_stock(ticker)['Close'][-1])
                ticker_map[ticker]['close_prices'].append(close)
            except Exception as e:
                print(e)
                continue

            email += compare_close_price(ticker_map[ticker], ticker)
        if email:
            print('Sending Email')
            send_email(sender,
                       recipients, {'text': email},
                       subject='Stock change')
        print_next_run_time(sleep_time)
        time.sleep(sleep_time)
Beispiel #25
0
def inform_ip():
	f = os.popen('ifconfig wlan0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
	ip=f.read()
	print ip
	
	try:
		fo = open('email_config.txt', "r")
		lines = fo.readlines()
		fo.close()
		
		sourceEmail = lines[0]
		sourcePass = lines[1]
		destEmail = lines[2]
		
		emailer.send_email(sourceEmail, sourcePass, destEmail, "Robot IP", "RoPiRemote: http://" + ip + "\r\n\r\n" + ip)
	except:
		print "Unexpected error:", sys.exc_info()[0]
def my_form_post():
    sender = request.remote_addr
    if not TimeOut.timed_out(sender, __name__):
        return "You must wait before sending another message."
    else:
        TimeOut.add(sender, __name__, 5)

    sender = request.form['from']
    subject = request.form['subject']
    message = request.form['message']
    answer = request.form['answer']
    code = request.form['code']

    if Captcha.check_answer(code, answer):
        emailer.send_email(sender, subject, message)
        return "correct!"
    else:
        return "wrong!"
Beispiel #27
0
def resetPassword(token):
    if token:
        try:
            email = confirm_token(token)
            newPassword = request.form['newPassword']
            confirmPassword = request.form['confirmPassword']

            user = db.session.query(Users).filter_by(email=email).first()

            if newPassword == confirmPassword:
                hashed_password = bcrypt.hashpw(
                    newPassword.encode('utf-8'),
                    bcrypt.gensalt()).decode('utf-8')
                user.password = hashed_password
                db.session.commit()
                return jsonify(success=True,
                               response="Successfully changed password!"), 201
            else:
                return jsonify(
                    success=False,
                    response="Confirm password doesn't match new password"
                ), 400
        except:
            return jsonify(response="The reset link is invalid or has expired",
                           success=False), 201

    else:
        email = request.form['email']
        user = db.session.query(Users).filter_by(email=email).first()

        if user:
            token = generate_confirmation_token(user.email)

            confirm_url = 'https://wocpr.com/resetpassword/' + token
            html = render_template('resetPasswordEmail.html',
                                   confirm_url=confirm_url)
            subject = "What's On Campus - Reset your password"
            send_email(user.email, subject, html)
            return jsonify(success=True,
                           response="Reset password email sent!"), 201
        else:
            return jsonify(success=False, response="Email doesn't exists"), 400
Beispiel #28
0
	def save(self, *args, **kwargs):
		#Set email template if unset
		if self.email_template == "":
			self.email_template = random.choice(self.EMAIL_TEMPLATES)[0]

		super(SurveyPriv, self).save(*args, **kwargs)

		try:
			self.pub
		except:
			self.pub = random.choice(SurveyPub.__subclasses__())()
			self.pub.save()

		#If email hasn't been sent... send it.
		if not self.is_email_sent():
			try:
				send_email(self)
				self.email_sent_on = timezone.now()
			except SMTPAuthenticationError as e:
				pass #Message is displayed in admin interface if this is an issue.

		super(SurveyPriv, self).save(*args, **kwargs)
Beispiel #29
0
def check_dashboard():
    email_file = open('email.txt', 'r')
    email_info = email_file.readline()
    email_file.close()

    reset_file = open('reset.txt', 'r')
    reset_info = reset_file.readline()
    reset_file.close()

    if '*' not in email_info:
        emailer.send_email(email_info)
        # overwrite file with '*'
        email_file = open('email.txt', 'w')
        email_file.write('*')
        print("email sent")

    if '1' in reset_info:
        canvas.fill(WHITE)
        pygame.image.save(canvas, IMAGE_NAME)
        reset_file = open('reset.txt', 'w')
        reset_file.write('0')
        print("canvas cleared")
Beispiel #30
0
def __on_turn_heater_on(rq_temp):
    current_temp = temp_sensor.value()
    __logger.debug("Current temperature={}".format(current_temp))

    if current_temp > __MAX_ALLOWED_TEMP:
        __on_turn_heater_off()
        message = "Current temperature <<{}>> is bigger then max allowed <<{}>>. Disabling heater" \
            .format(current_temp, __MAX_ALLOWED_TEMP)
        __logger.warn(message)
        emailer.send_email(message)

    elif current_temp > rq_temp:
        __logger.debug(
            "Current temperature <<{}>> is bigger then <<{}>> requested. Turning heater off"
            .format(current_temp, rq_temp))
        __on_turn_heater_off()

    else:
        __logger.debug(
            "Turning/keeping heater on (requested temperature={}".format(
                rq_temp))
        heater.turn_on()
Beispiel #31
0
def post_status(room_id):
    # print request.get_json()
    update_status = request.get_json()
    # update statuses
    status = statuses.get(room_id)

    # update given fields
    if update_status.get("status"):
        status.status = update_status.get("status")
        status.timestamp = utils.get_currrent_time_str()
        if update_status.get("status") == "FIRE":
            print "fire alert!"
            emailer.send_email(
                "[email protected], [email protected], [email protected], [email protected]",
                "FIRE Alert! [%s]" % room_id,
                "Status Details: \n" + utils.to_json(status))
    if update_status.get("occupancy"):
        status.occupancy = update_status.get("occupancy")
    # if update_status.get("carbon_detected"):
    if "carbon_detected" in update_status:
        status.carbon_detected = update_status.get("carbon_detected")

    return utils.to_json({"Update": True})
Beispiel #32
0
def post_status(room_id):
    # print request.get_json()
    update_status = request.get_json()
    # update statuses
    status = statuses.get(room_id)

    # update given fields
    if update_status.get("status"):
        status.status = update_status.get("status")
        status.timestamp = utils.get_currrent_time_str()
        if update_status.get("status") == "FIRE":
            print "fire alert!"
            emailer.send_email(
                "[email protected], [email protected], [email protected], [email protected], [email protected]",
                "FIRE Alert! [%s]" % room_id, "Status Details: \n" + utils.to_json(status))
            # send_message("9492664065", "There is FIRE at room [%s]!" % (room_id))
    if update_status.get("occupancy"):
        status.occupancy = update_status.get("occupancy")
    # if update_status.get("carbon_detected"):
    if "carbon_detected" in update_status:
        status.carbon_detected = update_status.get("carbon_detected")

    return utils.to_json({"Update": True})
Beispiel #33
0
        self.favorite_thing = favorite_thing


info1 = EmailData('Zach', 'Ethan', 'Michael', '*****@*****.**',
                  'quinceañera', 'The Cheesecake Factory',
                  'their pretty little cupcakes')
info2 = EmailData('Elyse', 'Zach', 'Ruth', '*****@*****.**',
                  'first-grade graduation', 'Chuck-E-Cheese',
                  'terrible pizza and sticky booths')

info_list = [info1, info2]

message_template = """
Hi {to_name},

I would like to invite you to {about_name}'s' {occasion}! We will be celebrating at {location} because, as you know, {about_name} loves {favorite_thing}.

Best wishes, {from_name}
"""
subject_template = "Hi {to_name}! You're invited..."

for info in info_list:
    message = message_template.format(to_name=info.to_name,
                                      about_name=info.about_name,
                                      occasion=info.occasion,
                                      location=info.location,
                                      favorite_thing=info.favorite_thing,
                                      from_name=info.from_name)
    subject = subject_template.format(to_name=info.to_name)
    send_email(info.to_address, message, subject)
Beispiel #34
0
    return ips


attacks = None
if args.load:
    attacks = load(args.load)

if attacks is None:
    attacks = dict()

whitelist = []
if args.whitelist:
    whitelist = open_whitelist(args.whitelist)

attacks = log_parser.parse(args.kippo, attacks, whitelist)

attacks = find_abuse_emails(attacks)

for key, value in attacks.items():
    if len(value.abuse_emails) != 0 and value.sent_notifications == 0:
        attack = emailer.send_email(value.abuse_emails[0], args.email, args.password, value)
        #attack = emailer.send_email("*****@*****.**", args.email, args.password, value)
        attack.sent_notifications = attack.attempts
        attacks[key] = attack

if args.save:
    if save(args.save, attacks):
        module_logger.info("The attacks were saved to file: %s" % args.save)
    else:
        module_logger.error("Could not write too: %s" % args.save)
Beispiel #35
0
import time
import emailer

time.sleep(5)
fp = open("Hello.%d.txt" % int(time.time()), "w")
fp.write("Sup.")
fp.close()

emailer.send_email("*****@*****.**", ["*****@*****.**"], subject="Test Email", text="Sup, dude.")
Beispiel #36
0
def checkbank():
    phantomjs_executable = ''
    if os.name=='nt': phantomjs_executable = "phantomjs.exe"
    else: phantomjs_executable = "phantomjs"
    phantomjs = os.path.realpath(os.path.join(os.getcwd(), phantomjs_executable))
    browser = webdriver.PhantomJS(phantomjs)
    url = r"https://www.firstcitizenstt.net/"

    browser.get(url)

    username = browser.find_element_by_name('userName')
    username.send_keys(account_number)
    password = browser.find_element_by_name('password')
    password.send_keys(account_password)

    form = browser.find_element_by_id('noautocomplete')
    form.submit()

    url = r"https://www.firstcitizenstt.net/accountList.do"
    browser.get(url)
    response = browser.page_source
    soup = BeautifulSoup(response, "html.parser")

    #TOTAL BALANCE
    total_balance = []
    total_balance_type = []
    total_balance_amount = []
    for td in soup.find_all('div', {'class': 'column'}):
        for span in td.find_all('dt'):
            total_balance_type.append(span.text)
        for span in td.find_all('dd'):
            total_balance_amount.append(span.text)
    total_balance = zip(total_balance_type, total_balance_amount)

    browser.quit();

    #GET CURRENT BALANCE
    total_available = []
    total_available_type = []
    total_available_amount = []
    alltr =  soup.find_all("tr", {"class":["odd", "even"]},recursive=True)
    for tr in alltr:
        total_available_type.append(tr.contents[1].get_text())
        total_available_amount.append(tr.contents[-1].get_text())
    total_available = zip(total_available_type, total_available_amount)

    email_subject = ""
    email_body = ""
    '''
    for amount in total_balance:
        email_body+= (amount[0]+": "+amount[1]+"\n")
    email_body+="\n"
    '''
    for amount in total_available:
        email_body+= (amount[0]+": "+amount[1]+"\n")
        email_subject += (amount[0]+": "+amount[1]+" | ")

    email_subject = email_subject[:-2] + " - FCB"
    email_subject = "FCB Account Update"

    account_body = ""
    with open('accountlog.txt', 'r') as accountlog:
        account_body = accountlog.read()

    if account_body != email_body:
        with open('accountlog.txt', 'w') as accountlog:
            accountlog.write(email_body)
        send_email(account_email, email_subject, email_body, False)
Beispiel #37
0
        logging.info('Running')
        try:
            # gets list of all artists from users public playlists
            all_artists = get_all_artists_names(spot)

            # gets list with all artist information for today
            curr_artist_info = get_all_artists_info(spot, all_artists)

            # gets the list of artists with new albums
            artists_with_new_albums = get_artists_with_new_albums(spot, prev_artist_info, curr_artist_info)

            if data_not_present():
                logging.info('Ran program for the first time')
                write_to_CSV(prev_artist_info, curr_artist_info)
            elif len(artists_with_new_albums) >= 1:
                email_sent = send_email(artists_with_new_albums)
                if email_sent:
                    write_to_CSV(prev_artist_info, curr_artist_info)
            else:
                print('No new albums')

            # deletes extra .csv files if there are more than three
            del_extra_files()

        except ConnectionResetError:
            print('Error establishing connection (Connection Reset Error)')
        except ConnectionError:
            print('Error establishing connection (Connection Error)')
        except OSError:
            print('OSError: [Errno 50] Network is down')
else:
def main():
    # if rocket_launches_in_period.verify_launches_will_happen():
    launches_tomorrow_message = compose_message_for_upcoming_launches(launches_in_period())
    send_email(launches_tomorrow_message)
Beispiel #39
0
def email_updates(repo, tag_name, name, notes):
  subject = "%s version %s has been released"%(repo, tag_name)
  body = "<h2>%s version %s has been released </h2>"%(repo, tag_name)
  body += "<br><b>%s</b>"%name
  body += "<br>" + notes
  emailer.send_email(config.release_contacts[repo], subject, body)
import json
from matchup import Matchup
from emailer import send_email

with open('history/2017-05-02.json', 'r') as f:
    games = [Matchup.from_json(g) for g in json.load(f)]

with open('history/2017-season.json', 'r') as f:
    totals = json.load(f)

send_email(games, games, totals, {
    'email_template': './email_template.html',
    'email_to': '*****@*****.**',
    'email_from': '*****@*****.**',
    'email_from': '*****@*****.**',
    'email_password': '******',
    'email_cc': ['*****@*****.**', '*****@*****.**'],
})
    i=0
    while i<len(price):
        l_price.append(price[i])
        i = i + 1


    for element in l_price:
        for d in digits:
            filtered_price += d if element == d

    converted_price = float(filtered_price)
    return converted_price , currency , title


amazon_url = input("Amazon Url : ")
currency = get_price(amazon_url)
print("\n \n")
budget = float(input("Your Budget (in " + currency + ") : "))

while True:
    converted_price , currency , title = Amazon_Scraper(amazon_url)
    if converted_price <= budget:
        message = "The Article : '"+title + "' priced at " + currency + "" + str(converted_price) + " Is affordable !!  Here is the link to buy it: \n "+ amazon_url
        emailer.send_email(message)
        sys.exit(0)

    else:
        time.sleep(300)
        pass

Beispiel #42
0
def work():
    # Make sure the attack duration value is valid
    try:
        attack_duration = int(os.environ['ATTACK_TIMEOUT_DURATION'])
        logger.debug(f'Attack duration timeout set to {attack_duration}')
    except:
        logger.error("Invalid value for Attack Timeout Duration.  Must be int")
        exit(1)

    logger.debug('Starting alert handler worker thread')

    # Make sure queue folder exists
    root = os.getcwd()
    attack_file_path = os.path.join(root, 'attacks')
    os.makedirs(attack_file_path, exist_ok=True)

    # Setup list to track which attacks have been alerted on
    alerted = []

    while 1:
        # Get all existing file names for detected attacks
        existing_attack_files = []

        logger.debug('Fetching current attack file names')
        with os.scandir(attack_file_path) as file_names:
            for file_name in file_names:
                if file_name.is_file():
                    existing_attack_files.append(file_name.name)

                    # If any notifications haven't been sent for an attack file send it.
                    if file_name.name not in alerted:
                        attack_info = file_name.name.split('_')
                        logger.debug(
                            'Sending notification email for new attack')
                        email_body = f'{attack_info[0]} attack detected from ip {attack_info[1]} mac {attack_info[2]}\n'
                        email_body += f'See CanaryPi logs for more detail.'

                        if emailer.send_email("CanaryPi Attack Detected",
                                              email_body):
                            alerted.append(file_name.name)

        for _ in range(len(new_alerts)):
            # Grab the most recent alert out of the new_alerts list
            alert = new_alerts.pop()

            # Grab the message from the alert
            message = alert.pop()

            # Combine the attack type, source ip, and source mac into a name
            attacker_ip = alert[1]
            attacker_mac = alert[2]
            alert_name = "_".join(alert)
            attack_file_name = os.path.join(attack_file_path, alert_name)

            # If new attack_type, source_ip or source_mac then create temporary attack file
            if alert_name not in existing_attack_files:
                logger.debug('Writing new attack file')
                with open(attack_file_name, 'w') as f:
                    f.write(
                        f'{datetime.now().strftime("%Y/%m/%d %H:%M:%S")} - {message} from ip {attacker_ip} mac {attacker_mac}\n'
                    )
                    existing_attack_files.append(alert_name)

                    logger.debug('Sending notification email for new attack')
                    email_body = f'Attack detected from ip {attacker_ip} mac {attacker_mac}\n'
                    email_body += f'{message}'

                    if emailer.send_email("CanaryPi Attack Detected",
                                          email_body):
                        alerted.append(alert_name)

            # Otherwise append to the existing one.
            else:
                logger.debug('Appending to attack file')
                with open(attack_file_name, 'a') as f:
                    f.write(
                        f'{datetime.now().strftime("%Y/%m/%d %H:%M:%S")} - {message} from ip {alert[1]} mac {alert[2]}\n'
                    )

        # for each on disk que get the last written to time/date
        with os.scandir(attack_file_path) as file_names:
            for file_name in file_names:
                if file_name.is_file():
                    # compare most recent activity to attack timeout time
                    current_time = time.time()
                    modified_time = os.path.getmtime(file_name)
                    time_since_modified = current_time - modified_time

                    # if time has expired
                    if time_since_modified > attack_duration:
                        # Read file from disk and build summary
                        with open(file_name, 'r') as f:
                            lines = f.readlines()

                        line_parts = lines[0].split("-", 1)
                        start_time = line_parts[0]
                        end_time = lines[len(lines) - 1].split("-")[0]
                        attack_details = line_parts[1].split(" ")
                        attack_type = attack_details[1]
                        attacker_ip = attack_details[7]
                        attacker_mac = attack_details[9]

                        # Build email message
                        message = f'{attack_type} attack has not been detected for {attack_duration} seconds from ip {attacker_ip}, mac {attacker_mac}'
                        message += f'Considered over.  See details below\n'
                        message += f'The attack began at {start_time} and ended at {end_time}\n'
                        message += f'There were {str(len(lines))} instances of this attack detected during that timeframe.\n'
                        message += f'For more information see the CanaryPi log files\n'

                        # Send email alert with summary
                        logger.debug(
                            f'Sending email because attack is considered over {str(time_since_modified)} is greater than {attack_duration}'
                        )
                        if emailer.send_email("CanaryPi Attack Ended",
                                              message):
                            # Delete file from disk
                            os.remove(file_name)

                            # Remove item from alerted list
                            alerted.remove(file_name.name)

        # sleep x seconds
        # remember this is hard coded
        logger.debug('Alert worker sleeping')
        time.sleep(10)