Kleies Utility programm für unsere Email verwaltung
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

153 lines
5.1 KiB

2 years ago
"""
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.
"""
2 years ago
import imaplib, email, os, json
from smtplib import SMTP_SSL, SMTP_SSL_PORT
2 years ago
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):
2 years ago
# Credential Setup
SMTP_HOST = server
2 years ago
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)
2 years ago
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()
2 years ago
#! This function loads all known contacts from the Json file
def loadKnownContacts():
f = open('contacts.json')
contacts = json.load(f)
return contacts
2 years ago
#! This function returns all Contacts from the Inbox
def getContacts(search):
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host=server)
2 years ago
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
2 years ago
#! This function adds new contacts to the json file for later use
def jsonAddContacts(contacts):
2 years ago
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:
2 years ago
json.dump(knowContacts, f, ensure_ascii=False, indent=4)
2 years ago
#! 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)
2 years ago
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)
2 years ago
#! 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():
2 years ago
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
2 years ago