4
4
import json
5
5
from .common import API_URL
6
6
7
+ def _email_file_from_path (path ):
8
+ with open (path , 'rb' ) as file :
9
+ return {
10
+ 'name' : os .path .basename (path ),
11
+ 'content' : base64 .b64encode (file .read ()).decode ('utf-8' )
12
+ }
13
+
7
14
class _Email ():
8
15
def __init__ (self , interceptor ):
9
16
self .path = '/email'
10
17
self .interceptor = interceptor
11
18
12
19
def send (self , message ):
13
20
message ._add_files ()
14
- r = requests .post (API_URL + self .path , auth = self .interceptor , data = message .toJSON ())
21
+ r = requests .post (API_URL + self .path , auth = self .interceptor , data = message .to_json ())
22
+ data = r .json ()
15
23
if not 200 <= r .status_code < 300 :
16
- response = r . json ( )
17
- raise EmailError ( response [ 'code' ], r [ 'message' ])
24
+ raise EmailError ( data [ 'code' ], data [ 'message' ] )
25
+ return EmailMessage . from_json ( data )
18
26
19
27
class EmailMessage ():
20
28
def __init__ (self , to , sender , subject ):
@@ -40,7 +48,7 @@ def add_inline(self, path):
40
48
def add_attachment (self , path ):
41
49
self .attachments .append (path )
42
50
43
- def toJSON (self ):
51
+ def to_json (self ):
44
52
return json .dumps ({
45
53
'to' : self .to ,
46
54
'from' : self .sender ,
@@ -50,13 +58,14 @@ def toJSON(self):
50
58
'attachments' : self ._attachments
51
59
})
52
60
53
- def _email_file_from_path (path ):
54
- with open (path , 'rb' ) as file :
55
- return {
56
- 'name' : os .path .basename (path ),
57
- 'content' : base64 .b64encode (file .read ()).decode ('utf-8' )
58
- }
59
-
61
+ @classmethod
62
+ def from_json (self , message ):
63
+ em = EmailMessage (message ['to' ], message ['from' ], message ['subject' ])
64
+ em .id = message ['id' ]
65
+ em .time = message ['time' ]
66
+ em .status = message ['status' ]
67
+ return em
68
+
60
69
class EmailError (Exception ):
61
70
def __init__ (self , code , message ):
62
71
self .code = code
0 commit comments