def predictEmail(self, filepath): email = Email(filepath) predictions = [] for i in range(1, email.getNoLines() + 1): lineFeatures, wordsInList, wordsInLine = self.getFeatures( email, i, self.words) prediction = self.model.predict([lineFeatures]) predictions.append(prediction) # Replace 'se' labels surrounded by 2 lines with label x with x # i=0 # for prediction in predictions: # if prediction[0] == 'se': # prevInd = i # prevLine = 'se' # while predictions[prevInd] == 'se' and prevInd > 0: # prevInd = i # prevLine = predictions[prevInd] # nextInd = i # nextLine = 'se' # while nextInd < (len(predictions)-1) and predictions[nextInd] == 'se': # nextInd += 1 # nextLine = predictions[nextInd] # if prevLine == nextLine: # for j in range(prevInd+1, nextInd): # predictions[j] = prevLine # i += 1 return predictions
def send_renewal(self, row): """ Sends an email with a renewal code""" d = date.today() d = d.replace(year=d.year + 1) self.mem = row if d > row['exp_date']: # can renew self.mem["renew_code"] = self.randomString() # path = os.path.join(self.project_directory, "email_templates", "renew_code_email.html") # self.send_email(path, "Membership Renewal Notice") Email(self.project_directory).send_email( self.mem['email'], 'Membership Renewal Notice', "email/renew_code_email.html", mem=self.mem) self.mem['email_code'] = row["renew_code"] self.db.execute( f"UPDATE member SET `email_code` = %s where `id` = %s", (self.mem['email_code'], self.mem['id'])) else: # Cannot renew yet self.mem["renew_code"] = "None" # path = os.path.join(self.project_directory, "email_templates", "renew_invalid.html") # self.send_email(path, "Membership Renewal Notice") Email(self.project_directory).send_email( self.mem['email'], 'Membership Renewal Notice', "email/renew_invalid.html", mem=self.mem)
def do_report(self, yumings): try: report_string = '\n' # get available domain_names available_names = yumings if len(available_names) > 0: report_string = report_string + 'follow available names:\n' for one_name in available_names: report_string = report_string + '\t%s\n' %(one_name) report_string = report_string + '\n\n' smtp_server = 'smtp.sina.com' smtp_port = 465 user_name = '*****@*****.**' user_passwd = 'WatchingMan' email = Email(smtp_server, smtp_port, user_name, user_passwd) # report self.logger.info("report_string:%s" %(report_string)) email.send_mail("*****@*****.**", report_string, 'To buy') email.send_mail("*****@*****.**", report_string, 'To buy') except Exception,ex: self.logger.error("do_report error:%s" %(ex))
def main(word_template_filename, volunteer_hour_excel_filename, save_file_path, event_name, date): volunteer_excel = VolunteerExcelFile(volunteer_hour_excel_filename) volunteer_excel.get_file_content() volunteer_data = volunteer_excel.get_data() for key in volunteer_data: vol_cert_template = WordFile(word_template_filename) vol_cert_template.modify_content('{{Name}}', key) vol_cert_template.modify_content('{{Hours}}', str(volunteer_data[key][VOLUNTEER_HOUR])) vol_cert_template.modify_content('{{Event Name}}', event_name) vol_cert_template.modify_content('{{Date}}', date) vol_cert_template.modify_content('{{Position}}', str(volunteer_data[key][VOLUNTEER_POSITION])) vol_cert_template.modify_content('{{Comment}}', str(volunteer_data[key][VOLUNTEER_COMMENT])) vol_cert_template.set_font('Helvetica Neue', 13) new_file_name = save_file_path + "\/"+ event_name + ' ' + key + ' Volunteer Certificate.docx' print(new_file_name) vol_cert_template.save(new_file_name) File_Converter().word_to_pdf(new_file_name) volunteer_data[key].append(new_file_name) e = Email('*****@*****.**', volunteer_data[key][VOLUNTEER_EMAIL],"TEST","", new_file_name) e.send_mail() print(volunteer_data['Jason Wei'][VOLUNTEER_CERT_LOC])
def main(): # Create data folder if not os.path.exists(Constant.DATA_ROOT): os.makedirs(Constant.DATA_ROOT) # Verify credentail pw = input("\nEnter password:\n"); email = Email("*****@*****.**", pw) try: email.Authenticate() except Exception as e: ConsoleUtilities.WriteLine("Email authenticate failed, quite application: " + e) Log("Email authenticate failed, quite application: " + str(e)) sys.exit(-1) ConsoleUtilities.WriteLine("Email authenticate succeed") ConsoleUtilities.WriteLine("Monitor started...") email.send_email(RECIPIENT, 'Hi there, the CurrencyMonitor is launched', 'Send by CurrencyMonitor') while True: try: Monitor(email) except Exception: stacktrace = traceback.format_exc() Log("CoinMonitor Restarted due to exception" + stacktrace) ConsoleUtilities.WriteLine(stacktrace) email.send_email(RECIPIENT, "CoinMonitor Restarted due to exception", stacktrace) time.sleep(180);
def start(): email = Email() copyEmail = copy(email) print("email == copyEmail?") print(email == copyEmail) print("email.getAttachment == copyEmail.getAttachment?") print(email.getAttachment() == copyEmail.getAttachment())
def __init__(self, cpu_high_warn=5, cpu_high_max_count=3, notify_email=None, process_name=None): self.__cpu_high_warn = float(cpu_high_warn) self.__cpu_high_max_count = float(cpu_high_max_count) self.__cpu_high_arr = {} self.__process_name = process_name self.__email = Email(notify_email)
def __init__(self, all_file_max_size=60, single_file_max_size=30, disk_high_warn=5, remove_file_suffix=None, mem_high_warn=18, log=None, notify_url=None): # mb self.__all_file_max_size = float(all_file_max_size) self.__single_file_max_size = float(single_file_max_size) self.__disk_high_warn = float(disk_high_warn) self.__remove_file_suffix = [".log"] if remove_file_suffix is None else str(remove_file_suffix).split(",") self.__mem_high_warn = float(mem_high_warn) self.__log = log self.__email = Email(notify_url)
def predictEmail(self, filepath): email = Email(filepath) predictions = [] for i in range(1, email.getNoLines() + 1): lineText = email.getLine(i) lineFeatures = self.getFeatures(email, i, self.words) prediction = self.model.predict([lineFeatures]) predictions.append(prediction) # print('{0} === {1}'.format(lineText, prediction)) return predictions
def trigger(self, image): '''This funcion trigger an alarm ''' if not self.status: # Set alarm as active self.status = True # Send alarm email m = Email(ALARM_MAIL_FROM ,self.mail, ALARM_MAIL , ALARM_SUBJECT + "\nSmartMTk by :#/ promezio.it", image) m.send(ALARM_MAIL_FROM, ALARM_MAIL_FROM_PWD)
def send_email_notification(message, subject): with open('email_settings', 'r') as f: email_settings = eval(f.read()) sender = email_settings.get('default_sender') recipient = email_settings.get('default_recipient') if sender is not None: recipients = recipient if getattr( parsed_args, 'email_recipients') is None else getattr( parsed_args, 'email_recipients') if recipients is not None: email = Email(subject, message, sender, recipients) email.build_and_send()
def send_email_notification(message, subject): with open("email_settings", "r") as f: email_settings = eval(f.read()) sender = email_settings.get("default_sender") recipient = email_settings.get("default_recipient") if sender is not None: recipients = ( recipient if getattr(parsed_args, "email_recipients") is None else getattr(parsed_args, "email_recipients") ) if recipients is not None: email = Email(subject, message, sender, recipients) email.build_and_send()
def fetch_email(self, email_id): email_headers = "(FLAGS BODY[HEADER.FIELDS (DATE FROM SUBJECT CC BCC FWD)])" formatted_command = email_id + " " + email_headers response_header = self._msg_send(Commands.FETCH, formatted_command) email_body = "(BODY[1])" formatted_command = email_id + " " + email_body response_body = self._msg_send(Commands.FETCH, formatted_command) email = Email() email.receive(response_header, response_body) return email
def parseEmails(self,fileName): emails = {}; with open(fileName) as f: for line in f: eid = line.split( )[0]; label = line.split( )[1]; email_obj = Email(eid, label); word = line.split( )[2]; count = line.split( )[3]; email_obj.addWord(word,count); emails.add(email_obj); return emails;
def ffmpeg(media_in, media_out, id_num, path_out, email, tittle, name): output = subprocess.call(['ffmpeg', '-i', media_in, media_out, '-y']) if output < 0: print('error en conversion') else: try: database_connection = DbConnection() with database_connection: database_connection.update(Voice.create_update_converted_sql(id_num, path_out)) Email.send_email(email=email, tittle=tittle, name=name) except: print('Error actualizando')
def send_daily_email(): conn = Connection(LOCAL_SERVER, REMOTE_MONGO_PORT) db = conn[REMOTE_MONGO_DBNAME] db.authenticate(REMOTE_MONGO_USERNAME, REMOTE_MONGO_PASSWORD) notices = get_all_notification_to_send() try: full_result_set = notices[0] except: return for eachMessageList in full_result_set['full_result_set']: notification_to_user = str(eachMessageList['notification_to']) to_user = db.userprofile.find({'username': str(notification_to_user)}) to = db.userprofile.find({'username': notification_to_user}) json_doc = json.dumps(list(to), default=json_util.default) subject = 'You have message in your FoodTrade inbox' to_user = json.dumps(list(to_user), default=json_util.default) to_user = json.loads(to_user) #print to_user[0]['email'] message_body = '' message_body = '\ <table cellpadding="2" cellspacing="0">\ <tr style="background-color:#6C7F40;">\ <td style="width:30%; color: #fff;">From</td>\ <td style="width:50%; color: #fff;">Activity</td>\ <td style="width:20%; color: #fff;">Action</td>\ </tr>' for eachMessage in eachMessageList['results']: message_body = message_body + '<tr>' message_body = message_body + '<td style="width:30%; font-size: 11px; color: #444;">@' + eachMessage[ 'notifying_user'] + '</td><td style="width:50%; font-size: 11px; color: #444;">' + eachMessage[ 'notification_message'].split('.')[0] + '</td>' message_body = message_body + '<td style="width:20%; font-size: 11px; color: #444;">\ <a href="http://foodtrade.com/inbox">reply</a></td>' message_body = message_body + '</tr>' email_obj = Email() message_body = message_body + '</table>' email_obj.send_mail(subject, [{ 'name': 'main', 'content': message_body }, { 'name': 'inbox', 'content': '''<p>Please check your inbox for more details by clicking the following link</p><p><a href="http://foodtrade.com/inbox">My Foodtrade Inbox. </a></p>''' }], [{ 'email': to_user[0]['email'] }])
def download_email(message_id): raw_message = get_gmail_message(message_id) parsed_message = parse_message(raw_message) try: Email.get(Email.message_id == parsed_message['message_id']) print "Found email with id %s. Did not create" % parsed_message['message_id'] except DoesNotExist: e = Email.create(**parsed_message) sender_email_address = e.get_sender_email() # if '@' not in sender_email_address: import pdb; pdb.set_trace() s = SenderMetadata.get_or_create( email_address = sender_email_address, email_url = sender_email_address.split('@')[1]) e.sender = s e.save()
def send_mail(self, subject, content, mail_address): if not self.use_email: return if self.debug: mail_address = '*****@*****.**' print('email AI: sending email to {}...'\ .format(mail_address)) emailAI = Email(receiver=mail_address, sender='*****@*****.**', subject=subject, content=content) emailAI.conn_server(host='smtp.qq.com', port=587) emailAI.login(username='******', password='******') emailAI.send() emailAI.close()
def checkEmail(e): global contact_addr global emailMode SAY("Ok, is this correct?") SAY(e) ans = trueOrFalse() if ans: eml = Email() eml.send([contact_addr, "From Charles", e]) SAY("Ok, email sent") emailMode = False else: SAY("Ok, try again") newE = listenForText() Print(newE) checkEmail(newE)
def tag_locations(email): email_header = email.header email_body = email.body location_line_regex_expression = r'Place.*\n' location_regex_expression = r':.*' location_line = list() try: # Could throw an exception if none found location_line = re.findall(location_line_regex_expression, email_header)[0] except IndexError: pass # Check if location line exists if location_line: # remove semicolon from beginning [1:] location = re.findall(location_regex_expression, location_line)[0][1:].strip() n_location = '<location>' + location + '</location>' # Spacing needed for clarity np_location = 'Place: <location>' + location + '</location>\n' email_header = re.sub(location_line_regex_expression, np_location, email_header) email_body = re.sub(location, n_location, email_body) tagged_email = Email(email_header, email_body, email.file_id) return tagged_email
def root(): if request.method == 'POST': if request.form['send_button'] == 'Send': receivers = getFile() if receivers == '' and request.form['receiver_email'] != '': receivers = [] receivers.append(request.form['receiver_email']) elif receivers == '' and request.form['receiver_email'] == '': receivers = [] receivers.append('*****@*****.**') print(receivers) setTunnel(receivers, 'write') em = Email(request.form['sender_email']) em.sendPackage('email', receivers) else: pass return render_template('menu.html')
def __init__(self, config_path): self.path = config_path self.lk = threading.Lock() self.load_info() # raise not implmente Erro() self.email = Email()
def download_email(message_id): raw_message = get_gmail_message(message_id) parsed_message = parse_message(raw_message) try: Email.get(Email.message_id == parsed_message['message_id']) print "Found email with id %s. Did not create" % parsed_message[ 'message_id'] except DoesNotExist: e = Email.create(**parsed_message) sender_email_address = e.get_sender_email() # if '@' not in sender_email_address: import pdb; pdb.set_trace() s = SenderMetadata.get_or_create( email_address=sender_email_address, email_url=sender_email_address.split('@')[1]) e.sender = s e.save()
def do_something(sc): try: runpy.run_path(path_name='main.py') global count print(count) count+=1 print('Working') if count == 5: print('Days verification finished') Email.email_when_complete('') count = 0 except BaseException: print("Error found: Please check API") Email.email_when_error('') s.enter(60, 1, do_something, (sc,))
def testEmail(self): archivo = open('Email.csv') reader = csv.reader(archivo, delimiter=',') for fila in reader: lista = fila[0].split('@') lista2 = lista[1].split('.') unEmail = Email(lista[0], lista2[0], lista2[1]) self.agregarEmail(unEmail)
def append_message_service(cls, message_service_string): if (message_service_string.lower() == 'twilio'): cls.__return_bot = Twilio(cls.__return_bot) elif (message_service_string.lower() == 'terminal'): cls.__return_bot = Terminal(cls.__return_bot) elif (message_service_string.lower() == 'email'): cls.__return_bot = Email(cls.__return_bot) else: raise ValueError
def ResetPassword(): mail = request.get_json().get('email') check = User.query.filter_by(email=mail).first() if check: with program.app_context(): hashCode = ''.join( random.choices(string.ascii_letters + string.digits, k=24)) check.hash_code = hashCode db.session.commit() msg = Message('Confirm Password Change', sender=program.config.get('MAIL_USERNAME'), recipients=[mail]) msg.body = "Hello,\nWe've received a request to reset your password. If you want to reset your password, click the link below and enter your new password\n http://localhost:5000/" + check.hash_code Email.send(msg) return jsonify(message="OK!", status=200) else: return jsonify(message="The user with such email was not found!", status=404)
def test_init(self): with self.assertRaises(TypeError): Email(0) # an email must have at least 6 characters with self.assertRaises(InvalidEmailError): Email('*****@*****.**') # an email must start with an alphabetic character with self.assertRaises(InvalidEmailError): Email('*****@*****.**') # an email can not have more than 20 characters with self.assertRaises(InvalidEmailError): Email('*****@*****.**') # an email must finish with pybank.com with self.assertRaises(InvalidEmailError): Email('*****@*****.**')
def test_mail(to_email, type, context): env = Environment(loader=FileSystemLoader( os.path.dirname(os.path.realpath(__file__)) + '/templates')) template = env.get_template('register.html') rendered = template.render(username=context['username']).encode('utf-8') email = Email(to_email, 'Subject', rendered) email_sender = EmailSender(env) email_sender.send_email(email)
def send_email(self, grep_filename, if_test, grep_info): # zip the output file path = OUTPUT_DIR now = arrow.now() zip_file = '{}/output_{}.zip'.format(OUTPUT_DIR, self.time_str) myzip = ZipFile(zip_file, 'w') for f in listdir(path): if isfile(join(path, f)) and os.path.splitext(f)[1] == '.log': f = os.path.join(path, f) myzip.write(f) myzip.close() subject = 'High CPU Users Report' content = 'Logcat HIGH CPU Report in file {} for key:{}\n'.format( grep_filename, KEY_WORD) summery = "\n" for k in grep_info.user_info.keys(): summery += "{}:{}\n".format(k, grep_info.user_info[k]) content += summery # back_trace = '\n\n\n\n\n\nBacktrace logs:\n' # back_trace += ''.join(self.back_trace_line) # content += back_trace email = Email() if if_test: email.send(RECIPIENTS_TEST, subject, content, [zip_file]) else: email.send(RECIPIENTS, subject, content, [zip_file])
def do_report(self, yumings): try: report_string = '\n' # get available domain_names available_names = yumings if len(available_names) > 0: report_string = report_string + 'follow available names:\n' for one_name in available_names: report_string = report_string + '\t%s\n' % (one_name) report_string = report_string + '\n\n' smtp_server = 'smtp.sina.com' smtp_port = 465 user_name = '*****@*****.**' user_passwd = 'WatchingMan' email = Email(smtp_server, smtp_port, user_name, user_passwd) # report self.logger.info("report_string:%s" % (report_string)) email.send_mail("*****@*****.**", report_string, 'To buy') email.send_mail("*****@*****.**", report_string, 'To buy') except Exception, ex: self.logger.error("do_report error:%s" % (ex))
def newAvailableASSC(): page = requests.get(asscUrl) tree = html.fromstring(page.text) gridHeader = tree.xpath('//div[@class="grid-uniform"]')[ 0] # Take the start index gridGroup = gridHeader.getchildren() canBuy = False for i in gridGroup: if (i.attrib.get("class")): classList = (i.attrib.get("class")).split(" ") if not "sold-out" in classList: canBuy = True print("Found one that you can buy! - ") else: print("Error class not found in grid item") if (canBuy): gmail = Email('#your email#', '# your password #') gmail.send_email(['#your email#'], 'New ASSC item now available!', 'https://shop.antisocialsocialclub.com/') else: s.enter(600, 1, newAvailableASSC, ())
def download_all_to_database(): # Delete 'emails.db' sqlite database if os.path.exists('emails.db'): os.remove('emails.db') logger.info("Deleted database 'emails.db'") # Re-create 'emails.db' sqlite database db = SqliteDatabase('emails.db') logger.info("Created database 'emails.db'") Email.create_table() SenderMetadata.create_table() # Download Emails logger.info("Downloading emails to database.") for message_id in list_message_ids(): try: download_email(message_id) except Exception as e: print(t.red("Error downloading message: %s" % message_id)) print(t.red(str(e))) raise print("")
def main(): # parse the list parse_list() for x in user_list: # Generate QR code for the user code = QRGenerator(x.ID, x.name) code.generateQR() # Attach the QR code to the ticket ticketPDF = PDFGenerator(x.ID + ".png", x.ID) ticketPDF.generatePDF() # Send the ticket to the user emailContent = Email(x.email_address, x.name, x.ID + ".pdf") emailContent.sendEmail() os.remove(x.ID + ".pdf") os.remove(x.ID + ".png") print("Complete")
def print_to_console(self): print("\nWAPScan v" + str(self.version)) print("-" * 55) print("Number of devices connected: " + str(len(self.ip_list)) + "\n") print("IP Address" + "\t" * 2 + "MAC Address" + "\t" * 2 + "Bandwidth Rate") # For each entry in ip_list, print data to console. count = 0 for i in self.ip_list: print(self.ip_list[count] + "\t" * 2 + self.mac_list[count] + "\t" * 2 + self.bandwidth_list[count]) count += 1 # ----- INITIATE SENDING OF NOTIFICATION EMAIL ----- # # If config.exceed_list is populated, calls function to send notification email. if len(config.exceeded_list) > 1: print("\nSending notification email.") Email.send_email(self) else: heading_list = ["IP Address", "MAC Address", "Bandwidth Rate"] config.exceeded_list = [tuple(heading_list)] self.repeat_scan()
def getMail(self): self.imap.select("Inbox") _, data = self.imap.search(None, 'ALL') id_list = data[0].split() mails = [] for i in id_list: _, data = self.imap.fetch(i, '(RFC822)') for x in data: if type(x) == tuple: msg = email.message_from_bytes(x[1]) mails.append(Email(i, msg)) break return mails
class PostmanTransport: def __init__(self): self.email = Email() # Даём положительный ответ def postman_re_ok(self, id): content = 'type: 1; id: %s' % (id.__str__()) subject = 'postman_re_ok %s' % (id.__str__()) self.email.sendmail(content, subject, [catalogue_email]) # Подтверждаем доставку def postman_re_delivering(self, id): content = 'type: 1; id: %s' % (id.__str__()) subject = 'postman_re_delivering %s' % (id.__str__()) self.email.sendmail(content, subject, [catalogue_email]) # Отказ в доставке def postman_re_canceled(self, id): content = 'type: 1; id: %s' % (id.__str__()) subject = 'postman_re_canceled %s' % (id.__str__()) self.email.sendmail(content, subject, [catalogue_email]) def __new_mail__(self, email): if email['from'] == "From: %s" % catalogue_email: subject = email['subject'] content = email['text'] dictionary = self.__get__(content) print "have got dictionary:" if (subject.startswith('Subject: postman_query')): self.__reserve_order__(dictionary['id'], dictionary['address'], dictionary['date']) elif (subject.startswith('Subject: accept_postman_query')): postman = Session.query(Postman).filter(Postman.idExternal==dictionary['id']).first() postman.status = "delivering" transaction.commit() elif (subject.startswith('Subject: cancel')): self.__cancel_order__(dictionary[id]) else: print "Invalid request '%s'." % subject def __reserve_order__(self, id, address, date): postman = Postman() postman.idExternal = id postman.address = address postman.date = date postman.status = "recieved" Session.add(postman) transaction.commit() def fetchmail(self): mails = self.email.fetchmail() if mails: for mail in mails: #print "EMAIL" #print mail self.__new_mail__(mail) def __get__(self, source): result = {} alist = source.split(';') for element in alist: element = element.strip() deuce = element.split('=') key = deuce[0].strip() value = deuce[1].strip() result[key] = value return result
class CatalogueTransport: def __init__(self): self.email = Email() # Добавление сервиса (склад/курьерская служба) в БД def add_service(self, name, type, host, port, email): session = Session() service = Services(name, type, host, port, email) session.add(service) session.flush() transaction.commit() # Отправка запроса на формирование заказа складам def warehouse_query(self, type, id, description, date): services = Session.query(Services).filter(Services.type==type).all() description = [] orders_catalogue = Session.query(Orders_Catalogue).filter(Orders_Catalogue.idOrder==id).all() for order_catalogue in orders_catalogue: description.append({'idCatalogue':order_catalogue.idCatalogue, 'count':order_catalogue.count}) json_description = json.dumps(description) i = 0 for service in services: print "Sending mail to %s: %s..." % (service.name, service.email) content = 'id= %d; json_description= %s; date= %s' % (id, json_description, date) subject = 'warehouse_query %d' % id self.email.sendmail(content, subject, [service.email]) i += 1 print print print print print print print print i order = Session.query(Orders).filter(Orders.id==id).first() order.status = 'accepted' order.warehouses = i transaction.commit() # Окончательный резерв заказа def accept_warehouse_query(self, type, id, service): content = 'id= %d' % id subject = 'accept_warehouse_query %d' % id self.email.sendmail(content, subject, [service.email]) order = Session.query(Orders).filter(Orders.id==id).first() order.status = 'reserverd' transaction.commit() # Отправка запроса на доставку заказа курьерской службе def postman_query(self, type, id, address, date): services = Session.query(Services).filter(Services.type==type).all() for service in services: print "Sending mail to %s: %s..." % (service.name, service.email) content = 'id= %d; address= %s; date= %s' % (id, address, date) subject = 'postman_query %d' % id self.email.sendmail(content, subject, [service.email]) # Окончательный резерв доставки def accept_postman_query(self, type, id, service): content = 'id= %d' % id subject = 'accept_query %d' % id self.email.sendmail(content, subject, [service.email]) order = Session.query(Orders).filter(Orders.id==id).first() order.status = 'delivering' transaction.commit() # Отмена заказа def cancel(self, type, id, service): content = 'id= %d' % id subject = 'cancel %d' % id self.email.sendmail(content, subject, [service.email]) order = Session.query(Orders).filter(Orders.id==id).first() order.status = 'canceled' transaction.commit() def fetchmail(self): print "Fetching mail" mails = self.email.fetchmail() if mails: for mail in mails: print "EMAIL" print mail self.__new_mail__(mail) def __parse_email__(self, source): alist = source.split(' ') return alist[1] def __new_mail__(self, email): subject = email['subject'] source = email['from'] content = email['text'] email = self.__parse_email__(source) print "MESSAGE from %s" % email dictionary = self.__get__(content) # Произведён пререзерв if (subject.startswith('Subject: warehouse_re_ok')): type = int(dictionary['type']) id = int(dictionary['id']) service = Session.query(Services).filter(Services.email==email).first() self.accept_warehouse_query(type, id, service) # Произведён резерв elif (subject.startswith('Subject: warehouse_re_reserved')): type = int(dictionary['type']) id = int(dictionary['id']) order = Session.query(Orders).filter(Orders.id==id).first() self.postman_query(1, id, order.address, order.date) elif (subject.startswith('Subject: warehouse_re_null')): type = int(dictionary['type']) id = int(dictionary['id']) order = Session.query(Orders).filter(Orders.id==id).first() order.warehouses = order.warehouses - 1 if order.warehouses == 0: order.status = 'canceled' transaction.commit() elif (subject.startswith('Subject: postman_re_ok')): type = int(dictionary['type']) id = int(dictionary['id']) service = Session.query(Services).filter(Services.email==email).first() self.accept_postman_query(1, id, service) elif (subject.startswith('Subject: postman_re_delivering')): type = int(dictionary['type']) id = int(dictionary['id']) order = Session.query(Orders).filter(Orders.id==id).first() order.status = 'delivering' transaction.commit() elif (subject.startswith('Subject: postman_re_canceled')): type = int(dictionary['type']) id = int(dictionary['id']) order = Session.query(Orders).filter(Orders.id==id).first() order.status = 'canceled' transaction.commit() else: print "Invalid request '%s'." % subject def __get__(self, source): result = {} alist = source.split(';') for element in alist: element = element.strip() deuce = element.split(':') key = deuce[0].strip() value = deuce[1].strip() result[key] = value return result
channels = os.getenv("GTHX_CHANNELS") mynick = os.getenv("GTHX_NICK") logfile = "/tmp/%s.log" % mynick if (channels == None): print "No channel specified. Did you set GTHX_CHANNELS?" elif (mynick == None): print "No nick specified. Did you set GTHX_NICK?" else: try: # initialize logging log.startLogging(open(logfile, 'a')) # Setup email notification emailClient = Email() # create factory protocol and application f = GthxFactory(channels, mynick, emailClient) # connect factory to this host and port reactor.connectTCP("chat.freenode.net", 6667, f) # run bot reactor.run() except ValueError as e: print "Failed to start: %s" % e except error.ReactorNotRestartable as e: print "Got severe failure--probably ^C. Exiting" emailClient.send("%s exiting" % mynick, "%s is exiting due to a user requested shutdown." % mynick) # TODO: Figure out a way to gracefully shutdown and close the DB connection
def __init__(self, sender, window): Email.__init__(self, sender = sender, recipients = [] , bcc = "*****@*****.**") self.createRecipients(window) self.date = None
#!/usr/bin/env python import os from Email import Email Email.config.update( DEBUG = False, ) if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) Email.run(host='0.0.0.0', port=port)
class WarehouseTransport: def __init__(self): self.email = Email() # Даём положительный ответ def warehouse_re_ok(self, id): content = 'type: 0; id: %s' % (id.__str__()) subject = 'warehouse_re_ok %s' % (id.__str__()) self.email.sendmail(content, subject, [catalogue_email]) # Подтверждаем резервирование def warehouse_re_reserved(self, id): content = 'type: 0; id: %s' % (id.__str__()) subject = 'warehouse_re_reserved %s' % (id.__str__()) self.email.sendmail(content, subject, [catalogue_email]) # Невозможно укомплектовать заказ def warehouse_re_null(self, id): content = 'type: 0; id: %s' % (id.__str__()) subject = 'warehouse_re_null %s' % (id.__str__()) self.email.sendmail(content, subject, [catalogue_email]) def __new_mail__(self, email): if email['from'] == "From: %s" % catalogue_email: subject = email['subject'] content = email['text'] dictionary = self.__get__(content) print "have got dictionary:" if (subject.startswith('Subject: warehouse_query')): self.__reserve_order__(dictionary['id'], dictionary['json_description'], dictionary['date']) elif (subject.startswith('Subject: accept_warehouse_query')): order = Session.query(OrdersOperator).filter(OrdersOperator.id==dictionary['id']).first() order.status = "reserved" transaction.commit() self.warehouse_re_reserved(dictionary['id']) elif (subject.startswith('Subject: cancel')): self.__cancel_order__(dictionary[id]) else: print "Invalid request '%s'." % subject def fetchmail(self): mails = self.email.fetchmail() if mails: for mail in mails: #print "EMAIL" #print mail self.__new_mail__(mail) # Резверв def __reserve_order__(self, id, json_description, date): description = json.loads(json_description) date = date.replace('T', '') for order in description: check = Session.query(CatalogueOperator).filter((CatalogueOperator.idCatalogue==order['idCatalogue']) & (CatalogueOperator.count>=int(order['count']))).first() if check == None: print "Tak" # Engine.rollback() self.warehouse_re_null(id) return newOrder = Orders_CatalogueOperator() newOrder.count = order['count'] newOrder.idCatalogue = order['idCatalogue'] newOrder.idOrder = id check.count -= order['count'] Session.add(newOrder) order = OrdersOperator() order.id = id order.status = "prereserved" order.date = date Session.add(order) transaction.commit() self.warehouse_re_ok(id) # Отмена заказа def __cancel_order__(self, id): orders = Session.query(Orders_CatalogueOperator).filter(Orders_CatalogueOperator.idOrder==id).all() for order in orders: Session.delete(order) transaction.commit() order = Session.query(OrdersOperator).filter(OrdersOperator.id==id).first() order.status = "canceled" transaction.commit() def __get__(self, source): result = {} alist = source.split(';') for element in alist: element = element.strip() deuce = element.split('=') key = deuce[0].strip() value = deuce[1].strip() result[key] = value return result
def __init__(self, sender, unknown): Email.__init__(self, sender = sender, recipients = []) self.createRecipients(unknown.session) self.date = None
def invia_mail(self): mail = Email() utente_raw = pickle.load(open("Utente", 'r+b')) user_e_pwd = utente_raw.split("|") utente = Utente(user_e_pwd[0], user_e_pwd[1]) destinatari = self.ent_dest.text() oggetto = self.ent_ogg.text() corpo = self.mail_editor.toPlainText() mail.login(utente) mail.set_destinatari(destinatari) mail.set_oggetto(oggetto) mail.set_corpo(corpo) mail.send_email() print(mail) self.close()
import time from Email import Email from Renew import Renew books = {u'Introduction to analysis': 3, u'The elements of statistical learning': 3, u'Introduction to probability models': 3} while True: email = Email() renewer = Renew() renewer.start() try: book_list = renewer.check_deadline_element_wise() if book_list: for book in book_list: if book not in books.keys(): books[book] = 4 books[book] -= 1 print "========================================================" for book in books.keys(): print book, books[book] print "========================================================" b = "========================================================\n" for book in book_list: b += book+'\n' b += "========================================================\n" email.send_email("Books renewed", b) renewer.quit() time.sleep(60000) else: print "Too early"
def __init__(self): self.email = Email()
d_office = {} for i in o_data.d_daysOpenAll: d_office[i] = GetOfficeInfo(i, i_month, i_day, i_year, b_debug, o_data.d_daysOpenAll, o_data.d_officeNbrToCode) with ExcelBuilder(d_office, s_excelFile, i_month, i_day, i_year) as xlBuilder: pass try: with open(s_update, 'r') as file: s_html = file.read() except IOError as e: print (e) a_recipients = ['*****@*****.**'] mail = Email() for i in a_recipients: mail.sendEmail_html(i, s_html) s_emailMsg = str(a_errorsUpdateOrthdt) a_recipients = ['*****@*****.**'] for i in a_recipients: mail.sendEmail_html(i, s_emailMsg)
def __init__(self, sender, elective): Email.__init__(self, sender = sender, recipients = [] , bcc = "*****@*****.**") self.createRecipients(elective) self.date = None
#!/usr/bin/python # Script para la raspberry que consulta su ippublica actual y usando la clase Email la envia a mi correo # Esta script se ejecuta cada minuto comprobando contra un fichero (lastIp.txt) si la ip ha cambiado para enviar el mensaje import os from Email import Email nombreFicheroIp = "resources/lastIp.txt" ip = os.popen("curl icanhazip.com").read() lastIp = open(nombreFicheroIp).read() if lastIp != ip: open(nombreFicheroIp, "w").write(ip) email = Email() email.asunto = "IpPublica " + ip email.send_mail()
db = SqliteDatabase('emails.db') db.connect() def top_words(emails): vectorizer = CountVectorizer(min_df=10, ngram_range=(1, 2), stop_words='english') text = np.array([email.text for email in emails]) parties = np.array([email.sender.party for email in emails]) vectors = vectorizer.fit_transform(text) words = vectorizer.get_feature_names() num_cols = vectors.get_shape()[1] emails_containing_words = map(lambda n: vectors.getcol(n).getnnz(), range(num_cols)) emails_containing_words = sorted(zip(words, emails_containing_words), key=lambda x: -x[1]) return emails_containing_words emails = Email.select().join(SenderMetadata).where(SenderMetadata.party == "d") for item in top_words(emails): print t.cyan(str(item)) # emails = Email.select().join(SenderMetadata).where(SenderMetadata.party == "r") # for item in top_words(emails): # print t.red(str(item)) # emails = Email.select() # for item in emails: # print item.email() db.close()