forked from tomwardill/FakeEmail
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsmtpd.py
76 lines (64 loc) · 2.37 KB
/
smtpd.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
74
75
76
import mailparser
import sqlite3
from aiosmtpd.controller import Controller
import os, time
from datetime import datetime
from web import start_web
class DataHandler(object):
def __init__(self, mailbox_dir, db_name, table_name):
self.maildir =os.path.expanduser(mailbox_dir)
self.db_name = db_name
self.table_name = table_name
self.db = f"{self.maildir}/{self.db_name}"
self.init_db()
async def save_mail(self, _from, to, email_title, tm, raw_mail, has_attach):
conn = sqlite3.connect(self.db)
cur = conn.cursor()
sql = f"""
insert into {self.table_name} (`email_from`, `email_to`, `email_title`, `dt`, `email_raw`, `has_attach`) values
(?, ?, ?, ?,?, ?)
"""
#print(sql)
cur.execute(sql, (_from, to, email_title, tm, raw_mail, has_attach))
conn.commit()
cur.close()
conn.close()
async def parse(self, raw_mail):
mail = mailparser.parse_from_string(raw_mail)
from_ = mail.from_[0][1]
to_ = mail.to[0][1]
email_subject = mail.subject
has_attach = 1 if len(mail.attachments)>0 else 0
tm = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"{tm}\t{from_}\t{to_}\t{mail.subject}")
await self.save_mail(from_, to_, email_subject, tm, raw_mail, has_attach)
async def handle_DATA(self, server, session, envelope):
s = envelope.content.decode('utf8', errors='replace')
await self.parse(s)
return '250 Message accepted for delivery'
def init_db(self):
print(f"use db {self.db}")
conn = sqlite3.connect(self.db)
cur = conn.cursor()
sql = f"""
create table if not exists {self.table_name}(
id INTEGER PRIMARY KEY autoincrement,
email_from VARCHAR(255),
email_to VARCHAR(255),
email_title VARCHAR(512),
dt TEXT,
email_raw TEXT,
has_attach INTEGER not null
)
"""
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
if __name__=='__main__':
try:
controller = Controller(DataHandler("~/mailbox", 'fake_mail.db', "fake_mail"), hostname='0.0.0.0', port=25)
controller.start()
start_web("0.0.0.0", "8888")
except KeyboardInterrupt:
print("smtpd quit!")