import getpass from gmail import Gmail # Leemos los datos mediante la consola de entrada my_gmail = input("Escribe tu Gmail: ") my_gmail_password = getpass.getpass("Password: "******"Introduce una lista con los emails de los destinatarios: ") asunto = input("Asunto del email: ") msg = input("Mensaje a enviar: ") my_gmail = Gmail( my_gmail, my_gmail_password ) for dest_email in list_dest_email.split(',') : dest_email_cleaned = dest_email.strip() try : my_gmail.send_message( dest_email_cleaned, msg, asunto ) print("Email enviado a %s" % dest_email_cleaned ) except Exception as err : print("Error enviado el email a %s. " % dest_email_cleaned + str( err ) ) my_gmail.quit()
class App: ''' Terminal User Interface ''' def __init__(self, username, password): self.username = username self.password = password self.gmail = Gmail(username, password) self.__clear_screen() print("Logged in as: {}\nThis is an App for using Gmail on your terminal!\n\n".format( self.username)) self.main_menu() def __clear_screen(self): if (os.name == 'nt'): os.system('cls') else: os.system('clear') def send(self): recipient = input( "Type in the address of who you want to send an e-mail: ") subject = input("Type in the subject: ") print("Type in the body (enter a blank line when you`re finished): ") body = "" stopword = "" while True: line = input() if line.strip() == stopword: break body += "%s\n" % line self.gmail.send_message(recipient, subject, body) self.__clear_screen() print("message sent to {}\n\n".format(recipient)) self.main_menu() def select_folder(self, mode='Read'): self.gmail.load_mailbox() if (mode == 'Read'): print("From which folder would you like to read?\n") if (mode == 'Move_Message'): print("Select Folder to Move Message:") self.gmail.list_mailboxes() folders = self.gmail.folders total_mailboxes = len(folders) - 1 selection = int(input()) print(total_mailboxes, selection) if (selection <= total_mailboxes): self.__clear_screen() return folders[selection] else: self.__clear_screen() print(total_mailboxes) print("Please select a valid folder number.") self.select_folder() def read_folder(self): folder = self.select_folder() self.gmail.set_mailbox(folder) self.gmail.get_messages() if (len(self.gmail.messages) == 0): self.main_menu() total_messages = len(self.gmail.messages) selection = int(input("Select which e-mail to read:\n")) self.__clear_screen() self.gmail.read_message(selection) def read_POP3(self): gm = Gmail_POP(self.username, self.password) gm.session_POP() print("Downloading all messages.\n") gm.get_mails() gm.set_mailbox() gm.get_messages() selection = int(input("Select which e-mail to read:\n")) self.__clear_screen() gm.read_message(selection) def create_folder(self): folders = self.gmail.folders print("These are the current folders\n") self.gmail.list_mailboxes() selection = input( "Type in the name of the new folder (special symbols are prone to errors). If you want to create a subfolder you'll have to type in the full path, IE: 'Parent_Folder/Child_Folder':\n") name = '"{}"'.format(selection) if (name in folders): self.__clear_screen() print("You can't create two mailboxes with the same name.") self.create_folder() self.gmail.create_mailbox(name) self.__clear_screen() print("You created '{}'\nThis is the updated Folder List:\n".format(name)) self.gmail.list_mailboxes() self.main_menu() def delete_folder(self): folders = self.gmail.folders print("These are the current folders\n") self.gmail.list_mailboxes() selection = input( "Type in the name of the folder you'd like to delete (DON'T TRY DELETING ANYTHING THAT'S DEFAULT FROM GMAIL):\n") name = '"{}"'.format(selection) if (name not in folders): self.__clear_screen() print( "You can't delete '{}' because it's not listed. A typo ocurred, perhaps?".format(name)) self.delete_folder() self.gmail.delete_mailbox(name) self.__clear_screen() print("You deleted '{}'\nThis is the updated Folder List:\n".format(name)) self.gmail.list_mailboxes() self.main_menu() def move_message(self): folder = self.select_folder() self.gmail.set_mailbox(folder) self.gmail.get_messages() if (len(self.gmail.messages) == 0): self.__clear_screen() print( "No messages in this folder. Please choose a folder that contains a message.\n") self.move_message() total_messages = len(self.gmail.messages) m_id = int(input("Select which e-mail to move:\n")) print("") destination_folder = self.select_folder(mode='Move_Message') self.gmail.move_message(m_id, destination_folder) print("Message moved to {}\n".format(destination_folder)) self.main_menu() def folders_ops(self): selection = input( "Type what you would like to do and press Enter:\n1 - Create Folder\n2 - Delete Folder\n3 - Move e-mail between folders\n9 - Main Menu\n\n") if (selection == "1"): self.__clear_screen() self.create_folder() elif (selection == "2"): self.gmail.session_IMAP() self.__clear_screen() self.delete_folder() self.gmail.logout_IMAP() self.main_menu() elif (selection == "3"): self.__clear_screen() self.move_message() elif (selection == "9"): exit() else: self.__clear_screen() print("Please select 1, 2 or 3\n\n") self.main_menu() def main_menu(self): selection = input( "Type what you would like to do and press Enter:\n1 - Send e-mails\n2 - Read e-mails (IMAP)\n3 - Read e-mails (POP3)\n4 - Folders\n9 - Exit\n\n") if (selection == "1"): self.__clear_screen() self.send() elif (selection == "2"): self.gmail.session_IMAP() self.__clear_screen() self.read_folder() self.gmail.logout_IMAP() self.main_menu() elif (selection == "3"): self.__clear_screen() self.read_POP3() self.main_menu() elif (selection == "4"): self.__clear_screen() self.folders_ops() elif (selection == "9"): exit() else: self.__clear_screen() print("Please select 1, 2 or 3\n\n") self.main_menu()
class ContractChecker: """Dear reader, the intended architecture relies on machine learning to generate a probability a contract contains some flaw. Due to the lack of training data, a heuristic approach is used. Future implementations will include more sophisticated text mining techniques. """ def __init__(self, name_customer, name_lawyer, email,contract,template_success,template_warning): self.numbers = {'een':1,'Een':1,'één':1,'Eén':1,'twee':2,'Twee':2,'Drie':3,'drie':3,None:0,1:1} self.gm = Gmail('*****@*****.**', 'hackathonmasters') self.name_customer = name_customer self.name_lawyer = name_lawyer self.email = email self.contract = contract self.subject = 'Betreffende uw contract' with open(template_success) as f: self.template_success = f.read() with open(template_warning) as f: self.template_warning = f.read() def run(self): message = self.generate_template(self.name_customer, self.concurrentiebeding(self.contract), self.proeftijd(self.contract)) self.gm.send_message(self.email, self.subject, message) def generate_template(self,name_customer,cb,pt): if cb and pt: template = self.template_warning template = re.sub("__KLANT__",self.name_customer,template) template = re.sub("__VERANDERING WET__","de wijziging van Wet Werk en Zekerheid per januari dit jaar", template) template = re.sub("__NAAM CONTRACT__","Arbeidsovereenkomst #1001",template) template = re.sub("__AANDACHTSPUNT__","de proeftijd is mogelijk te lang. Daarnaast heeft het concurrentiebeding uitgebreidere uitleg nodig",template) return re.sub("__UW NAAM__",self.name_lawyer,template) if cb: template = self.template_warning template = re.sub("__KLANT__",self.name_customer,template) template = re.sub("__VERANDERING WET__","de wijziging van Wet Werk en Zekerheid per januari dit jaar", template) template = re.sub("__NAAM CONTRACT__","Arbeidsovereenkomst #1034",template) template = re.sub("__AANDACHTSPUNT__","het concurrentiebeding heeft uitgebreidere uitleg nodig",template) return re.sub("__UW NAAM__",self.name_lawyer,template) if pt: template = self.template_warning template = re.sub("__KLANT__",self.name_customer,template) template = re.sub("__VERANDERING WET__","de wijziging van Wet Werk en Zekerheid per januari dit jaar", template) template = re.sub("__NAAM CONTRACT__","Arbeidsovereenkomst #1029",template) template = re.sub("__AANDACHTSPUNT__","de vastgelegde proeftijd is mogelijk te lang",template) return re.sub("__UW NAAM__",self.name_lawyer,template) template = self.template_success template = re.sub("__KLANT__",self.name_customer,template) template = re.sub("__NAAM CONTRACT__","Arbeidsovereenkomst #2098",template) return re.sub("__UW NAAM__",self.name_lawyer,template) def concurrentiebeding(self,contract): fd = nltk.FreqDist(nltk.word_tokenize(contract)) bepaaldeTijd = fd['bepaalde']>fd['onbepaalde'] concurrentiebeding = fd['concurrentiebeding']>0 or fd['Concurrentiebeding']>0 return bepaaldeTijd and concurrentiebeding def proeftijd(self,contract): if "proeftijd" not in contract: return False contractduur = re.match("duur van (\w+) maanden", contract, flags=re.IGNORECASE) if "eerste maand van de arbeidsovereenkomst geldt als proeftijd" in contract: proeftijd = 1 if not proeftijd: proeftijd = re.match("proeftijd van (\w+) maand", contract, flags=re.IGNORECASE) if not proeftijd: proeftijd = re.match("\w+\smaand", contract, flags=re.IGNORECASE) proeftijd = self.numbers[proeftijd] contractduur = self.numbers[contractduur] print("Proeftijd: {0} Contractduur: {1}".format(proeftijd,contractduur)) if contractduur < 6: return proeftijd > 0 if contractduur > 12: return proeftijd > 1 if contractduur >= 24: return proeftijd > 2 return False
def listen(self): """ Listens to the songs and outputs info whenever a new song has been listened to Parameters ---------- None Returns ------- None """ gmail = Gmail() last_track = self.spotify.current_user_playing_track() last_id = self._get_track_id(last_track) while True: try: # Read current track from api current_track = self.spotify.current_user_playing_track() while current_track is None: time.sleep(10) current_track = self.spotify.current_user_playing_track() if current_track is None or current_track[ "item"] is None or self._check_if_podcast( current_track): continue current_id = self._get_track_id(current_track) # Add info to database (if any) should_release, last_info = self._should_release( current_id, last_id, last_track) if should_release and last_info is not None: artist_id = self._get_artist_id(last_track) try: self.firebase.add_song(last_id, artist_id, last_info) self.firebase.add_to_week(last_id, artist_id, last_info) except ServiceUnavailable as e: print("Reinitializing Firebase") self.firebase = FireManager() time.sleep(5) self.firebase.add_song(last_id, artist_id, last_info) self.firebase.add_to_week(last_id, artist_id, last_info) self._update_current(current_id, current_track) # Update last_track last_id = current_id last_track = current_track # Wait 10 seconds time.sleep(10) # Check for errors except requests.exceptions.ReadTimeout as e: msg = f"ReadTimeout {e}" print(msg) time.sleep(30) except spotipy.exceptions.SpotifyException as e: try: self.spotify = self._init_spotify() except: tb = ''.join(traceback.format_tb(sys.exc_info()[2])) msg = f"Could not init spotify: {sys.exc_info()[0]}\nTraceback:\n{tb}" print(msg) gmail.send_message(msg) exit() except UnboundLocalError as e: tb = ''.join(traceback.format_tb(e.__traceback__)) msg = f"Unbound Local Error {e}\nTraceback:\n{tb}" print(msg) gmail.send_message(msg) time.sleep(30) except: tb = ''.join(traceback.format_tb(sys.exc_info()[2])) msg = f"Unhandled Error: {sys.exc_info()[0]}\nTraceback:\n{tb}" print(msg) gmail.send_message(msg) raise
def send_gmail(username, password, to_addrs, subject, message): logger.info("Sending Email to: %s" % to_addrs) gm = Gmail(username, password) gm.send_message(to_addrs, subject, message) gm.close()