def permission_check(__id, frame,log_time): ''' This function is to check permission to access. It checks permission using visitor's id. (access value is 'true' or 'false') Then, it saves the log about all visitors. If the visitor doesn't have permission to access, led blinks 2 times and door stays close. Otherwise, if the visitor has permisson, it sends an email to the visitor about their entrance, then led blinks once. ''' # Check permission to access db_visitors = mongo_db.smartbell.visitors try: valid = db_visitors.find_one({"_id": ObjectId(__id[0])}) except EOFError: return 0 save_log(valid['firstname'], valid['lastname'], frame, valid['_id'], log_time, valid['access']) # If permission to access is true, if valid['access']: print("Available face") send_email.email(valid['email'],valid['firstname'],valid['lastname'],log_time) led() else: print("No permission, closed") for n in range(2): led()
def main(): # TIME start = time.time() # GET ALL THE ARTICLE LINKS # CBC get_articles(cbc, CBC) # CNBC get_articles(cnbc, CNBC) # ScienceDaily get_articles(science_daily, ScienceDaily) # ScienceNews get_articles(science_news, ScienceNews) # TechCrunch get_articles(tech_crunch, TechCrunch) # PRINT OUT THE SUMMARIZATION OF EACH ARTICLE NewsPage.clear_storage() for href in AggregatorFirefox.links_of_articles: NewsPage(href) for href in AggregatorChrome.links_of_articles: NewsPage(href) # CALCULATE ELAPSED TIME end = time.time() print(f"Elapsed time: {end - start}") # SEND THE EMAIL FROM ARTICLE_STORAGE.TXT email()
def process_image(data, model): # guardar imagen para procesar fit = True filename, exif = save_image_to_process(data, fit) # procesar imagen path_styled = 'process/' + str( time.time()) + '_' + data['name'] + '_' + data['estilo'] + data['ext'] os.system('python neural_style/neural_style.py eval --content-image ' + filename + ' --model ' + model + ' --output-image ' + path_styled + ' --cuda 1') while not os.path.exists(path_styled): process = True # styled con marco border = (not 'ppm_sm_pd' in filename) # and (data['evento'] == 'CL') if border: image.printeable_image(path_styled, exif) # upload image styled print('subir imagen') r = upload_image(path_styled, data) if not r: return False, 'Error al subir la imagen' # enviar correo sender.email([data['correo']], [path_styled]) # borrar imagenes if not save_images: os.remove(filename) os.remove(path_styled) return True
def email_create(self, sub, msg): ''' sends the email ''' config = read() sender = self.team_name.replace(' ', '-') + '*****@*****.**' email(sub, msg, sender, config)
def rsvp(): data = json.loads(request.data) msg = "%s wants to attend the next talk. They can be contact at %s" % (data['name'], data['email']) try: email( subject="DevTalks: RSVP", fro="*****@*****.**", to='*****@*****.**', msg=msg) return Response(status=200) except: return Response(status=500)
def requesttalk(): data = json.loads(request.data) print data msg ="%s would like to a talk about %s, they can be reached at %s and " % (data['requester_name'], data['suggested_topic'], data['requester_email']) if data['can_present'] == 'on': msg = msg + "they are willing to present." else: msg + msg + "they are not willing to present." try: email( subject="DevTalks: A talk has been requested:", fro="*****@*****.**", to='*****@*****.**', msg=msg) return Response(status=200) except: return Response(status=500)
def sendEmail(): from send_email import email import os while True: crawler.finished.get() exmail = email() exmail.set_from("*****@*****.**") exmail.set_to("*****@*****.**") exmail.set_subject("xiecheng%s" % setting["start_date"]) print os.getcwd()+"/xiecheng%s.csv" % setting["start_date"] exmail.add_attachment(os.getcwd()+"/xiecheng%s.csv" % setting["start_date"]) exmail.send() # exmail.set_to("*****@*****.**") # exmail.send() crawler.finished = AsyncResult()
def main(): config = configparser.ConfigParser() config.read('config.ini') username = config['sineserver']['username'] password = config['sineserver']['password'] server = config['sineserver']['server'] db = config['sineserver']['database'] sys_type = platform.system() py_file_path = os.path.dirname(os.path.realpath(__file__)) if sys_type == 'Windows': filepath = py_file_path + '\\report_exports\\' logpath = py_file_path + '\\logs\\' else: filepath = py_file_path + '//report_exports//' logpath = py_file_path + '//logs//' dt = datetime.datetime.now().strftime("%Y_%m_%d") logfile = 'ssrs_downloads_' + dt + '.log' fn = logpath + logfile logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # create file handler if logger.handlers: logger.handlers = [] handler = logging.FileHandler(fn) handler.setLevel(logging.INFO) # create logging format formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%m-%d-%Y %I:%M:%S %p') handler.setFormatter(formatter) # add the handlers to the logger logger.addHandler(handler) logger.info("-"*40) logger.info('Started') rpt_pass = [] rpt_fail = [] email_pass = [] email_fail = [] try: cnxn = pyodbc.connect('Driver={ODBC Driver 13 for SQL Server};' r'Server='+ server +';' r'Database='+ db +';' r'UID='+ username +';' r'PWD='+ password +';') logger.info("SQL connection complete.") except: logger.info("SQL connection failed") return False # PULL REPORT DATA FROM SQL SERVER cursor = cnxn.cursor() cursor.execute(""" SELECT RPT_EXPRT_DIM_ID ,[RPT_NM] ,[RPT_FILE_NM] = RPT_FILE_NM + CAST(year(getdate()) as varchar(4)) +'-'+case when len(month(getdate())) = 1 THEN '0' + cast(month(getdate()) as varchar(2)) ELSE CAST(month(getdate()) as varchar(2)) END +'-' +case when len(day(getdate())) = 1 THEN '0' + cast(day(getdate()) as varchar(2)) ELSE CAST(day(getdate()) as varchar(2)) END ,[RPT_CONN_NM] ,[RPT_SRVR_LOC_DESC] ,[RPT_EXPRT_SUFFIX_DESC] ,[RPT_EXPRT_FILE_TYP] = CASE WHEN [RPT_EXPRT_FILE_TYP] = '.xls' THEN 'excel' ELSE 'pdf' END FROM [ICG_WORK].[work].[RPT_EXPRT_DIM] WHERE 1=1 AND ACTV_IND = 1 AND EXPIR_DT IS NULL """) logger.info("SQL cursor executed") # EXPORT REPORTS for row in cursor: try: # print(row.RPT_EXPRT_FILE_TYP,row.RPT_SRVR_LOC_DESC,row.RPT_FILE_NM, filepath) get_rpt(row.RPT_EXPRT_FILE_TYP,row.RPT_SRVR_LOC_DESC,row.RPT_FILE_NM, filepath) rpt_pass.append([row.RPT_EXPRT_DIM_ID,row.RPT_NM]) logger.info("\tSUCCESS! Report ID: {0} \t| Name: {1}".format(row.RPT_EXPRT_DIM_ID,row.RPT_NM)) except: rpt_fail.append([row.RPT_EXPRT_DIM_ID,row.RPT_NM]) logger.warning("\tFAIL! Report ID: {0} \t| Name: {1}".format(row.RPT_EXPRT_DIM_ID,row.RPT_NM)) # LOG REPORT OUTPUT pass_rpts = len(rpt_pass) fail_rpts = len(rpt_fail) total_rpts = pass_rpts + fail_rpts # pass reports logger.info("{0} of {1} reports downloaded successfully.".format(pass_rpts,total_rpts)) # fail reports logger.info("{0} of {1} reports failed to download.".format(fail_rpts,total_rpts)) logger.info("Downloads complete") cursor.close() #--------------------------------------------------------------------------------------------------------------- rpt_list = [] rpt_ids = '' #prepare email list for rpt in rpt_pass: rpt_list.append(rpt[0]) rpt_ids = ','.join(str(x) for x in rpt_list) logger.info("Sucessful report ids: {0}".format(rpt_ids)) cursor = cnxn.cursor() sql = """ SELECT A.RPT_EXPRT_DIM_ID ,B.RPT_EXPRT_EMAIL_DIM_ID ,B.USER_EMAIL ,A.[RPT_NM] ,[RPT_FILE_NM] = A.[RPT_FILE_NM] + CAST(year(getdate()) as varchar(4)) +'-'+case when len(month(getdate())) = 1 THEN '0' + cast(month(getdate()) as varchar(2)) ELSE CAST(month(getdate()) as varchar(2)) END +'-' +case when len(day(getdate())) = 1 THEN '0' + cast(day(getdate()) as varchar(2)) ELSE CAST(day(getdate()) as varchar(2)) END + [RPT_EXPRT_FILE_TYP] FROM [ICG_WORK].[work].[RPT_EXPRT_DIM] A LEFT JOIN work.RPT_EXPRT_EMAIL_DIM B ON B.RPT_EXPRT_DIM_ID = A.RPT_EXPRT_DIM_ID WHERE 1=1 AND A.ACTV_IND = 1 AND A.EXPIR_DT IS NULL AND B.EXPIR_DT IS NULL AND A.RPT_EXPRT_DIM_ID IN (""" + rpt_ids + """) """ # AND B.USER_EMAIL = '*****@*****.**' # print(sql) cursor.execute(sql) logger.info("SQL email cursor executed") logger.info("Begin email routine") # Email REPORTS for row in cursor: rptnm = 'Attached Report: ' + row.RPT_NM body = """ <p>""" + row.RPT_NM + """ report is attached.</p> <p>Please reply to this message with any questions.</p> <p>Thank you,</p> <p>Sine Analytics</p> """ try: email(row.USER_EMAIL, rptnm, body, filename=row.RPT_FILE_NM, filepath=filepath,html="yes") email_pass.append([row.RPT_EXPRT_DIM_ID,row.RPT_NM,row.USER_EMAIL,row.RPT_EXPRT_EMAIL_DIM_ID]) logger.info("\tSENT! Email ID: {0} \t| Report: {1} \t| To: {2}".format(row.RPT_EXPRT_EMAIL_DIM_ID,row.RPT_NM,row.USER_EMAIL)) except: email_fail.append([row.RPT_EXPRT_DIM_ID,row.RPT_NM,row.USER_EMAIL,row.RPT_EXPRT_EMAIL_DIM_ID]) logger.warning("email failed: {0} to {1} ".format(row.RPT_NM,row.USER_EMAIL)) # return False # LOG EMAIL OUTPUT pass_email = len(email_pass) fail_email = len(email_fail) total_email = pass_email + fail_email # pass emails logger.info("{0} of {1} emails were sent successfully.".format(pass_email,total_email)) # fail emails logger.info("{0} of {1} emails failed to send.".format(fail_email,total_email)) logger.info("emails complete") cursor.close() logger.info('Finished') email('*****@*****.**',dt + ' email export log','Log file is attached.',filename=logfile,filepath=logpath)
def main(): # Set up logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.FileHandler('logs.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logger.addHandler(handler) # Load settings with open('settings.json', 'r') as file: settings = json.loads(file.read()) os.chdir(os.path.dirname(os.path.realpath(__file__))) logger.info("Starting the script.") # Get username and password conn = sql.connect('main.db') cursor = conn.cursor() cursor.execute('SELECT * FROM users') username, password = cursor.fetchone() password = base64.b64decode(password).decode('utf-8') # Create grades table cursor.execute('CREATE TABLE IF NOT EXISTS grades (username, unid, course, type, lecturer, assessment)') conn.commit() conn.close() # Get a session object session = My2Session(username, password) session.login() # Constantly check for new grades logger.info('Checking for grades every {} seconds.'.format(settings['reload_interval'])) while True: resp = session.get(GRADES_URL) if resp.status_code != 200: # Re-initialize the session if status code is 500 if resp.status_code == 500: logger.warning("500 status code, restarting session.") session = My2Session(username, password) session.login() continue else: logger.warning("{} status code, quitting.".format(resp.status_code)) exit(1) # Check if there are new grades soup = BeautifulSoup(resp.content.decode('utf-8'), 'html.parser') current_grades = [i for i in extract_grades(soup)] if len(current_grades) > len(get_old_grades(username)): logger.info("Found new grades") new_grades = get_new_grades(current_grades, username) print(new_grades) # Send email send_email.email('ISM Grades', '{}@stud.ism.lt'.format(username), grades_to_text(new_grades)) logger.info('Email sent') # Upload new grades to the database conn = sql.connect('main.db') cursor = conn.cursor() cursor.execute('DELETE FROM grades') cursor.executemany('INSERT INTO grades VALUES (?, ?, ?, ?, ?, ?)', [[username] + list(i.values()) for i in current_grades]) conn.commit() conn.close() # Waitl time.sleep(settings['reload_interval']) if datetime.now().hour == settings['night_hour']: logger.info('Resting until {}'.format(datetime.now() + timedelta(hours=settings['night_duration']))) time.sleep(settings['night_duration']*60*60) logger.info('Continuing.')
) trace1 = Scatter( x=range(len(data)), y=data, mode='markers' ) trace2 = Scatter( x=range(len(allowance)), y=allowance, mode='lines' ) data2 = Data([trace0, trace1, trace2]) py.image.save_as({'data': data2}, 'testing.png') #plot_url = py.plot(data, filename='line-scatter') flag = 0 b = email(Dictionary.HDTV.name, Dictionary.HDTV.price, Dictionary.HDTV.store, z[0], (z[1] > 50)) for i in fit: if i > allow and flag == 0: b.run() flag = 1 fp = open('index.html', 'r') string = (fp.read()) fp.close() for i in range(len(you)): string += "<tr> <td> "+str(you[i])+" </td> <td> "+str(purchases[i])+" </td> <td> "+str(times[i]+1)+" </td>" string += "</div> </div> <div> </div> </body> </html>" string += "</div> </div> <ul> <li>Average spending per day: $"+ str(int(np.average(purchases))) +"</li> <li> Adjusted average spending per day: $"+str(int(p[1]))+"</li> <li> Highest expenditure: $"+str(int(max(purchases)))+" on a "+str((you[purchases.index(max(purchases))]))+"</li> <li> Projected spending for the month: $"+str(int(max(fit)))+"</li> </body> </html>" fp = open('templates/index.html', 'w+') string = (fp.write(string)) fp.close()
from send_email import email email()
#check until when the updates should be made now = datetime.datetime.now() year = now.strftime("%Y") month = now.strftime("%m") day = now.strftime("%d") #Invoices should only be created once a month for the last month! #We will create a list of month_to_invoice list_of_month_to_invoice = [] #that's the list! year_to_invoice = int(last_update_year) #int year month_to_invoice = int(last_update_month) #init month #create email instance sender=send_email.email() while year_to_invoice < int(year): if month_to_invoice > 12: month_to_invoice = 1 while month_to_invoice <= 12: text=str(year_to_invoice) text+='-' if len(str(month_to_invoice)) <= 1: text \ += '0' text+=str(month_to_invoice) text+='-' text+=str(calendar.monthrange(year_to_invoice, month_to_invoice)[1]) list_of_month_to_invoice.append(text) month_to_invoice+=1
import nse_download import send_email try: nse_download.main() except: send_email.email(mail_flag='fail') else: send_email.email(mail_flag='pass')
def process(frame, count=0): cv2.imwrite('donga.jpg', frame) if face('donga.jpg') == 1: print("Good") else: email('donga.jpg')
:param names: a list of short names contained in the address.keys(), non-existing name will be ignored :return: a list of email addresses corresponding to the names given """ # emails = [] # for name in names: # if name in address.keys(): # emails.append(address[name]) # else: # print('%s is not in the address lists, email won\'t be sent to this user' % name) # return emails return [address[name] for name in names if name in address.keys()] # list comprehension for page in range(page_num): check_sku(page + 1) # print(tmp) if len(output) > 0: print(output) recipients = name_to_email(['jz']) email(subject='!! Duplicate sku found !!', recipients=recipients, body='Please check logs') else: print('Congratulations, no duplicate sku!') recipients = name_to_email(['jz']) email(subject='No duplicate sku', recipients=recipients, body='Congratulations, no duplicate sku!')
def __init__(self, session, fabman_id): sender = email() self.has_billingAddress=False url = str("https://fabman.io/api/v1/members/" + str(fabman_id)) result = session.get(url) memberdata = result.json() self.id = fabman_id self.email = memberdata['emailAddress'] self.address = str(memberdata['address']) if memberdata['address2']: self.address+=' ' self.address += str(memberdata['address2']) self.city = memberdata['city'] self.zip = memberdata['zip'] self.country = memberdata['countryCode'] self.firstname = memberdata['firstName'] self.lastname = memberdata['lastName'] self.company = memberdata['company'] if not self.company: self.company=' ' self.billingAddress= str(memberdata['billingAddress']) if memberdata['billingAddress2']: self.billingAddress+= ' ' self.billingAddress += str(memberdata['billingAddress2']) self.billingCity = memberdata['billingCity'] self.billingZip = memberdata['billingZip'] self.billingCompany = memberdata['billingCompany'] if not self.billingCompany: self.billingCompany=' ' self.billingEmail = memberdata['billingEmailAddress'] self.billingFirstName = memberdata['billingFirstName'] self.billingLastName = memberdata['billingLastName'] self.billingCountry = memberdata['billingCountryCode'] if self.billingFirstName and self.billingLastName: self.has_billingAddress=True try: self.sap = memberdata['metadata']['SAP'] except: if self.has_billingAddress: namelist = { 'firstName': memberdata['billingFirstName'], 'lastName': memberdata['billingLastName'], 'address': self.billingAddress, 'city': self.billingCity, 'ZIP': self.billingZip, 'country': self.billingCountry, 'email': self.email, 'company': self.company } else: namelist={ 'firstName':memberdata['firstName'], 'lastName': memberdata['lastName'], 'address':self.address, 'city': self.city, 'zip': self.zip, 'country': self.country, 'email': self.email, 'company': self.company } #sender.send_SAP_request(namelist) sender.add_sap_request(namelist) self.sap = ' '
def main(): logger.setLevel(logging.INFO) logfile_path = 'dcabot.log' # TODO set in constants.py fh = logging.FileHandler(logfile_path) sh = logging.StreamHandler() sh.setFormatter(log_format) fh.setFormatter(log_format) logger.addHandler(fh) logger.addHandler(sh) logger.info("Starting DCABot") if _is_test: threshold_daily_buy = 999999.0 if (not config_utils.check_files_exist()): raise FileNotFoundError("Configuration file not found.") tracked_currencies = conf.get_tracked_currencies() threshold_daily_buy = conf.threshold_daily_buy btcusd_daily_buy = conf.btcusd_daily_buy ethusd_daily_buy = conf.ethusd_daily_buy bchusd_daily_buy = conf.bchusd_daily_buy total_sought_usd = btcusd_daily_buy + ethusd_daily_buy + bchusd_daily_buy auth_client = SM.SecretsManager().cbpro_auth_client() all_accounts = auth_client.get_accounts() usd_balance = 0.0 for acct in all_accounts: if (acct['currency'] == "USD"): usd_balance = float(acct['balance']) logger.info(f"Avalable balance to trade: ${usd_balance:.2f}") if (usd_balance > threshold_daily_buy): if (usd_balance < total_sought_usd): logger.error( f"Insufficient funds to buy! \nUSD balance:\t${usd_balance}\nTotal sought:\t${total_sought_usd:.2f}" ) # TODO: # email(fail_msg) exit(1) for curr_amt_pair in tracked_currencies: this_buy = place_buy(auth_client, curr_amt_pair[0], curr_amt_pair[1]) sleep(0.05) # I dunno y if (this_buy): _confirm = confirm_order(auth_client, this_buy['id']) if (not _confirm): logger.error( "Oh shit. Your order was placed successfully, but we can't confirm that it went through." ) else: logger.info( f"Successfully bought ${curr_amt_pair[1]} of {curr_amt_pair[0]}" ) else: logger.error( f"Insufficient funds! (balance: ${usd_balance:.2f}, threshold balance: ${threshold_daily_buy:.2f})" ) email_message = """ Sup, Your daily trade was not executed because your USD balance ({}) is below your pre-defined threshold ({}). You can update this threshold amount in etc/dcabot.conf, or you can add more funds at https://pro.coinbase.com. -dcabot This script is found in {} and run in /etc/cron.daily. """.format(usd_balance, threshold_daily_buy, sys.argv[0]) if (not _is_test): email(email_message) exit(1)
from urllib.request import * os.environ["PATH"] += os.pathsep + os.getcwd() download_path = "C:/Users/Sagnik Chatterjee/Desktop/abc/" while (True): choice = input( "Enter :\n 1. To send an email \n 2. To list out broken urls \n 3. To download images \n Enter your choice \n" ) if (choice == "1"): sub = input("Enter your Subject : \t") msg = input("Enter your Message : \t") reciever = input("Enter recievers email: ") send_email.email(sub, msg, reciever) elif (choice == "2"): broken = [] url = input("Enter the desired URL :") driver = webdriver.Firefox() driver.get(url) time.sleep(3) list_links = driver.find_elements_by_tag_name('a') for i in list_links: url1 = str(i.get_attribute('href')) if validators.url(url1) == False: broken.append(url1) if broken == []: print("All links are OK.") for x in broken: