def __init__(self): self.sleep_time = 60 self.config_file_path = "config.json" self.config = ConfigReader(self.config_file_path) self.checker = MovieChecker(self.config) self.sender = EmailSender(self.config)
def _send_email(self, to, content): t = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') e = EmailSender() e.login(self._smtp_server, 25, self._user, self._passwd) e.setContent('arXiv Paper Recommendation({})'.format(t), content) e.sendEmail(self._user, [to], 'Automatic Paper Recommendation') e.logout()
def main(): email_sender = EmailSender() for name, data in get_employee_content().items(): try: form = FORMS.get(data.get('level'), NotExistLevelForms) form(name, email_sender) except Exception as err: print('Error: Main fail with {}'.format(err)) email_sender.update_message()
class BookingChecker: def __init__(self, name): """ :param name: The name of the person who is checked for double bookings. """ self.name = name self.booking_scraper = BookingScraper() self.email_sender = EmailSender() # List of bookings, each booking represented by a tuple with the format (time_interval, name). self.bookings = None # List used to keep track of previous conflicts to avoid sending multiple emails about the same conflict. self.previous_conflicts = [] def booking_checker_job(self): """Method that is called by the scheduler every 15 minutes to provide periodic checks to the booking system.""" self.bookings = self.booking_scraper.get_bookings() double_bookings = self.__check_double_booking() # Notifying the user of the conflicts if any exist. if double_bookings: self.email_sender.send_conflict_email(double_bookings) def __check_double_booking(self): """ Checks the current bookings for double bookings involving the specified name. A double booking is when the fitness room is booked by two people at the same time. :return: A list of double bookings involving the specified name. Empty list if no double bookings were found. """ double_bookings = [] # Creating a list of the bookings made by the specified name that are not in the past. name_bookings = [ booking for booking in self.bookings if booking["name"] == self.name and booking["end_datetime"] >= datetime.datetime.now() ] # Checking each booking for conflicts that would result in a double booking. for name_booking in name_bookings: for booking in self.bookings: if booking not in self.previous_conflicts: if booking["name"] != self.name: start_conflict = booking["start_datetime"] <= name_booking["start_datetime"] < \ booking["end_datetime"] end_conflict = booking["start_datetime"] < name_booking["end_datetime"] <= \ booking["end_datetime"] if start_conflict or end_conflict: double_bookings.append((name_booking, booking)) self.previous_conflicts.append(booking) return double_bookings
def __init__(self, key, language): self.key = key self.languages = { 'en': alphabet_eng, 'ru': alphabet_rus, 'de': alphabet_deu } self.language = language self.sender = EmailSender('config.txt', False)
class Notification: def _email_config(self, sender, password, stmp_url, stmp_port): self._email_sender = EmailSender(sender, password, stmp_url, stmp_port) def email_config(self, email_sender_json): self._email_sender = EmailSender(email_sender_json['email'], email_sender_json['password'], email_sender_json['stmp']['url'], email_sender_json['stmp']['port']) def send_email(self, sender_name, recipient, subject, changed_sites): logging.info('Mailing: {}:{}'.format(sender_name, recipient)) logging.debug(changed_sites) message = self._construct_message(changed_sites) message['From'] = sender_name message['To'] = recipient message['Subject'] = subject self._email_sender.send_email(recipient, message) # https://stackoverflow.com/questions/882712/sending-html-email-using-python def _construct_message(self, changed_sites): msg = MIMEMultipart('alternative') stringSites = [] for info in changed_sites: stringSites.append('{}: {}'.format(info[0], info[1])) text = '\n'.join(stringSites) stringSites = [] for info in changed_sites: stringSites.append("""\ <tr> <td style="width:20%; font-size: 16px; text-align: center; padding-top:20px">{}</td> <td style="white-space: nowrap; overflow: hidden; text-overflow:ellipsis; width:80%; padding-top:20px">{}</td> </tr>""".format(info[0], info[1])) bodyString = '\n'.join(stringSites) html = ("<html><head></head><body><table>" + bodyString + "</table></body></html>") part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) return msg
def __init__(self, name): """ :param name: The name of the person who is checked for double bookings. """ self.name = name self.booking_scraper = BookingScraper() self.email_sender = EmailSender() # List of bookings, each booking represented by a tuple with the format (time_interval, name). self.bookings = None # List used to keep track of previous conflicts to avoid sending multiple emails about the same conflict. self.previous_conflicts = []
def send_email(self, _host, _username, _password, _subject, _toaddr, _body, window): host = _host.get() username = _username.get() password = _password.get() subject = _subject.get() tolist = _toaddr.get(1.0, END).split("\n") tolist.append(self.receiver_entry.get()) body = _body.get(1.0, END) sender = EmailSender(host.split(":")[0], int(host.split(":")[1])) result = sender.send(username, password, tolist, subject, body) print(result) messagebox.showinfo("Info ", result) window.destroy()
def __notifyByEmail(self, msg): host = self.config.get('email', 'host') port = self.config.get('email', 'port') username = self.config.get('email', 'username') password = self.config.get('email', 'password') email_sender = EmailSender(host, port, username, password) to_addr = self.config.get('email', 'recipient') from_addr = self.config.get('email', 'from_addr') if email_sender.isValidEmailAddress(to_addr): self.logger.info('Sending notification email to %s' % to_addr) email_sender.send(from_addr, to_addr, 'IP address changed', msg) else: self.logger.error('Invalid email recipient: %s' % to_addr)
def start_main_task(dataframe): now = datetime.now() dt_string = now.strftime("%Y_%m_%d_%H_%M") for i, server_info in dataframe.iterrows(): name, ip, model = server_info[:3] device = FireWallDevice(name , ip , model.lower() , store_path=dt_string) device.get_firewall_credential() if device.login(): device.run_all_commands() device.logout() else: print(f"fail to connect to {name}/{ip}") zipf = zipfile.ZipFile(f'{dt_string}.zip', 'w', zipfile.ZIP_DEFLATED) zipdir(f'{dt_string}', zipf) zipf.close() shutil.rmtree(dt_string) EmailSender.send(f'{dt_string}.zip') os.remove(f'{dt_string}.zip')
class MovieNotifier: def __init__(self): self.sleep_time = 60 self.config_file_path = "config.json" self.config = ConfigReader(self.config_file_path) self.checker = MovieChecker(self.config) self.sender = EmailSender(self.config) def run(self): found_movie = False while not found_movie: if self.checker.check_movie(): self.sender.notify() found_movie = True else: print("Sleep %i seconds" % self.sleep_time) time.sleep(self.sleep_time)
def send_notification(self, status, subject, message): ColorPrint.info("Send message {0}".format(message)) list_of_providers = self.provider.split(",") if len(list_of_providers) == 0 or not self.notify: ColorPrint.err("Notification providers list is empty or notification disabled.") else: for provider in list_of_providers: if status is True: subject += " Successful" else: subject += ' Failed' if provider == "telegram": ColorPrint.info("Send telegram message") telegram = TelegramSender(None) telegram.send_message(self.chat_id, subject + '\n\n' + message) if provider == "email": ColorPrint.info("Send email message") email_sender = EmailSender(None, None, None, None) email_sender.send_message(self.recipient, subject, message, status)
async def check_email(request): post_data = await request.post() log.debug("POST check_email request with post_data -> {post}", extra = {"post": post_data}) try: email = post_data['email'] MySqlCon.get_instance().check_email(email) #EmailSender(post_data['email'], Emairandom.randint(2345600000000, 2345700000000)) code = random.randint(1000, 9999) EmailSender(email, code) RedisCon.get_instance().setCode(email, code) except Exception: log.exception('POST get_info request wasn`t done') return json_response({'status': '400', 'message': 'Wrong credentials'}, status=400) return json_response({'status' : 'ok', 'message': 'Receipt was saved'}, status=200)
class DMessageEngine(): def __init__(self, key, language): self.key = key self.languages = { 'en': alphabet_eng, 'ru': alphabet_rus, 'de': alphabet_deu } self.language = language self.sender = EmailSender('config.txt', False) def report_key(self): return (('Используем ключ: {}').format(self.key)) def report(self, begining_message): ciphered_message = ((self.cipher(begining_message))) deciphered_message = (self.decipher(ciphered_message)) print(self.report_key()) print('Исходный текст: {}'.format(begining_message)) print(('После шифрования: {}').format(ciphered_message)) print(('После дешифрования: {}').format(deciphered_message)) self.sender.send_mail(ciphered_message, self.report_key(), "DMessageEngine", 'Лёня', '*****@*****.**') def cipher(self, message): return "".join([self.cipher_letter(letter) for letter in message]) def decipher(self, ciphered): return "".join([self.decipher_letter(letter) for letter in ciphered]) def cipher_letter(self, letter): return letter def decipher_letter(self, letter): return letter
def validate_speed(cls, trackable_object, time_stamp, frame): # Initialize log file. if not cls.log_file: cls.initialize_log_file() # check if the object has not been logged if not trackable_object.logged: # check if the object's speed has been estimated and it # is higher than the speed limit if trackable_object.estimated and trackable_object.speedMPH > MAX_THRESHOLD_SPEED: # set the current year, month, day, and time year = time_stamp.strftime("%Y") month = time_stamp.strftime("%m") day = time_stamp.strftime("%d") time = time_stamp.strftime("%H:%M:%S") if SEND_EMAIL: # initialize the image id, and the temporary file imageID = time_stamp.strftime("%H%M%S%f") tempFile = TempFile() cv2.imwrite(tempFile.path, frame) # create a thread to upload the file to dropbox # and start it t = Thread(target=EmailSender.send_email(), args=(tempFile, imageID)) t.start() # log the event in the log file info = "{},{},{},{},{},{}\n".format( year, month, day, time, trackable_object.speedMPH, imageID) else: # log the event in the log file info = "{},{},{},{},{}\n".format(year, month, day, time, trackable_object.speedMPH) cls.logFile.write(info) # set the object has logged trackable_object.logged = True
class Application(): argumentsParser = ArgumentsParser() emailSender = EmailSender() network_scanner = NetworkScanner() arguments = None def initialize(self): self.arguments = self.argumentsParser.get_arguments() self.start_scanning(self.arguments.interval or 5) def start_scanning(self, interval: int): output = self.network_scanner.get_network_devices_output() print(output) if self.arguments.testing == True or self.arguments.email != None and self.arguments.pw != None: self.emailSender.send_email(self.arguments.testing, self.arguments.email, self.arguments.pw, output) if self.arguments.watch: for x in range(1, interval): b = f" Next scan in: {interval - x} seconds" + "." * x print (b, end="\r") time.sleep(1) self.start_scanning(interval)
def test_send_email(self): self.assertEqual(EmailSender.send_email(), True)
def _email_config(self, sender, password, stmp_url, stmp_port): self._email_sender = EmailSender(sender, password, stmp_url, stmp_port)
def email_config(self, email_sender_json): self._email_sender = EmailSender(email_sender_json['email'], email_sender_json['password'], email_sender_json['stmp']['url'], email_sender_json['stmp']['port'])
def getSummaryReport(request, account, symbol, datefrom, dateto, user_email): # start filter report_list = None filename = "" content = "" #email content if account is not u"" or None: filename += account + "_" content += "Account: " + account + "\n" if report_list is None: report_list = Report.objects.filter(Q(account__icontains=account)) else: report_list = report_list.filter(Q(account__icontains=account)) if symbol is not u"" or None: filename += symbol + "_" content += symbol + " " if report_list is None: report_list = Report.objects.filter(Q(symbol=symbol)) else: report_list = report_list.filter(Q(symbol=symbol)) content += "Summary Report:\n" if datefrom is not u"" or None: filename += "%s_" % datefrom.replace("-", "") content += "from %s\n" % datefrom if report_list is None: report_list = Report.objects.filter(Q(reportDate__gte=datefrom)) else: report_list = report_list.filter(Q(reportDate__gte=datefrom)) if dateto is not u"" or None: filename += "%s_" % dateto.replace("-", "") content += "to %s\n" % dateto if report_list is None: report_list = Report.objects.filter(Q(reportDate__lte=dateto)) else: report_list = report_list.filter(Q(reportDate__lte=dateto)) if report_list != None: filename += "SUMM.csv" filepath = "./temp/" + filename with open(filepath, 'wb') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerow(['Symbol', 'SOD', 'Buys', 'BuyAve', 'Sells', 'SellAve', 'EOD', 'RealizedPNL', 'UnrealizedPNL', 'Commission', 'SEC Fees', 'ECN Fees', 'Net PNL']) summary_list = getSummary(report_list.order_by("reportDate")) for summary in summary_list: report = summary_list[summary] writer.writerow([report.symbol, report.SOD, report.buys, round(report.buyAve, 2), report.sells, round(report.sellAve, 2), report.EOD, round(report.realizedPNL, 2), round(report.unrealizedPNL, 2), round(report.commission, 2), round(report.secFees, 2), round(report.ecnFees, 2), round(report.netPNL, 2)]) es = EmailSender() success, message = es.send_email(filename, content, user_email, filepath) if success: message = "Summary report will be sent to <i><strong>%s</strong></i>." % user_email os.remove(filepath) else: message = "No match reports." data = { 'message': message } return simplejson.dumps(data)
'k5': '35', 'k6': '45', 'ms_1': '200', 'ms_2': '20', 'k7': 'FAIL', 'k8': 'PASS', 'k9': 'PASS'}]] labels = ['vanilla', 'modified'] t = GetComplexTable(runs, labels, TablePrinter.CONSOLE) print(t) email = GetComplexTable(runs, labels, TablePrinter.EMAIL) runs = [[{'k1': '1'}, {'k1': '1.1'}, {'k1': '1.2'}], [{'k1': '5'}, {'k1': '5.1'}, {'k1': '5.2'}]] t = GetComplexTable(runs, labels, TablePrinter.CONSOLE) print(t) simple_table = [ ['binary', 'b1', 'b2', 'b3'], ['size', 100, 105, 108], ['rodata', 100, 80, 70], ['data', 100, 100, 100], ['debug', 100, 140, 60], ] t = GetSimpleTable(simple_table) print(t) email += GetSimpleTable(simple_table, TablePrinter.HTML) email_to = [getpass.getuser()] email = "<pre style='font-size: 13px'>%s</pre>" % email EmailSender().SendEmail(email_to, 'SimpleTableTest', email, msg_type='html')
expected_costs = ExpectedCosts(config) for cluster in all_clusters: total_expected_cost = sum([ expected_costs.get_expected_cost(order_id) for order_id in cluster.orders ]) cluster.expected_cost = total_expected_cost if __name__ == "__main__": driver_creator = DriverCreator(sys.argv) with open(CONFIG_FILE, 'r') as config_file_stream: config = yaml.safe_load(config_file_stream) email_config = config['email'] email_sender = EmailSender(email_config) print("Retrieving Amazon tracking numbers from email...") amazon_tracking_retriever = AmazonTrackingRetriever(config, driver_creator) try: groups_dict = amazon_tracking_retriever.get_trackings() except: send_error_email(email_sender, "Error retrieving Amazon emails") raise if amazon_tracking_retriever.failed_email_ids: print( "Found %d Amazon emails without buying group labels and marked them as unread. Continuing..." % len(amazon_tracking_retriever.failed_email_ids)) print("Retrieving Best Buy tracking numbers from email...")
class Company: def __init__(self, people): self.people = people self.company_state = NO_EMAIL self.last_updated = time.time() self.email_sender = EmailSender() def increment_state(self, service): if self.company_state == NO_EMAIL: self.handle_no_email_sent(service) elif self.company_state == FIRST_EMAIL_SENT: self.handle_first_email_sent(service) elif self.company_state == SECOND_EMAIL_SENT: self.handle_second_email_sent(service) elif self.company_state == THIRD_EMAIL_SENT: self.handle_third_email_sent(service) def handle_no_email_sent(self, service): self.thread_ids = self.email_sender.send_first_email(service, self.people) self.company_state = FIRST_EMAIL_SENT def handle_first_email_sent(self, service): if not self.did_get_response(service): if self.did_enough_time_pass(): thread_id = self.email_sender.send_second_email(service, self.people, self.thread_ids[-1]) self.thread_ids.append(thread_id) self.company_state = SECOND_EMAIL_SENT else: self.company_state = GOT_RESPONSE def handle_second_email_sent(self, service): if True: #not self.did_get_response(service): if self.did_enough_time_pass(): thread_id = self.email_sender.send_third_email(service, self.people, self.thread_ids[-1]) self.thread_ids.append(thread_id) self.company_state = THIRD_EMAIL_SENT else: self.company_state = GOT_RESPONSE def handle_third_email_sent(self, service): if not self.did_get_response(service): if self.did_enough_time_pass(): self.company_state = NO_RESPONSE else: self.company_state = GOT_RESPONSE def did_enough_time_pass(self): if DEBUG: return True if self.company_state == NO_EMAIL: self.last_updated = time.time() return True elif self.company_state == FIRST_EMAIL_SENT: if time.time() - self.last_updated > SECONDS_ONE_WEEK: self.last_updated = time.time() return True elif self.company_state == SECOND_EMAIL_SENT: if time.time() - self.last_updated > SECONDS_ONE_MONTH: self.last_updated = time.time() return True elif self.company_state == THIRD_EMAIL_SENT: if time.time() - self.last_updated > SECONDS_ONE_MONTH: self.last_updated = time.time() return True return False def did_get_response(self, service): for thread_id in self.thread_ids: if self.did_get_response_for_thread_id(service, thread_id): return True return False def did_get_response_for_thread_id(self, service, thread_id): thread = service.users().threads().get(userId="me", id=thread_id).execute() return len(thread['messages']) > 1
from email_sender import EmailSender if __name__ == "__main__": EmailSender().clear_all_files()
def __init__(self, people): self.people = people self.company_state = NO_EMAIL self.last_updated = time.time() self.email_sender = EmailSender()
from email_sender import EmailSender from crawler import LinkedInCrawler from data_cleaning import clean_data if __name__ == '__main__': """ This is how the workflow is supposed to run. However, if the user wants to run the program to test it, I recommend running the scripts separately as one collection of one company in one city alone is ranging between 40-45m. The user can also set a small number of pages to be searched by including the desired number(int) to be searched by inserting it as a param in the get_data function below. If the scripts are to be run separately this would be the order to run the files run the files: crawler_linkedin.py > data_cleaning.py > email_sender.py If the user doesn't want to pester the Uber's employees again just make a list with a few names(first and last) and substitute the param in send_email function. """ start = time() cities = ['São Paulo', 'San Francisco'] company = ['Uber'] # TODO: You must install ChromeDrive in your computer from https://chromedriver.chromium.org/ for selenium to work # Collects the results from the all cities and companies combinations raw_data = LinkedInCrawler.get_data(cities, company) # Clean the data cleaned_data = clean_data(raw_data) # Send the emails EmailSender.send_email(cleaned_data) total = time() - start
if current_day in WORK_DAYS: push_backup(create_backup()) else: if current_day == total_month_days: for day in WORK_DAYS: if day > current_day and not count: count += 1 push_backup(create_backup()) if __name__ == host.stats().parent().guid: if SEND_FTP: ftp = FTPClient( host=FTP_HOST, port=FTP_PORT, user=FTP_LOGIN, passwd=FTP_PASS, work_dir=FTP_WD, callback=ftp_callback, check_connection=FTP_CHECK_CONNECTION, passive_mode=FTP_PASSIVE_MODE, ) if SEND_EMAIL: EMAIL_SUBSCRIBERS = EmailSender.parse_mails(EMAIL_SUBSCRIBERS) mail = EmailSender(EMAIL_ACCOUNT) schedule.every().day.at(SCHEDULE_TIME).do(check_current_day) schedule.run_continuously()
import host import helpers default_script_name = helpers.set_script_name() logger = helpers.init_logger("Archive_stat", debug=DEBUG) from script_object import ScriptObject from date_utils import ts_to_dt import schedule from schedule_object import ScheduleObject from email_sender import EmailSender MAIL = None if MAIL_ACCOUNT: MAIL = EmailSender(MAIL_ACCOUNT) if MAIL_SUBJECT: MAIL_SUBJECT = MAIL_SUBJECT.format(server_name=host.settings("").name) else: MAIL_SUBJECT = None scr_obj = ScriptObject() if WORK_SCHEDULE: WORK_SCHEDULE = ScheduleObject(WORK_SCHEDULE) else: WORK_SCHEDULE = None channels = [] selected_channels = None if CHANNELS:
email_server_port = 465 # Port of server For SMTP SSL connection body = "This is an email sent from Python security system." email_system_address = "" # [email protected] email_system_password = "" # password commanders = ["*****@*****.**", "*****@*****.**"] # emails that can do changes to the system commands = ["arm", "disarm", "status", "sens"] # commands supported by the system system_is_armed = False firstrun = True prev_frame=None actual_frame=None image_diff_threshold = 16 emailSender = EmailSender(email_server_address, email_server_port, email_system_address, email_system_password) emailReceiver = EmailReceiver(email_server_address, email_system_address, email_system_password) ##### FUNCTION TO BE USED BY MAIN ##### def arm_system(): global system_is_armed global firstrun firstrun = True system_is_armed = True print(get_time()+" - System armed.") def disarm_system(): global system_is_armed system_is_armed = False print(get_time()+" - System disarmed.")
} logger.debug("%s: task created (%s)", task_guid, path) paths.append(path) return paths selected_channels = get_channels( SELECTED_SERVER, _parse_channel_names(SELECTED_CHANNELS) ) saver = Saver(selected_channels, SAVE_FOLDER) saver.ss.timeout_sec = SHOT_AWAITING_TIME saver.remove = REMOVE if SENDING_METHOD == "Email": saver.email = EmailSender(EMAIL_ACCOUNT) saver.email_subscribers = EmailSender.parse_mails(EMAIL_SUBSCRIBERS) saver.email.max_attachments_bytes = EMAIL_MAX_SIZE * 1024 * 1024 elif SENDING_METHOD == "FTP": saver.ftp = FTPClient( FTP_HOST, port=FTP_PORT, user=FTP_USER, passwd=FTP_PASSWORD, work_dir=FTP_WORK_DIR, passive_mode=FTP_PASSIVE_MODE, ) saver.ftp_add_relative_path = FTP_ADD_RELATIVE_PATH else: pass
fail_count += 1 if fail_count > 5: break # zip #TODO: copy to onedrive file or send to file server result = os.system('zip -r zips/%s.zip content/%s' % (this_day, this_day)) # Generate list with open("zips/list-%s.txt" % this_day, 'w+') as f: for area_articles in spider.articles: for article in spider.articles[area_articles]: f.write(article.__str__() + '\n') # send sender = EmailSender(file_path='zips/list-%s.txt' % this_day) sender.send_email() else: print("no") break else: print("no_new_article_today") print(this_day) last_day = this_day time.sleep(432) def GetArticles(): return
from email_sender import EmailSender from analysis_engine import get_news_formatted import robin_stocks as rs from secrets import robin_password, robin_username from newscatcher import Newscatcher if __name__ == '__main__': es = EmailSender() rs.login(username=robin_username, password=robin_password, expiresIn=86400, by_sms=True) tickers = list(rs.build_holdings().keys()) # message = '' # # for ticker in tickers: # for article in get_news_formatted(ticker): # message += article+'\n' # # es.send_email(f'Morning Roundup', message) rs.logout()