-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_umail.py
256 lines (202 loc) · 7.9 KB
/
my_umail.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
# The MIT License (MIT)
#
# Copyright (c) 2022 David Festing
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# V1 29 Dec 2022
# added debugging to uMail found at https://github.com/shawwwn/uMail
import usocket
import utime
import machine
import config
DEFAULT_TIMEOUT = 30 # was 10 sec
LOCAL_DOMAIN = '127.0.0.1'
CMD_EHLO = 'EHLO'
CMD_STARTTLS = 'STARTTLS'
CMD_AUTH = 'AUTH'
CMD_MAIL = 'MAIL'
AUTH_PLAIN = 'PLAIN'
AUTH_LOGIN = 'LOGIN'
class SMTP:
def cmd(self, cmd_str):
sock = self._sock;
sock.write('%s\r\n' % cmd_str)
resp = []
next = True
while next:
code = sock.read(3)
next = sock.read(1) == b'-'
resp.append(sock.readline().strip().decode())
if (config.debug is True):
try:
with open('errors.txt', 'a') as outfile:
outfile.write(str(code) + '\n')
except OSError:
pass
return int(code), resp
def __init__(self, host, port, ssl=False, username=None, password=None):
import ussl
self.username = username
counter = 0
while True:
counter +=1
try:
addr = usocket.getaddrinfo(host, port)[0][-1]
break
except OSError as err:
if err.args[0] == -202: # no network available
try:
with open('errors.txt', 'a') as outfile:
outfile.write('no network available' + '\n')
except OSError:
pass
except Exception:
try:
with open('errors.txt', 'a') as outfile:
outfile.write('socket.getaddrinfo() failed' + '\n')
except OSError:
pass
if (counter == 5):
counter = 0
# generate a wdt
utime.sleep(80)
utime.sleep(5)
counter = 0 # reset counter
sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
sock.settimeout(DEFAULT_TIMEOUT)
while True:
counter +=1
try:
sock.connect(addr)
break
except OSError as err:
if err.args[0] == 116: # socket.timeout
try:
with open('errors.txt', 'a') as outfile:
outfile.write('socket timed-out' + '\n')
except OSError:
pass
except Exception:
try:
with open('errors.txt', 'a') as outfile:
outfile.write('socket.connect() failed' + '\n')
except OSError:
pass
if (counter == 5):
counter = 0
# generate a wdt
utime.sleep(80)
utime.sleep(5)
counter = 0 # reset
code = 0 # reset
while ((counter < 5) and (code != 220)):
counter +=1
if ssl:
sock = ussl.wrap_socket(sock)
print('SSL OK')
try:
with open('errors.txt', 'a') as outfile:
outfile.write('SSL try number = ' +str(counter) + '\n')
except OSError:
pass
code = int(sock.read(3))
utime.sleep(1)
if (counter == 5):
counter = 0
# generate a wdt
utime.sleep(80)
counter = 0 # reset
sock.readline()
assert code==220, 'cant connect to server %d, %s' % (code, resp)
self._sock = sock
code = 0 # reset
while ((counter < 5) and (code != 220)):
counter +=1
code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)
assert code==250, '%d' % code
if CMD_STARTTLS in resp:
code, resp = self.cmd(CMD_STARTTLS)
print('STARTTLS OK')
if (config.debug is True):
try:
with open('errors.txt', 'a') as outfile:
outfile.write('TLS try number = ' +str(counter) + '\n')
except OSError:
pass
assert code==220, 'start tls failed %d, %s' % (code, resp)
self._sock = ussl.wrap_socket(sock)
utime.sleep(1)
if (counter == 5):
counter = 0
# generate a wdt
utime.sleep(80)
counter = 0 # reset
if username and password:
self.login(username, password)
def login(self, username, password):
self.username = username
code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)
assert code==250, '%d, %s' % (code, resp)
auths = None
for feature in resp:
if feature[:4].upper() == CMD_AUTH:
auths = feature[4:].strip('=').upper().split()
assert auths!=None, "no auth method"
from ubinascii import b2a_base64 as b64
if AUTH_PLAIN in auths:
cren = b64("\0%s\0%s" % (username, password))[:-1].decode()
code, resp = self.cmd('%s %s %s' % (CMD_AUTH, AUTH_PLAIN, cren))
elif AUTH_LOGIN in auths:
code, resp = self.cmd("%s %s %s" % (CMD_AUTH, AUTH_LOGIN, b64(username)[:-1].decode()))
assert code==334, 'wrong username %d, %s' % (code, resp)
code, resp = self.cmd(b64(password)[:-1].decode())
else:
raise Exception("auth(%s) not supported " % ', '.join(auths))
assert code==235 or code==503, 'auth error %d, %s' % (code, resp)
return code, resp
def to(self, addrs, mail_from=None):
mail_from = self.username if mail_from==None else mail_from
code, resp = self.cmd(CMD_EHLO + ' ' + LOCAL_DOMAIN)
assert code==250, '%d' % code
code, resp = self.cmd('MAIL FROM: <%s>' % mail_from)
assert code==250, 'sender refused %d, %s' % (code, resp)
if isinstance(addrs, str):
addrs = [addrs]
count = 0
for addr in addrs:
code, resp = self.cmd('RCPT TO: <%s>' % addr)
if code!=250 and code!=251:
print('%s refused, %s' % (addr, resp))
count += 1
assert count!=len(addrs), 'recipient refused, %d, %s' % (code, resp)
code, resp = self.cmd('DATA')
assert code==354, 'data refused, %d, %s' % (code, resp)
return code, resp
def write(self, content):
print(content)
self._sock.write(content)
def send(self, content=''):
if content:
self.write(content)
self._sock.write('\r\n.\r\n') # the five letter sequence marked for ending
line = self._sock.readline()
return (int(line[:3]), line[4:].strip().decode())
def quit(self):
self.cmd("QUIT")
self._sock.close()