-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathfreshmail.py
More file actions
231 lines (193 loc) · 6.74 KB
/
freshmail.py
File metadata and controls
231 lines (193 loc) · 6.74 KB
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
import requests
import json
import hashlib
"""
subscriber status codes for use with API: (undocumented in API)
1 active
2 activation pending
3 not activated
4 resigned
5 soft bouncing
8 hard bouncing
"""
class FreshMail(object):
"""
Custom class for Freshmail REST API
author: Dariusz Stepniak <[email protected]>
requires Requests module:
http://www.python-requests.org/en/latest/
"""
response = ''
rawResponse = ''
httpCode = ''
contentType = 'application/json'
host = 'https://api.freshmail.com/'
prefix = 'rest/'
def __init__(self, api_key, api_secret):
"""
Create class instance, requires api_key and api_secret
:param api_key:
:param api_secret:
:return: FreshMail Instance
"""
self.api_key = api_key
self.api_secret = api_secret
def setContentType(self, contentType):
self.contentType = contentType
def setHost(self, host):
self.host = host
def setPrefix(self, prefix):
self.prefix = prefix
def getResponse(self):
return self.response
def getHttpCode(self):
return self.httpCode
def request(self, url, payload=None, raw_response=False, method='POST'):
"""
Makes request to REST API. Add payload data for POST request.
:param url: API endpoint
:param payload: POST data dict
"""
if payload is None:
post_data = ''
else:
post_data = json.dumps(payload)
full_url = '%s%s%s' % (self.host, self.prefix, url,)
strSign = "%s/%s%s%s%s" % (self.api_key,
self.prefix,
url,
post_data,
self.api_secret,)
m = hashlib.sha1()
m.update(strSign.encode("utf-8"))
headers = {
'content-type': self.contentType,
'X-Rest-ApiKey': self.api_key,
'X-Rest-ApiSign': m.hexdigest()
}
if method is 'POST':
r = requests.post(full_url, data=post_data, headers=headers)
elif method is 'GET':
r = requests.get(full_url, data=post_data, headers=headers)
else:
raise FreshMailException({'message':'GET or POST required methods. Got {}'.format(method)})
self.httpCode = r.status_code
if self.httpCode != 200 and r.json()['status'] == 'ERROR':
# get errors
self.errors = r.json()['errors']
for error in r.json()['errors']:
raise FreshMailException({'message':error['message'],'code':error['code']})
self.response = r.json()
self.rawResponse = r.content
if raw_response:
return self.rawResponse
else:
return self.response
def mailText(self, email, subject, text):
# self, url, payload=None, raw_response=False
payload = {
'subscriber': email,
'subject': subject,
'text': text
}
url = 'mail'
response = self.request(url, payload)
print(response)
return
def mailHtml(self, email, subject, html):
# self, url, payload=None, raw_response=False
payload = {
'subscriber': email,
'subject': subject,
'html': html
}
url = 'mail'
response = self.request(url, payload)
print(response)
return
def addSubscriber(self, email, list_hash, state=3, confirm=1, custom_fields=None):
#self, url, payload=None, raw_response=False
payload = {
'email' : email,
'list' : list_hash,
'state' : state,
'confirm' : confirm
}
if custom_fields is not None and isinstance(custom_fields, dict):
# custom fields need to be a dict
payload['custom_fields'] = custom_fields
else:
raise FreshMailException({'message':'Custom fields must be a dict. Got {}'.format(custom_fields)})
url = 'subscriber/add'
response = self.request(url, payload)
print(response)
return
def deleteSubscriber(self, email, list_hash):
#self, url, payload=None, raw_response=False
payload = {
'email' : email,
'list' : list_hash
}
url = 'subscriber/delete'
response = self.request(url, payload)
print(response)
return
def getLists(self):
#self, url, payload=None, raw_response=False
url = 'subscribers_list/lists'
response = self.request(url)
if response.get('status') and response.get('status') == 'OK':
return response.get('lists')
else:
return None
def getSubscriber(self, email, list_hash):
#self, url, payload=None, raw_response=False
url = 'subscriber/get/{}/{}'.format(list_hash, email)
response = self.request(url,method='GET')
return response
def findSubscriber(self, email):
#slow with large number of lists
lists = self.getLists()
if len(lists) > 0:
subscribed_lists = []
for list in lists:
list_hash = list['subscriberListHash']
try:
result = self.getSubscriber(email, list_hash)
subscribed_list = { 'list_hash' : list_hash, 'name': list['name'], 'subscriber':result}
subscribed_lists.append(subscribed_list)
except:
#ignore not found errors
pass
return subscribed_lists
else:
raise FreshMailException({'message':'No lists found'})
def findSubscriberInLists(self, email, lists):
#slow with large number of lists
if len(lists) > 0:
subscribed_lists = []
for list in lists:
list_hash = list['subscriberListHash']
try:
result = self.getSubscriber(email, list_hash)
subscribed_list = { 'list_hash' : list_hash, 'name': list['name'], 'subscriber':result}
subscribed_lists.append(subscribed_list)
except:
#ignore not found errors
pass
return subscribed_lists
else:
raise FreshMailException({'message':'No lists found'})
def addCustomFieldtoList(self, list, field_name, tag=None, type=0):
url = 'subscribers_list/addField'
payload = {
'hash': list,
'name' : field_name,
'type' : type
}
if tag is not None:
payload['tag'] = tag
response = self.request(url,payload,method='POST')
return response
class FreshMailException(Exception):
pass