""" This File handles all the email and contact shenanigans, its kind of convoluted at the Moment and needs a bit of cleanup. I tried to keep everything in functions so it stays readable. Some handle emails and the smtp & imap server-side, the others Json stuff to extract email addresses and save them as contacts for future use. """ import imaplib, email, os, json from smtplib import SMTP_SSL, SMTP_SSL_PORT from config import server, username, password, address, searchAll, searchYesterday, searchUnawnsered, today, searchSentsince from datetime import datetime #! This function takes a list of Email-Addresses and sends them emails def sendEmails(text, reciever): # Credential Setup SMTP_HOST = server SMTP_USER = address SMTP_PASS = password # Connect to Server smtp_server = SMTP_SSL(SMTP_HOST, port=SMTP_SSL_PORT) smtp_server.set_debuglevel(1) # Show SMTP server interactions smtp_server.login(SMTP_USER, SMTP_PASS) for r in reciever: # Craft the email from_email = f'{username} <{address}>' headers = f"From: {from_email}\r\n" headers += f"To: {', '.join(r)}\r\n" headers += f"Subject: Autoresponse\r\n" email_message = headers + "\r\n" + text # Send mail smtp_server.sendmail(from_email, r, email_message) # Disconnect from Server smtp_server.quit() #! This function loads all known contacts from the Json file def loadKnownContacts(): f = open('contacts.json') contacts = json.load(f) return contacts #! This function returns all Contacts from the Inbox def getContacts(search): # Connect to inbox imap_server = imaplib.IMAP4_SSL(host=server) imap_server.login(address, password) imap_server.select() # Default is `INBOX` contacts = [] # Find all emails in inbox _, message_numbers_raw = imap_server.search(None, search) for message_number in message_numbers_raw[0].split(): _, msg = imap_server.fetch(message_number, '(RFC822)') # Parse the raw email message in to a convenient object message = email.message_from_bytes(msg[0][1]) contact = message['from'].lower() if contact not in contacts: contacts.append(contact) newContacts = [] for c in contacts: contact = c.split('<') if len(contact) == 2: contact = contact[1].split('>') newContacts.append(contact[0]) else: contact = contact[0].split('(') newContacts.append(contact[0]) return newContacts #! This function adds new contacts to the json file for later use def jsonAddContacts(contacts): knowContacts = loadKnownContacts() for c in contacts: knowContacts.append(c) if os.path.isfile('./contacts.json'): print('Deleting Contacts') os.remove('contacts.json') with open('contacts.json', 'w', encoding='utf-8') as f: json.dump(knowContacts, f, ensure_ascii=False, indent=4) #! This function creates the initial Json file with all already known contacts from the inbox def jsonCreateContacts(): # Connect to inbox imap_server = imaplib.IMAP4_SSL(host=server) imap_server.login(address, password) imap_server.select() # Default is `INBOX` contacts = [] # Find all emails in inbox _, message_numbers_raw = imap_server.search(None, searchAll) for message_number in message_numbers_raw[0].split(): _, msg = imap_server.fetch(message_number, '(RFC822)') # Parse the raw email message in to a convenient object message = email.message_from_bytes(msg[0][1]) contact = message['from'].lower() if contact not in contacts: contacts.append(contact) newContacts = [] for c in contacts: contact = c.split('<') if len(contact) == 2: contact = contact[1].split('>') newContacts.append(contact[0]) else: contact = contact[0].split('(') newContacts.append(contact[0]) if os.path.isfile('./contacts.json'): os.remove('contacts.json') with open('contacts.json', 'w', encoding='utf-8') as f: json.dump(newContacts, f, ensure_ascii=False, indent=4) #! This function will safe the last execution date in a json-file def lastExecutionDate_Safe (executionDate): if os.path.isfile('./executionDate.json'): os.remove('executionDate.json') with open('executionDate.json', 'w', encoding='utf-8') as f: json.dump(executionDate, f, ensure_ascii=False, indent=4) #! This function will load the last execution date def lastExecutionDate_Load(): f = open('executionDate.json') date = json.load(f) return date #! This function returns all unkown contacts def checkFor_unkownContacts(): lastExecution = lastExecutionDate_Load() date = datetime.strptime(lastExecution, "%Y-%m-%d") contacts = getContacts(searchUnawnsered + date.strftime("%d-%b-%Y")) knownContacts = loadKnownContacts() unknownContacts = [] for c in contacts: if c not in knownContacts: unknownContacts.append(c) return unknownContacts