def check_new(user, password): pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user(user) pop_conn.pass_(password) # Get messages from server: messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] # Parse message into an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: subj = message['subject'] try: subj = decode_header(subj)[0][0] From = message.get('from', '') if subj.find(SUBSCRIBE_MOVIE) == 0: yield From elif subj.find(HOTWORD) == 0: attachment = message.get_payload()[1] # attachment.get_content_type() open('text.txt', 'wb').write(attachment.get_payload(decode=True)) res = os.system(SAE_STORAGEUPLOAD) retmsg = res == 0 and HOTWORD_RESULT or ERROR_UPLOAD mailer.send(retmsg, (From,), sub='hotresult') except: pass pop_conn.quit()
def password_reset(): """Password reset request """ if 'username' in session: return redirect('/') if request.method == 'POST': username = request.form['username'] u = User.query.filter_by(username=username).first() if u == None: u = User.query.filter_by(email=username).first() if u == None: # No user found flash('No user found under that username/email.', 'error') return render_template('password_reset_request.html') # Generate and set code for user code = generate_code() u.code = code db.session.commit() # Send email with reset link callback_url = f'{request.base_url}/callback?code={code}&email={u.email}' send( to=u.email, subject='Password Reset was Requested', body=f'Password request link: {callback_url}', ) flash('Email requesting password reset successfully sent!', 'info') return render_template('password_reset_request.html') else: return render_template('password_reset_request.html')
def queue_send_mail(request): addressee = request.POST.get('addressee') title = request.POST.get('title') body = request.POST.get('body') logging.info("sending mail: " + str(locals())) mailer.send(addressee, title, body) return HttpResponse('done')
def processOrder(order, user): print "[processing %s," % note(order), sys.stdout.flush() db.orders[order.id] = {'status': EXECUTING} db.commit() try: url = configurator.getApiUrl(order['action']) params = { 'orderId': order.id, 'userId': user.id, 'access': user.coinbase_access_token, 'pw': configurator.getWebPw(), } r = requests.get(url, params=params) print r.status_code, print r.text, if r.status_code == 200 and 'SUCCESS' in r.text: print "success]", sys.stdout.flush() db.orders[order.id] = {'status': EXECUTED} db.commit() try: mailer.send(user.email, getEmailTitle(order, EXECUTED), getEmailText(order, EXECUTED)) except Exception, err: if err.__class__.__name__ != 'SMTPAuthenticationError': #temp email problem raise else:
def main(): """Updater job entry point.""" logger.info('Updater job started') try: status = parser.parse_autelion() if status is None: logger.error('Updater job failed to parse Autelion') else: old_autelion = cache.get_autelion() cache.set_autelion(status) new_autelion = cache.get_autelion() if new_autelion is None: logger.error('Updater job failed to update cache') else: if old_autelion is None: logger.info('There was no previous status') mailer.send(new_autelion) else: if old_autelion.status == new_autelion.status: logger.info('Previous status has not changed') else: logger.info('Previous status has changed') mailer.send(new_autelion) finally: logger.info('Updater job finished')
def mail_santa(self, target): """ Send to the secret santa its target. """ if not isinstance(target, Participant): raise TypeError('Error: Target is not a participant.') send( '', self.mail, f'Hello {self.name}! This is your secret target!', f"Hi {self.name}!\n\nYou are {target.name}'s secret santa!\n\nGood luck! Have Fun!" )
def send_alert(temp, hum): gevent.sleep(1) if (config.CNF['last_time_called'] + 1200) < time.time(): mailer.send(temp, hum, config.CNF['last_time_called']) print(config.CNF['last_time_called']) config.set_time() print(config.CNF['last_time_called']) gevent.sleep(1)
def main(): Tos = [] for To in check_new(ME, PASSWORD): print To Tos.append(To) if Tos: with open(CUR_MOVIES) as f: infos = f.read().decode('utf8') mailer.send(infos, Tos)
def sendConfirmationEmail(self, mailer, base_url): mailer.send(account=self, subject='IrcQuotes account activation', body=ACTIVATION_EMAIL_TEMPLATE % { 'id': self.id, 'name': self.name, 'activation': self.activation, 'base_url': base_url, })
def notify(txt): logging.warn('notify txt: %s' % txt) try: info = copy.deepcopy(MailInfo) info['Subject'] = u"[SPAMMER]@%s warning" % now_str() info['Txt'] = u'local ip: %s\ntime: %s\n%s' % (local_ip(), now_str(), txt) mailer.send(**info) except Exception, e: logging.error('notify exception: %s' % e)
def send_mail(): import mailer newfname = CUR_MOVIES+'.new' if filecmp.cmp(CUR_MOVIES, newfname): os.remove(newfname) return os.rename(newfname, CUR_MOVIES) with open(CUR_MOVIES) as f: infos = f.read().decode('utf8') if len(infos)>10: mailer.send(infos, Tos)
def requestPasswordReset(self, mailer, base_url): if not self.trusted: return self.setupActivation(mailer, base_url) self.activation = hash.IHash(None) self.put() mailer.send(account=self, subject='IrcQuotes password reset', body=PASSWORD_EMAIL_TEMPLATE % { 'id': self.id, 'name': self.name, 'activation': self.activation, 'base_url': base_url, })
def main(): data = getpage(saleurl) soup = BeautifulSoup(data) res = soup.findAll('h2', {"class": "wdk_shopproduct-title"}) lst = [] for i in res: for aim in AIM_SIZE: if i.string.find(aim) >= 0: lst.append("<li>%s</li>" % i.string) infos = htmlinfo(lst) if infos: mailer.send(URL_ADDR + infos, tolist, sub='skate sale')
def do_POST(self): content_length = int( self.headers['Content-Length']) # <--- Gets the size of data post_data = self.rfile.read( content_length) # <--- Gets the data itself logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n", str(self.path), str(self.headers), post_data.decode('utf-8')) self._set_response() self.wfile.write("POST request for {}".format( self.path).encode('utf-8')) # Pido que manden el mail con estos datos mailer.send(post_data.decode('utf-8')) logging.info(post_data.decode('utf-8'))
def result_listener(event): if event.exception: #if a job crashes, send an email print('The job crashed :(') print(event) # print(event.exception) # print(event.traceback) message = "The following exception was thrown:\r\n\r\n" + str( event.exception) + "\r\n\r\n" + event.traceback mailer.send([config.get('email', 'adminAddress')], "A script has crashed!", message) else: #if a job doesn't crash, do nothing? print('The job worked :)')
def _mail_player(self, player, subject, body, then=None): """ Mail a player. Use 'then' as a callback and register an event url. Replaces 'EVENT_URL' in the body with the event url. Replaces 'PLAYER_NAME' in the body with the player's name. Returns the 'then' callback if there is one. """ logger.debug("Mailing {}".format(player)) if then != None: event_url = LINKSERVER_HOST + self._ls.register(then, once=True) body = body.replace("EVENT_URL", event_url) body = body.replace("PLAYER_NAME", player.name) mailer.send("outgoing.mit.edu", "*****@*****.**", player.email, subject, body) return then
def mail_to_editors(e): if e.check_mail(): return if e.get_result() != Result.SUCCESS: return tp_vals = dict() tp_vals["name"] = e.name tp_vals["submission_url"] = config.SUBMISSION_URL tp_vals["fullname"] = [d['title'] for d in e.metadata.entries][0] mailer.send(config.EDITORS, list(filter(None, re.split(" |,", e.metadata.contact))), "[AFP Submission] " + tp_vals["fullname"], fill_template(tp_vals, "mails/to_editors.mail.tp")) #create empty file "mail" to indicate sent mail e.signal_mail()
def halfday_updates(): log_msgs = [] now = datetime.now().replace(microsecond=0) db = Database(dbfile) log_irc('{now}--Checking for new GTFS files'.format(now=now)) gtfs_log, gtfs_email = transitfeeds.check_for_gtfs(db, cfg) log_msgs.extend(gtfs_log) if gtfs_email: log_irc('{now}--Emailing about GTFS update'.format(now=now)) mailer.send(cfg, gtfs_email) log_msgs.append('') log_file(log_msgs) db.close()
def test_send(): with patch('smtplib.SMTP') as mock: instance = mock.return_value instance.sendmail.return_value = {} res = send('*****@*****.**', '*****@*****.**', 'topic', 'body') assert res == {}
def test_send(patch_smtplib): res = send( '*****@*****.**', '*****@*****.**', 'topic', 'body' ) assert res == {}
def test_send(monkeypatch): smtp_mock = MagicMock() smtp_mock.sendmail.return_value = {} monkeypatch.setattr(smtplib, 'SMTP', MagicMock(return_value=smtp_mock)) res = send('*****@*****.**', '*****@*****.**', 'topic', 'body') assert res == {}
def format(ip, usr, pw): ip = ip usr = usr.rsplit() pw = pw.rsplit() if not usr and not pw: pass elif not usr: pass elif not pw: pw = "No password provided." m.send(ip, str(usr[0]), pw) cl.log(ip, str(usr[0]), pw) fl.log(str(usr[0]), pw) else: m.send(ip, str(usr[0]), str(pw[0])) cl.log(ip, str(usr[0]), str(pw[0])) fl.log(str(usr[0]), str(pw[0]))
def jump_p(li): li_jump_1 = [i for i in li if i.jump>0] total = len(li) lcc_1 = len([i for i in li if i.lcc>=1]) lcc_0 = len([i for i in li if i.lcc<1]) jump_1 = len(li_jump_1) jump_0 = len([i for i in li if i.jump<=0]) lcc_1_jump_1 = len([i for i in li if i.lcc>=1 and i.jump>0]) lcc_0_jump_1 = len([i for i in li if i.lcc<1 and i.jump>0]) lcc_1_jump_0 = len([i for i in li if i.lcc>=1 and i.jump<=0]) lcc_0_jump_0 = len([i for i in li if i.lcc<1 and i.jump<=0]) data = web.storage(total=total, lcc_1= "%s,%s%%" %(lcc_1,100*lcc_1/total), lcc_0= "%s,%s%%" %(lcc_0,100*lcc_0/total), jump_1= "%s,%s%%" %(jump_1,100*jump_1/total), jump_0= "%s,%s%%" %(jump_0,100*jump_0/total), lcc_1_jump_1= "%s,%s%%" %(lcc_1_jump_1,100*lcc_1_jump_1/jump_1), lcc_1_jump_0= "%s,%s%%" %(lcc_1_jump_0,100*lcc_1_jump_0/jump_0) , lcc_0_jump_1 = "%s,%s%%" %(lcc_0_jump_1,100*lcc_0_jump_1/jump_1) , lcc_0_jump_0= "%s,%s%%" %(lcc_0_jump_0,100*lcc_0_jump_0/jump_0) ) t = web.template.Template('''$def with (x)\n<table width="100%"> <tr><td></td><td>up</td><td>down</td><td>lcc-V</td></tr> <tr><td>up</td><td>$(x.lcc_1_jump_1)</td><td>$(x.lcc_1_jump_0)</td><td>$(x.lcc_1)</td></tr> <tr><td>down</td><td>$(x.lcc_0_jump_1)</td><td>$(x.lcc_0_jump_0)</td><td>$(x.lcc_0)</td></tr> <tr><td>jump》</td><td>$(x.jump_1)</td><td>$(x.jump_0)</td><td>$(x.total)</td></tr> </table><br/>''') ht = t(data) li_jump_1 = [r for r in li_jump_1 if r.low<r.open and r.close > r.open and r.jump<9] li_jump_1.sort(key=lambda x:x.jump,reverse=True) str_list = '<br/>'.join(['<a href="https://www.baidu.com/s?wd=%s" target="_blank">%s</a> , %s%%' % (x.stock_no[2:],x.stock_no[2:],'%0.2f'%x.jump) for x in li_jump_1]) html = str(ht) + str_list # print html mailer.send('d_%s_%s'%(li[0].date,li[0].time), html)
def test_send(): with patch('smtplib.SMTP') as mock: instance = mock.return_value instance.sendmail.return_value = {} res = send( '*****@*****.**', '*****@*****.**', 'topic', 'body' ) assert res == {}
def main(): for (url, threshold, product_name) in Targets: fprice = product_name + '.old' fullname = cur_fname(fprice) old_price = get_price(fullname) res = getpage(url) soup = BeautifulSoup.BeautifulSoup(res) sp = soup.find('span', id='priceblock_ourprice') price = float(sp.text[1:]) realprice = price * .85 - get_coupon(soup) if old_price != realprice: replace_file(fullname, str(realprice)) if old_price == 0 or (realprice < threshold and realprice < old_price): url_addr = '<a href="%s" >%s</a></br>' % ((url, ) * 2) subject = '%s < %s' % (product_name, threshold) mailer.send(url_addr + 'realprice: %s\n old_price: %s' % (realprice, old_price), tolist, sub=subject)
def test_send(monkeypatch): smtp_mock = MagicMock() smtp_mock.sendmail.return_value = {} monkeypatch.setattr(smtplib, 'SMTP', MagicMock(return_value=smtp_mock)) res = send( '*****@*****.**', '*****@*****.**', 'topic', 'body' ) assert res == {}
def test_send(faker: Faker, iteration: int): sender = faker.email() to = faker.email() body = faker.paragraph() subject = faker.sentence() with patch("smtplib.SMTP") as mock: client = mock.return_value client.sendmail.return_value = {} res = send(sender, to, subject, body) assert client.sendmail.called assert client.sendmail.call_args[0][0] == sender assert client.sendmail.call_args[0][1] == to assert subject in client.sendmail.call_args[0][2] assert body in client.sendmail.call_args[0][2] assert res == {}
def test_send_unittest(): sender = "*****@*****.**" to = "*****@*****.**" body = "Hello jane!" subject = "How are you?" with patch('smtplib.SMTP') as mock: client = mock.return_value client.sendmail.return_value = {} res = send(sender, to, subject, body) assert client.sendmail.called assert client.sendmail.call_args[0][0] == sender assert client.sendmail.call_args[0][1] == to assert subject in client.sendmail.call_args[0][2] assert body in client.sendmail.call_args[0][2] assert res == {}
def test_send(monkeypatch): sender = "*****@*****.**" to = "*****@*****.**" body = "Hello jane!" subject = "How are you?" smtp = Mock() monkeypatch.setattr(smtplib, "SMTP", smtp) client = smtp.return_value client.sendmail.return_value = {} res = send(sender, to, subject, body) assert client.sendmail.called assert client.sendmail.call_args[0][0] == sender assert client.sendmail.call_args[0][1] == to assert subject in client.sendmail.call_args[0][2] assert body in client.sendmail.call_args[0][2] assert res == {}
db.commit() try: mailer.send(user.email, getEmailTitle(order, EXECUTED), getEmailText(order, EXECUTED)) except Exception, err: if err.__class__.__name__ != 'SMTPAuthenticationError': #temp email problem raise else: raise Exception('could not buy') except Exception, err: #todo: log the problem print "fail]", sys.stdout.flush() db.orders[order.id] = {'status': FAILED} db.commit() mailer.send(user.email, getEmailTitle(order, FAILED), getEmailText(order, FAILED)) raise def processBuyAt(currentBuyPrice): triggeredOrders = db(\ (db.orders.status=='ACTIVE') & \ (db.orders.action=='BUY') & \ (currentBuyPrice<=db.orders.at_price) & \ (db.orders.at_price!=None) & \ (db.orders.amount!=None) \ ) for order in triggeredOrders.select(): user = db.users[order.user_id] if user.coinbase_access_token is not None: totalBuyPrice = price.getBuyPrice(order.amount) #todo - ask for price with users tokens if totalBuyPrice is not None and totalBuyPrice <= order.at_price * order.amount:
cursor = conn.cursor() cursor.execute("SELECT emailAddress, lastReset FROM tUsers WHERE userID='" + uname + "';") row = cursor.fetchone() if row == None: result = "bad username" else: email = row[0] lastReset = row[1] if (lastReset == None or ghShared.timeAgo(lastReset).find("minute") == -1): message = mailer.Message() message.From = "*****@*****.**" message.To = email message.Subject = "Galaxy Harvester password reset" message.Body = "Hello " + uname + ",\n\nYour password for galaxyharvester.net has been reset to:\n\n" + newPass + "\n\n go to http://galaxyharvester.net to login.\n" mailer = mailer.Mailer(mailInfo.MAIL_HOST) mailer.login(mailInfo.MAIL_USER, mailInfo.MAIL_PASS) mailer.send(message) cursor.execute('UPDATE tUsers SET userPassword="******", lastReset=NOW() WHERE userID="' + uname + '";') result = 'email sent' else: result = 'You can only reset your password 1 time per hour.' cursor.close() conn.close() print "Content-Type: text/html\n" print result
def add_and_sends_email(x, y): z = x + y mailer.send(to='*****@*****.**', subject='Complex addition', body=('The result was %s' % z)) return z
try: mailer.send(user.email, getEmailTitle(order, EXECUTED), getEmailText(order, EXECUTED)) except Exception, err: if err.__class__.__name__ != 'SMTPAuthenticationError': #temp email problem raise else: raise Exception('could not buy') except Exception, err: #todo: log the problem print "fail]", sys.stdout.flush() db.orders[order.id] = {'status': FAILED} db.commit() mailer.send(user.email, getEmailTitle(order, FAILED), getEmailText(order, FAILED)) raise def processBuyAt(currentBuyPrice): triggeredOrders = db(\ (db.orders.status=='ACTIVE') & \ (db.orders.action=='BUY') & \ (currentBuyPrice<=db.orders.at_price) & \ (db.orders.at_price!=None) & \ (db.orders.amount!=None) \ ) for order in triggeredOrders.select(): user = db.users[order.user_id] if user.coinbase_access_token is not None: totalBuyPrice = price.getBuyPrice(
def get(self): # Get the current logged-in user user = users.get_current_user() # Get the Session session = dal.return_and_global_session_update(self) # Check Login if not user: self.redirect(users.create_login_url('/admin/providers')) # Check if they are a admin if users.is_current_user_admin() == False: self.redirect('/') # Check Provider if self.request.get('provider') and self.request.get('action'): # Get ID's provider_id = int(self.request.get('provider')) action_str = self.request.get('action') # Provider Object provider_obj = schemas.Provider.get_by_id(int(self.request.get('provider'))) # Check if it's a Valid Provider if provider_obj is not None and provider_obj is not False: # What action if action_str == "remove" or action_str == "delete": # Get the members to send the Mail to members = dal.memberships_by_provider(provider_obj) # Loop and Mail the Members for member in members: # Send Mail to Member template_locales = { 'title': str(provider_obj.name) + ' has been removed from IdentiChip.org', 'description': str(provider_obj.name) + ' has been removed from IdentiChip.org', 'subject': str(provider_obj.name) + ' has been removed from IdentiChip.org', 'provider': provider_obj } # The Form parameters were validated mailer.send( to=str(member.user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/provider/provider_deleted.html', locales=template_locales) # Remove Members db.delete(dal.memberships_by_provider(provider_obj)) # Delete the Provider db.delete(provider_obj) elif action_str == "approve": # Set Settings provider_obj.approved = self.request.get('flag') == "on" # Get the members to send the Mail to members = dal.memberships_by_provider(provider_obj) # Loop and Mail the Members for member in members: # Is on if self.request.get('flag') == "on": # Text text_str = str(provider_obj.name) + ' has been Approved' # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj } # The Form parameters were validated mailer.send( to=str(member.user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/provider/provider_approved.html', locales=template_locales) else: # Text text_str = str(provider_obj.name) + ' has had it\'s approval status removed' # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj } # The Form parameters were validated mailer.send( to=str(member.user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/provider/provider_not_approved.html', locales=template_locales) # Save provider_obj.put() elif action_str == "tested": # Set Settings provider_obj.tested = self.request.get('flag') == "on" # Get the members to send the Mail to members = dal.memberships_by_provider(provider_obj) # Loop and Mail the Members for member in members: # Is on if self.request.get('flag') == "on": # Text text_str = str(provider_obj.name) + ' has been Marked as Tested by a Administrator' # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj } # The Form parameters were validated mailer.send( to=str(member.user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/provider/provider_tested.html', locales=template_locales) else: # Text text_str = str(provider_obj.name) + ' has been had it\'s tested status removed by a Administrator' # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj } # The Form parameters were validated mailer.send( to=str(member.user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/provider/provider_not_tested.html', locales=template_locales) # Save provider_obj.put() # Tell the Provider they have been included in the searches if provider_obj.approved and provider_obj.tested: # Get the members to send the Mail to members = dal.memberships_by_provider(provider_obj) # Loop and Mail the Members for member in members: # Text text_str = str(provider_obj.name) + ' is now regonized as a trusted provider on Identichip.org' # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj } # The Form parameters were validated mailer.send( to=str(member.user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/provider/provider_included.html', locales=template_locales) # Redirect self.redirect('/admin/providers#provider_block_' + str(provider_obj.key().id())) # Else redirect else: self.redirect('/admin/providers') # Get Providers providers_list = dal.get_list_of_providers() # Counters approved_providers_count = 0 accepted_providers_count = 0 tested_providers_count = 0 # Count for provider_list_obj in providers_list: # Count Approved if provider_list_obj.approved and provider_list_obj.tested: # Count accepted_providers_count += 1 # Count Approved elif not provider_list_obj.approved: # Count approved_providers_count += 1 # Counter elif not provider_list_obj.tested: # Count tested_providers_count += 1 # Locales locales = { 'title': 'Manage Approved Providers', 'description': 'Providers', 'user': users.get_current_user(), 'session': session, 'providers': providers_list, 'approved_providers_count': approved_providers_count, 'accepted_providers_count': accepted_providers_count, 'tested_providers_count': tested_providers_count, 'is_current_user_admin': users.is_current_user_admin() } # Render the template template = jinja_environment.get_template('admin/providers.html') self.response.out.write(template.render(locales))
def get(self, uid, result_number=0): if uid: # Get the search object and responses (search_obj, search_responses) = dal.search_by_token(uid) # Check if the search exists and if any responses are associated with it. if search_obj and search_responses and search_obj.expires > datetime.datetime.now(): # Get the current logged-in user user = users.get_current_user() # Update the expiring date. We allow anyone to view the search x minutes after it's been searched search_obj.expires = datetime.datetime.now() + datetime.timedelta( minutes=runner.EXPIRES_AFTER ) search_obj.put() # Filter the Results to what we need success_results = [] failure_results = [] for response in search_responses: if response.status == runner.ProviderResponse.STATUS_FOUND: success_results.append(response) elif response.status not in [runner.ProviderResponse.STATUS_FOUND, runner.ProviderResponse.STATUS_NOTFOUND]: failure_results.append(response) # Get the current provider, chip and owner to show if len(success_results) > 0: # What response should we look at ? current_index = 0 if self.request.get('provider'): # Only executed if the user provided a provider to check for. # This is used when multiple provider gave a response. # So we can list all the responses for the user. try: # Assign custom index from request requested_provider_uid = int(self.request.get('provider')) # Get the index of a the provider with that id current_index = [int(y.provider.key().id()) for y in success_results].index(requested_provider_uid) except Exception as ex: # Just use the default value current_index = 0 # Check that the index is sane else we make it the first one if current_index > (len(success_results)): current_index = 0 # Single Response Object single_response = success_results[current_index] # Get the provider provider = success_results[current_index].provider # Get the Chip Details chip = json.loads(success_results[current_index].parsed_response) # Section of the Result Page to show. section = 'info' # Set section according to request if self.request.get('section'): # Parse the string as a section requested_section_str = str(self.request.get('section').strip().lower()) # Is this a valid Section if requested_section_str in ['info', 'result', 'contact']: # Then we assign it section = requested_section_str # ######## # Handle Posts if any # ######## # success_message_flags contact_form_success = False # Errors contact_form_error = False # Handle Contact Form if self.request.POST.get('form_contact'): # Set section as they will want to see their response section = 'contact' # Handle the contact form contact_name = self.request.POST.get('form_contact_name') contact_email = self.request.POST.get('form_contact_email') contact_message = self.request.POST.get('form_contact_message') # Validate contact_form_error = None if single_response.email_sent == True: # We can't send multiple E-Mails to the same user on the same search contact_form_error = 'An E-Mail has already been sent to the user. We do not allow multiple E-Mails to prevent spamming. Please give the user some time to response to your E-Mail after which you\'ll be able to communicate directly.' elif not contact_name or len(str(contact_name).strip()) == 0: # Name is Required contact_form_error = 'Your name is Required' elif not contact_email or len(str(contact_email).strip()) == 0 or not re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", contact_email): # An Valid E-Mail is Required contact_form_error = 'A Valid E-Mail by which the user can reach you again.' elif not contact_message or len(str(contact_message).strip()) == 0: # Message is required contact_form_error = 'We need a message which we will send to the user. This should include basic details such as where you found the pet and your location' else: # Generate Template to send template_locales = { 'title': 'Search for #' + str(search_obj.uid), 'description': 'Contact message by User who searched for #' + str(search_obj.uid), 'chip': chip, 'subject': 'Contact message by User who searched for #' + str(search_obj.uid), 'sender_name': str(contact_name).strip(), 'sender_email': str(contact_email).strip(), 'message': str(contact_message).strip(), 'provider': provider } # The Form parameters were validated mailer.send( to=str(chip['owner']['email']), reply_to=str(template_locales['sender_email']), subject=str(template_locales['subject']), view='mail/contact_from_search.html', locales=template_locales) # Update to show that the E-Mail was sent single_response.email_sent = True single_response.email_sent_from = str(contact_email).strip() single_response.email_sent_name = str(contact_name).strip() single_response.email_sent_text = str(contact_message).strip() single_response.put() section = 'info' contact_form_success = 'true' # Create the Locales for the Page to use locales = { 'title': 'Search for #' + str(search_obj.uid), 'description': 'The results of the search for the Unique Number #' + str(search_obj.uid), 'chip': chip, 'current_response': single_response, 'search': search_obj, 'provider': provider, 'success_results': search_obj.provider_success_responses, 'failure_results': search_obj.provider_failure_responses, 'notfound_results': search_obj.provider_notfound_responses, 'total_providers_asked': search_obj.provider_total_requests, 'search_obj': search_obj, 'search_responses': search_responses, 'search_success_responses': success_results, 'search_failure_responses': failure_results, 'user': user, 'contact_form_error': contact_form_error, 'contact_form_success': contact_form_success, 'section': section, 'post_params': self.request.POST, 'contact_post_url': '/view/' + search_obj.token + "?provider=" + str(provider.key().id()) + "&response=" + str(single_response.key().id()), 'session': dal.return_and_global_session_update(self), 'is_current_user_admin': users.is_current_user_admin() } # Render the Template with those Values template = jinja_environment.get_template('search/result.html') self.response.out.write(template.render(locales)) else: session_store = sessions.get_store(request=self.request) session = session_store.get_session() if 'search_token' not in session: session['search_token'] = str(uuid.uuid1()) session_store.save_sessions(self.response) # Well if their was not result we redirect to homepage # Create the Locales for the Page to use locales = { 'title': 'No Results found for #' + str(search_obj.uid), 'description': 'The results of the search for the Unique Number #' + str(search_obj.uid), 'success_results': search_obj.provider_success_responses, 'failure_results': search_obj.provider_failure_responses, 'notfound_results': search_obj.provider_notfound_responses, 'total_providers_asked': search_obj.provider_total_requests, 'search_obj': search_obj, 'search': search_obj, 'search_responses': search_responses, 'search_success_responses': success_results, 'search_failure_responses': failure_results, 'user': user, 'session': session, 'session': dal.return_and_global_session_update(self), 'is_current_user_admin': users.is_current_user_admin() } # self.response.out.write("<li>" + detail.provider.name + " <-> <img src=\"" + images.get_serving_url(detail.provider.logo.key(), 32) + "\" /></li>") # Render the Template with those Values template = jinja_environment.get_template('search/notfound.html') self.response.out.write(template.render(locales)) else: # That search does not exist. Redirect them to the homepage. self.redirect('/') else: # They did not give a search uid redirect them to the homepage self.redirect('/')
# res.index = pd.to_datetime(res.index, format='%d-%m-%Y') NetworkModel(df, "19941227", "20150101", 100, saveSimulations=True) # benchmarkModel(df,saveSimulations=True) # exit() # retS = pd.read_csv('rSeries_benchmark.csv', index_col=0) # retS.index = pd.to_datetime(retS.index, format='%Y-%m-%d') # generateBerkowizData(retS,_genDailyReturns(df)) # ESFormalTest(es=res['bnch_ES5'], var=res['bnch_VaR5'], alpha=0.05, data=df, name='bnchES5p') # NetworkModel(trainingData=df, start='20121227', end='20150101', memory=100, saveSimulations=True) mailer.send( "dailyResults_" + time.strftime("%Y%m%d", time.gmtime()) + ".csv", "*****@*****.**", "Ireren er færdig" ) mailer.send( "dailyResults_" + time.strftime("%Y%m%d", time.gmtime()) + ".csv", "*****@*****.**", "Ireren er færdig" ) except: mailer.send( "dailyResults_" + time.strftime("%Y%m%d", time.gmtime()) + ".csv", "*****@*****.**", "Ireren har fejlet", ) mailer.send( "dailyResults_" + time.strftime("%Y%m%d", time.gmtime()) + ".csv", "*****@*****.**", "Ireren har fejlet",
CONFIG_FILE = './xrss.conf' config = ConfigParser.RawConfigParser() config.read(CONFIG_FILE) logging.config.fileConfig(CONFIG_FILE) logger = logging.getLogger('xrss') FEED_LIST = str2list(config.get('xrss', 'urls')) TEMPLATE_DIR = config.get('xrss', 'template_dir') TEMPLATE_FILE = config.get('xrss', 'template_file') STALE_DATE = ( datetime.datetime.now() - datetime.timedelta(days=config.getint('xrss', 'stale_date'))).timetuple() #print str2list(config.get('xrss', 'recipients')) html = get_content(TEMPLATE_DIR, TEMPLATE_FILE, FEED_LIST) f = open('/tmp/o.html', 'w+') f.write(html.encode('utf8')) f.close() try: mailer.send(subject='News from xRSS', addresser=config.get('mail', 'addresser'), passwd=config.get('mail', 'passwd'), recipients=str2list(config.get('xrss', 'recipients')), html=get_content(TEMPLATE_DIR, TEMPLATE_FILE, FEED_LIST)) logger.info('send news successfully') except: logger.error('send news failed')
df = pd.read_csv('data/TData9313_final6.csv', sep=",", index_col=0) print "data loaded", time.time() - t0 df.index = pd.to_datetime(df.index) # res = pd.read_csv('resultstest.csv', index_col='Date') # res.index = pd.to_datetime(res.index, format='%d-%m-%Y') NetworkModel(df,'19941227','20150101',100,saveSimulations=True) #benchmarkModel(df,saveSimulations=True) #exit() #retS = pd.read_csv('rSeries_benchmark.csv', index_col=0) #retS.index = pd.to_datetime(retS.index, format='%Y-%m-%d') #generateBerkowizData(retS,_genDailyReturns(df)) #ESFormalTest(es=res['bnch_ES5'], var=res['bnch_VaR5'], alpha=0.05, data=df, name='bnchES5p') #NetworkModel(trainingData=df, start='20121227', end='20150101', memory=100, saveSimulations=True) mailer.send('dailyResults_' + time.strftime("%Y%m%d", time.gmtime()) + ".csv", '*****@*****.**', 'Ireren er færdig') mailer.send('dailyResults_' + time.strftime("%Y%m%d", time.gmtime()) + ".csv", '*****@*****.**', 'Ireren er færdig') except: mailer.send('dailyResults_' + time.strftime("%Y%m%d", time.gmtime()) + ".csv", '*****@*****.**', 'Ireren har fejlet') mailer.send('dailyResults_' + time.strftime("%Y%m%d", time.gmtime()) + ".csv", '*****@*****.**', 'Ireren har fejlet')
def get(self): provider_obj = schemas.Provider.get_by_id(int(self.request.get('provider'))) if provider_obj is not None and provider_obj is not False: # Ok so Provider exists. # Now check if this is a logged in user and if they are a member of this provider. # If so we rather so a dashboard and edit properties and controls. user = users.get_current_user() if user: # Ok so let's check if they are a member membership_obj = dal.membership_by_user(provider_obj, user) if membership_obj is not None and membership_obj is not False: # Check if we have at least one member still in the provider current_members = dal.memberships_by_provider(provider_obj) # Check for at least 1 member if current_members.count() > 0: if self.request.get('type') == 'remove': # Get the members to send the Mail to members = dal.memberships_by_provider(provider_obj) # Loop and Mail the Members for member in members: # Text text_str = str(self.request.get('email')) + ' has been removed as a member of ' + str(provider_obj.name) # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj } # The Form parameters were validated mailer.send( to=str(member.user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/provider/member_deleted.html', locales=template_locales) # Remove the Membership dal.delete_memberships_by_provider(provider_obj, users.User(self.request.get('email'))) elif self.request.get('type') == 'add': # Get the members to send the Mail to members = dal.memberships_by_provider(provider_obj) # Loop and Mail the Members for member in members: # Text text_str = str(self.request.get('email')) + ' has been added as a member of ' + str(provider_obj.name) # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj, 'user': user } # The Form parameters were validated mailer.send( to=str(member.user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/new_member_just_added.html', locales=template_locales) # Send to current user text_str = str(provider_obj.name) + ' has added your account as a member' # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj, 'user': user } # The Form parameters were validated mailer.send( to=str(self.request.get('email')), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/newly_added_member.html', locales=template_locales) # Create new member membership_obj = schemas.ProviderMember(provider=provider_obj,user=users.User(self.request.get('email'))) # Save Member membership_obj.put() self.redirect('/provider/' + str(provider_obj.key().id()) + "?section=members")
import SendClassFollowup import RegistrationMonitor import ArchiveInactive import SyncDiscourseGroups print("Scripts imported") waiver_check = WaiverCheck.ChildScript('Waiver Check') class_followup = SendClassFollowup.ChildScript('Class Followup') registration_monitor = RegistrationMonitor.ChildScript( 'Registration Monitor') archiver = ArchiveInactive.ChildScript('Archiver') discourse_sync = SyncDiscourseGroups.ChildScript('Discourse Sync') message = "Dispatcher started" mailer.send([config.get('email', 'adminAddress')], "Dispatcher script has restarted!", message) except Exception as e: message = traceback.format_exc() mailer.send([config.get('email', 'adminAddress')], "Dispatcher script has crashed!", message) sys.exit() def result_listener(event): if event.exception: #if a job crashes, send an email print('The job crashed :(') print(event) # print(event.exception) # print(event.traceback)
import time import mailer timestamp = time.strftime("%Y-%m-%d %I:%M %p", time.localtime()) outgoing_host = "smtp.mandrillapp.com" from_addr = "*****@*****.**" to_addr = "*****@*****.**" subject = "Hey There" body = "mailer test\n{}".format(timestamp) mailer.send(outgoing_host, from_addr, to_addr, subject, body)
CONFIG_FILE = './xrss.conf' config = ConfigParser.RawConfigParser() config.read(CONFIG_FILE) logging.config.fileConfig(CONFIG_FILE) logger = logging.getLogger('xrss') FEED_LIST = str2list(config.get('xrss', 'urls')) TEMPLATE_DIR = config.get('xrss', 'template_dir') TEMPLATE_FILE = config.get('xrss', 'template_file') STALE_DATE = (datetime.datetime.now() - datetime.timedelta(days=config.getint('xrss', 'stale_date'))).timetuple() #print str2list(config.get('xrss', 'recipients')) html=get_content(TEMPLATE_DIR, TEMPLATE_FILE, FEED_LIST) f = open('/tmp/o.html', 'w+') f.write(html.encode('utf8')) f.close() try: mailer.send( subject='News from xRSS', addresser=config.get('mail', 'addresser'), passwd=config.get('mail', 'passwd'), recipients= str2list(config.get('xrss', 'recipients')), html=get_content(TEMPLATE_DIR, TEMPLATE_FILE, FEED_LIST)) logger.info('send news successfully') except: logger.error('send news failed')
cur.close() conn.close() if __name__ == "__main__": if len(sys.argv) != 2: print("usage: python add_users.py <csv file>") exit(1) csv_file = sys.argv[1] if not os.path.isfile(csv_file): print("file not found %s" % csv_file) exit(2) # Reading csv file with the users to add print("Parsing the %s file" % csv_file) users = csvreader.read(csv_file) # Connecting to the db print("Connecting to database") conn, cur = connectdb() query = "INSERT INTO myneect.new_users (full_name, mail, token) VALUES (%s, %s, %s)" print("Adding users...") for user in users: token = secrets.token_urlsafe(16) cur.execute(query, (user.name, user.mail, token)) conn.commit() mailer.send(user.name, user.mail, token) closedb() print("Done")
def notify_monitors(self, message): mailer.send(self.monitors, message)
def get(self): user = users.get_current_user() if user: if 'USER_ORGANIZATION' in os.environ: user.organization = os.environ['USER_ORGANIZATION'] session_store = sessions.get_store(request=self.request) session = session_store.get_session() # Error to show if any register_form_error = False # Check if this is a form post if self.request.POST.get('form_register'): # Assign Local cleaned parameters provider_name = str(self.request.POST.get('form_provider_name')).strip() provider_description = str(self.request.POST.get('form_provider_description')).strip() provider_website = str(self.request.POST.get('form_provider_website')).strip() # Valdidate if not self.request.POST.get('form_provider_name') or len(provider_name) == 0: # Name is Required register_form_error = 'Name of your Provider is Required' elif not self.request.POST.get('form_provider_website') or len(provider_website) == 0 or (not 'http://' in provider_website or 'https://' in provider_website): # Website is Required. # We check for http:// or https:// register_form_error = 'Website of your Provider is Required. The Path must include http:// or https://' else: # Handle Logo Uploads logo = None try: logo = self.get_uploads()[0] except: register_form_error = 'Error while uploading Logo' # Create our API Secret Key d = date.today() value_key = str(str(d.year) + "-" + str(d.month) + "-" + str(d.day)) + provider_name + provider_description + provider_website provider_secret = hashlib.sha1(value_key).hexdigest() # Create the Provider Object and Populate provider_obj = schemas.Provider( name=provider_name, description=provider_description, website=provider_website, approved=False, tested=False, logo=logo, secret=provider_secret) # Save that sucker provider_obj.put() if self.request.POST.get('form_provider_name') == 'yes' and user.organization and len(user.organization) > 0: if 'members' in session: for member in session['members']: if 'admin' in member and member['admin'] == 'true': # Add the current user as the first member new_member = users.User(member['email']) membership_obj = schemas.ProviderMember(provider=provider_obj,user=new_member) membership_obj.put() else: # Add the current user as the first member membership_obj = schemas.ProviderMember(provider=provider_obj,user=user) membership_obj.put() # The Form parameters were validated mailer.send_admin( subject='New Provider registered ' + str(provider_obj.name), body='New Provider registered ' + str(provider_obj.name)) # Text text_str = 'New Provider Registration Received for IdentiChip' # Send Mail to Member template_locales = { 'title': text_str, 'description': text_str, 'subject': text_str, 'provider': provider_obj, 'user': user } # Send to Current User mailer.send( to=str(user.email()), reply_to='*****@*****.**', subject=template_locales['subject'], view='mail/provider/provider_new.html', locales=template_locales) # Redirect to the new Registered Provider self.redirect('/provider/' + str(provider_obj.key().id())) # Count of the Admins in the Group admin_member_count = 0 if 'members' in session: for member in json.loads(str(session['members'])): if 'admin' in member and member['admin'] == 'true': admin_member_count = admin_member_count + 1 # Create the registration layout locales = { 'register_form_error': register_form_error, 'title': 'Register a New Provider', 'description': 'Search Microchips', 'user': user, 'admin_member_count': admin_member_count, 'session': session, 'post_params': self.request.POST, 'upload_url': blobstore.create_upload_url('/provider/register'), 'session': dal.return_and_global_session_update(self), 'is_current_user_admin': users.is_current_user_admin() } template = jinja_environment.get_template('provider/create.html') self.response.out.write(template.render(locales)) else: self.redirect(users.create_login_url('/provider/register'))
aprx.updateConnectionProperties(editingGDB, hubGDB) try: aprx.save() except: logging.basicConfig(filename=logFile, level=logging.ERROR) logging.error(' Error with ArcGIS Pro project {}.'.format(m)) del aprx logging.basicConfig(filename=logFile, level=logging.INFO) logging.info(' Data sources for {} were updated.'.format(m)) with open(csvFile, 'w') as g: writer = csv.writer(g) writer.writerow(['APRX File Path']) message.Subject = "ArcGIS Pro Data Source Update - SUCCESS" message.Html = "All ArcGIS Pro projects that had data pointing to the Editing geodatabase have been repointed to the Hub.<br><br>" \ "Check the log (<a href='{}'>{}</a>) if you like.<br><br>" \ "Or you can simply go on with your day.".format(logFile, logFile) mailer = mailer.Mailer("mailhost.co.jeffco.us") mailer.send(message) finish = time.time() duration = str(finish - start) logging.basicConfig(filename=logFile, level=logging.INFO) logging.info(' Sync was successful in {} seconds'.format(duration))
def sendEmailNotification(subject, body): mailer.send(configurator.getDebugEmail(), subject, body)
def mail_report(report): if report != "": #print report mailer.send('[RW] Modification de droits sur Vikidia.',report)
def post(self): # Check if they gave a token if self.request.get('token'): # They did so now let's check the client client_obj = authenticate_client(str(self.request.get('token'))) # Check client if client_obj and client_obj is not False: # Well get the details # http://www.identichip.org/apis/v1/contact?token=testing&key=ag5kZXZ-aWRlbnRpY2hpcHIQCxIKVXNlclNlYXJjaBhwDA&option=ag5kZXZ-aWRlbnRpY2hpcHIWCxIQVXNlclNlYXJjaERldGFpbBhxDA if self.request.get('key'): # Get the search object and responses (search_obj, search_responses) = dal.search_by_token(self.request.get('key')) # Check if the search exists and if any responses are associated with it. if search_obj and search_responses and search_obj.expires > datetime.datetime.now(): # Filter the Results to what we need success_results = [] failure_results = [] for response in search_responses: if response.status == runner.ProviderResponse.STATUS_FOUND: success_results.append(response) elif response.status not in [runner.ProviderResponse.STATUS_FOUND, runner.ProviderResponse.STATUS_NOTFOUND]: failure_results.append(response) # Get the current provider, chip and owner to show if len(success_results) > 0: # What response should we look at ? current_index = 0 if self.request.get('provider'): # Only executed if the user provided a provider to check for. # This is used when multiple provider gave a response. # So we can list all the responses for the user. try: # Get the index of a the provider with that id current_index = [y.provider.key() for y in success_results].index(str(self.request.get('provider'))) except Exception as ex: # Just use the default value current_index = 0 # Check that the index is sane else we make it the first one if current_index > (len(success_results)): current_index = 0 # Single Response Object single_response = success_results[current_index] # Get the provider provider = success_results[current_index].provider # Get the Chip Details chip = json.loads(success_results[current_index].parsed_response) # Handle the contact form contact_name = self.request.POST.get('contact_name') contact_email = self.request.POST.get('contact_email') contact_message = self.request.POST.get('contact_message') if single_response.email_sent == True: # We can't send multiple E-Mails to the same user on the same search self.response.out.write(json.dumps({ 'error': 'An E-Mail has already been sent to the user. We do not allow multiple E-Mails to prevent spamming. Please give the user some time to response to your E-Mail after which you\'ll be able to communicate directly.' })) elif not contact_name or len(str(contact_name).strip()) == 0: # Name is Required self.response.out.write(json.dumps({ 'error': 'The Name of the person that wants to send the Mail is required' })) elif not contact_email or len(str(contact_email).strip()) == 0 or not re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", contact_email): # An Valid E-Mail is Required self.response.out.write(json.dumps({ 'error': 'The Valid E-Mail of the user is required. This must match our pattern!' })) elif not contact_message or len(str(contact_message).strip()) == 0: # Message is required self.response.out.write(json.dumps({ 'error': 'We need a message which we will send to the user. This should include basic details such as where the user found the pet and their location or some arrange to call them.' })) else: # Generate Template to send template_locales = { 'chip': chip, 'subject': 'Contact message by User who searched for #' + str(chip.uid), 'sender_name': str(contact_name).strip(), 'sender_email': str(contact_email).strip(), 'message': str(contact_message).strip(), 'provider': provider } # The Form parameters were validated mailer.send( to=str(chip['owner']['email']), reply_to=str(template_locales['sender_email']), subject=str(template_locales['subject']), view='mail/contact_from_search.html', locales=template_locales) # Update to show that the E-Mail was sent single_response.email_sent = True single_response.email_sent_from = str(contact_email).strip() single_response.email_sent_name = str(contact_name).strip() single_response.email_sent_text = str(contact_message).strip() single_response.put() self.response.out.write(json.dumps({ 'message': 'Success E-Mail was sent !', 'status': True })) else: # This was not a succesfull search ! self.response.out.write(json.dumps({ 'error': 'This was not a succesfull search.' })) else: # Search not found or expired self.response.out.write(json.dumps({ 'error': 'Either your search could not be found or it has expired. Searches are only valid for ' + str(runner.EXPIRES_AFTER) + ' minutes after their last action' })) else: # self.response.out.write(json.dumps({ 'error': 'No Search Key Provided' })) else: # Inform them self.response.out.write(json.dumps({ 'error': 'No such client found. Invalid Token !' })) else: # Inform them self.response.out.write(json.dumps({ 'error': 'No Client token was given. Please login and create a client to start searching from our providers' }))