-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailserver.py
306 lines (284 loc) · 10.2 KB
/
mailserver.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
from socket import *
from copy import *
import os
import time
import email.header
from email.parser import Parser
import sql
import hashlib
import base64
sleeptime=0.8
errno =13
class Mail:
sender='' #发件人地址
receiver='' #收件人地址
topic='' #标题
uid='' #文件uid
class Smtp: #邮件发送类
mailserver='' #邮件服务器
username='' #用户名
password='' #密码
path=''
mail=Mail()
def __init__(self,mailserver, username, password, path=None, mail=None) -> None: #路径虽然没有写死,但实际上只有C:\\MailServer\\Draft目录下可以写入数据库
self.mail=deepcopy(mail)
self.mailserver=mailserver
self.username=username
self.password=password
self.path=path
def sendmail(self):
f=open(self.path+'\\'+self.mail.uid+'.txt')
message=f.read()
Socket=socket(AF_INET,SOCK_STREAM)
Socket.connect((self.mailserver,25))
recv=Socket.recv(1024).decode()
if recv[0:3]!='2':
#输出错误,print()函数仅用作测试
print("error1")
return errno
unamelist=self.username.split('@')
helomsf='HELO '+unamelist[0]+'\r\n'
Socket.send(helomsf.encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
recvlist=recv.split('\r\n')
if recvlist[1][0:3]!='250':
print("error2")
return errno
Socket.sendall(('AUTH LOGIN\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='334':
print("error3")
return errno
Socket.sendall((str(base64.b64encode(self.username.encode()),'utf-8')+'\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='334':
print("error4")
return errno
Socket.sendall((str(base64.b64encode(self.password.encode()),'utf-8')+'\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='235':
print("error5")
return errno
Socket.sendall(('MAIL FROM: '+'<'+self.mail.sender+'>\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='250':
print("error6")
return errno
Socket.sendall(('RCPT TO: '+'<'+self.mail.receiver+'>\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='250':
print("error7")
return errno
Socket.sendall(('DATA\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='354':
print("error8")
return errno
Socket.sendall(message.encode())
Socket.sendall('\r\n.\r\n'.encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='250':
print("error9")
return errno
Socket.send('QUIT\r\n'.encode())
Socket.close()
f.close()
return 0
class Pop3: #邮件接收类
mailserver=''
username=''
password=''
def __init__(self,mailserver,username,password) -> None:
self.mailserver=mailserver
self.username=username
self.password=password
def store(self,maillist):
dbtuple=sql.SQL.show_tables()
dblist=''
for i in dbtuple:
dblist+=i[0]
if(dblist.find('mail')==-1):
sql.SQL.create_sql('Mail')
else:
sql.SQL.drop_table('Mail')
sql.SQL.create_sql('Mail')
cnt=1
for i in maillist:
sql.SQL().add_sql(i.sender,i.receiver,i.topic,i.uid,cnt,'Mail')
cnt+=1
return
def get_body(self,msg):
if msg.is_multipart():
return self.get_body(msg.get_payload(0))
else:
return msg.get_payload(None,decode=True)
def recvmail(self,operation,index):
path='C:\\MailServer' #默认路径
while not os.path.exists(path):
os.makedirs(path)
Socket=socket(AF_INET,SOCK_STREAM)
Socket.connect((self.mailserver,110))
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='+OK':
print("error")
return errno
unamelist=self.username.split('@')
Socket.sendall(('USER '+unamelist[0]+'\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='+OK':
print("error")
return errno
Socket.sendall(('PASS '+self.password+'\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
if recv[0:3]!='+OK':
print("error")
return errno
if operation=='STAT':
Socket.send('STAT\r\n'.encode())
time.sleep(sleeptime)
recv=Socket.recv(1024).decode()
print(recv) #仅作测试用
elif operation=='LIST':
Socket.send('LIST\r\n'.encode())
time.sleep(sleeptime)
recv=Socket.recv(65536).decode()
if recv[0:3]!='+OK':
print("error")
return errno
recvlist=recv.split('\r\n')
maillist=[]
for per in range(1,len(recvlist[1:len(recvlist)-2])+1):
Socket.sendall(('TOP '+str(per)+' 5\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(65536).decode()
toplist=recv.split('\r\n')
mail=Mail()
mail.receiver=self.username
findex=0
starti=0
dflag=False
for i in range(len(toplist)):
if(toplist[i].find('From: ') != -1):
findex=i
break
mail.sender=toplist[findex][5:]
for i in range(len(toplist)):
if(toplist[i].find('Subject: ') != -1):
findex=i
starti=toplist[i].find('=?')
if(starti!=-1):
dflag=True
break
if(dflag):
stmp,fcode=email.header.decode_header(toplist[findex][starti:])[0]
mail.topic=stmp.decode(fcode)
else:
mail.topic=toplist[findex][8:]
Socket.send(('UIDL '+str(per)+'\r\n').encode())
time.sleep(sleeptime)
uid=Socket.recv(1024).decode()
uidlist=uid.split(' ')
mail.uid=uidlist[2][0:len(uidlist[2])-2]
maillist.append(mail)
self.store(maillist)
##此处需连接数据库##
elif operation=='RETR':
Socket.sendall(('UIDL '+str(index)+'\r\n').encode())
time.sleep(sleeptime)
uid=Socket.recv(1024).decode()
uidlist=uid.split(' ')
Socket.sendall(('RETR '+str(index)+'\r\n').encode())
time.sleep(sleeptime)
recv=Socket.recv(65536).decode()
if(recv[0:3]!='+OK'):
print("error")
return errno
recvlist=recv.split('\n',1)
msg=Parser().parsestr(recvlist[1])
charset=msg.get_charset()
if charset is None:
if(recv.find('UTF-8')!=-1 or recv.find('utf-8')!=-1):
charset='utf-8'
elif(recv.find('GBK')!=-1):
charset='gbk'
elif(recv.find('gb18030')):
charset='gb18030'
else:
charset='utf-8'
body=self.get_body(msg).decode(charset)
f=open(path+'\\'+uidlist[2][0:len(uidlist[2])-2]+'.txt',mode='w')
#recvlist=recv.split('\n',1)
try:
f.write(body)
except Exception as e:
print(e)
f.close()
elif operation == 'DELE':
Socket.sendall(('UIDL '+str(index)+'\r\n').encode())
time.sleep(sleeptime)
uid=Socket.recv(1024).decode()
uidlist=uid.split(' ')
Socket.sendall(('DELE '+str(index)+'\r\n').encode())
os.remove(path+'\\'+uidlist[2][0:len(uidlist[2])-2]+'.txt')
# sql.SQL.delete_sql(uidlist[2][0:len(uidlist[2])-2],'Mail')
# sql.SQL.update_after_dele(index)
Socket.send('QUIT'.encode())
Socket.close()
return 0
class Sender_proc:
def __init__(self,sender,receiver,subject,message) -> None: #init时创建邮件报文
self.sender=sender
self.receiver=receiver
self.message=message
self.subject=subject
self.msg=self.gene_mail() #此时确定时间戳
def gene_uid(self):
return hashlib.md5(self.msg.encode('utf-8')).hexdigest()
def gene_mail(self):
msg="From: "+self.sender+'\n' \
+"To: "+self.receiver+'\n' \
+"Subject: "+self.subject+'\n' \
+"Date: "+time.asctime()+"\n"\
+"Content-Type: text/plain; charset=UTF-8 \n"\
+'\r\n'\
+self.message.encode('utf-8').decode('utf-8')+'\r\n'
return msg
def gene_mailclass(self):
mail=Mail()
mail.receiver=self.receiver
mail.sender=self.sender
mail.topic=self.subject
mail.uid=self.gene_uid()
return mail
def store(self):
mail=self.gene_mailclass()
path='C:\\MailServer\\Draft'
while not os.path.exists(path):
os.makedirs(path)
f=open(path+'\\'+mail.uid+'.txt',mode='w')
f.write(self.msg)
f.close()
return path+'\\'+mail.uid+'.txt'
def add_to_sql(self):
dbtuple=sql.SQL.show_tables()
dblist=''
for i in dbtuple:
dblist+=i[0]
if(dblist.find('draft')==-1):
sql.SQL.create_sql('Draft')
sql.SQL.add_sql(self.sender,self.receiver,self.subject,self.gene_uid(),0,'Draft')
@staticmethod
def delete_draft(uid):
os.remove("C:\\MailSever\\Draft\\"+uid+'.txt')
sql.SQL.delete_sql(uid,'Draft')