-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
73 lines (61 loc) · 1.87 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from __future__ import print_function
from datetime import datetime
import notifier
from mail_handler import handle_mail, update_statistics
import asyncore
from smtpd import SMTPServer
import os
from datetime import datetime
from config import get_server_settings, setup_logging
from sqlite import get_sqlite_database
from generator import generate
import logging
CONFIG = get_server_settings()
def save_email(text, no):
capture_dir = "logged_mails"
if not os.path.exists(capture_dir):
os.mkdir(capture_dir)
datestr = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"{datestr}_{no}.eml"
path = os.path.join(capture_dir, filename)
with open(path, "w") as f:
f.write(text)
logging.warning(f"{filename} saved.")
class KaffeLogger(SMTPServer):
no = 0
capture = CONFIG["capture"].upper()
def process_message(
self,
peer,
mailfrom,
rcpttos,
data,
mail_options=["BODY=8BITMIME", "SMTPUTF8"],
rcpt_options=[],
):
text = data.decode("UTF-8")
try:
handled, _ = handle_mail(text)
except:
logging.exception("Unable to parse email")
if self.capture == "ALL" or ((not handled) and self.capture == "UNPARSED"):
save_email(text, self.no)
self.no += 1
update_statistics()
generate.generate_coffee_report(get_sqlite_database())
notifier.notify_on_low_ingredient_levels()
def run():
# start the smtp server on 0.0.0.0:1025
ip = CONFIG["ip"]
port = CONFIG["port"]
capture = CONFIG["capture"]
KaffeLogger((ip, port), None)
logging.info(f"Now listening for mails on ip: {ip}, port {port}")
logging.info(f"Capturing emails: {capture}")
try:
asyncore.loop()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
setup_logging()
run()