1
+ import os
2
+ import base64
3
+ import requests
4
+ import json
5
+ from .common import API_URL
6
+
7
+ class _Email ():
8
+ def __init__ (self , interceptor ):
9
+ self .path = '/email'
10
+ self .interceptor = interceptor
11
+
12
+ def send (self , message ):
13
+ message ._add_files ()
14
+ r = requests .post (API_URL + self .path , auth = self .interceptor , data = message .toJSON ())
15
+ if not 200 <= r .status_code < 300 :
16
+ response = r .json ()
17
+ raise EmailError (response ['code' ], r ['message' ])
18
+
19
+ class EmailMessage ():
20
+ def __init__ (self , to , sender , subject ):
21
+ self ._inlines = []
22
+ self ._attachments = []
23
+ self .to = to
24
+ self .sender = sender
25
+ self .subject = subject
26
+ self .body = ''
27
+ self .inlines = []
28
+ self .attachments = []
29
+ self .status = ''
30
+
31
+ def _add_files (self ):
32
+ for path in self .inlines :
33
+ self ._inlines .append (_email_file_from_path (path ))
34
+ for path in self .attachments :
35
+ self ._attachments .append (_email_file_from_path (path ))
36
+
37
+ def add_inline (self , path ):
38
+ self .inlines .append (path )
39
+
40
+ def add_attachment (self , path ):
41
+ self .attachments .append (path )
42
+
43
+ def toJSON (self ):
44
+ return json .dumps ({
45
+ 'to' : self .to ,
46
+ 'from' : self .sender ,
47
+ 'subject' : self .subject ,
48
+ 'body' : self .body ,
49
+ 'inlines' : self ._inlines ,
50
+ 'attachments' : self ._attachments
51
+ })
52
+
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
+
60
+ class EmailError (Exception ):
61
+ def __init__ (self , code , message ):
62
+ self .code = code
63
+ self .message = message
64
+
65
+ def __str__ (self ):
66
+ return 'email error, code={0}, message={1}' .format (self .code , self .message )
67
+
0 commit comments