forked from madmimi/madmimi-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmadmimi.py
404 lines (300 loc) · 12.1 KB
/
madmimi.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/env python
#
# 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.
"""Python MadMimi client library."""
__author__ = ('[email protected] (tav),'
'[email protected] (Jordan Bouvier)')
__maintainer__ = '[email protected] (Jordan Bouvier)'
import csv
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from urllib import quote, urlencode
from urllib2 import urlopen
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
from yaml import dump
DEFAULT_CONTACT_FIELDS = ('first name', 'last_name', 'email', 'tags')
def parse_lists(response):
tree = ElementTree.ElementTree()
lists = {}
tree.parse(StringIO(response))
for elem in list(tree.getiterator('list')):
lists[elem.attrib['name']] = MailingList(elem.attrib['id'],
elem.attrib['name'],
elem.attrib['subscriber_count'])
return lists
class MailingList(object):
"""The main mailing list object."""
def __init__(self, list_id=0, list_name="", subscribers=0):
self.subscribers = subscribers
self.id = list_id
self.name = list_name
def __unicode__(self):
return u"<MailingList: %s>" % self.name
def __repr__(self):
return "<MailingList: %s>" % self.name
class MadMimi(object):
"""
The client is straightforward to use:
>>> mimi = MadMimi('[email protected]', 'account-api-key')
You can use it to list existing lists:
>>> mimi.lists()
{'test': <MailingList: test>}
>>> mimi.lists()["test"].subscribers
3
>>> mimi.lists()["test"].name
"test"
Delete any of them:
>>> mimi.delete_list('test')
Create new ones:
>>> mimi.add_list('ampify')
Add new contacts:
>>> mimi.add_contact(['Tav', 'Espian', '[email protected]'])
Subscribe contacts to a list:
>>> mimi.subscribe('[email protected]', 'ampify')
See what lists a contact is subscribed to:
>>> mimi.subscriptions('[email protected]')
<lists>
<list subscriber_count="1" name="ampify" id="77461"/>
</lists>
And, of course, unsubscribe a contact from a list:
>>> mimi.unsubscribe('[email protected]', 'ampify')
>>> mimi.subscriptions('[email protected]')
<lists>
</lists>
Send a transactional email:
>>> mimi.send_message('John Doe','[email protected]','Promotion Name',
... 'Subject of the message','[email protected]',
... {'var1':'This will go to the template'})
'1146680279'
Send an email to a list:
>>> mimi.send_message_to_list('List Name', 'Promotion Name',
... {'var1':'This will go to the template'})
'1223645'
"""
base_url = 'http://api.madmimi.com/'
secure_base_url = 'https://api.madmimi.com/'
def __init__(self, username, api_key):
self.username = username
self.api_key = api_key
self.urlopen = urlopen
def _get(self, method, **params):
"""Issue a GET request to Madmimi.
Arguments:
method: The path to the API method you are accessing, relative
to the site root.
is_secure: If is_secure is True, the GET request will be issued
to MadMimi's secure server.
Returns:
The result of the HTTP request as a string.
"""
is_secure = params.get('is_secure')
if is_secure:
url = self.secure_base_url
else:
url = self.base_url
params['username'] = self.username
params['api_key'] = self.api_key
url = url + method + '?' + urlencode(params)
return self.urlopen(url).read()
def _post(self, method, **params):
"""Issue a POST request to Madmimi.
Arguments:
method: The path to the API method you are accessing, relative
to the site root.
is_secure: If is_secure is True, the GET request will be issued
to MadMimi's secure server.
Returns:
The result of the HTTP request as a string.
"""
is_secure = params.get('is_secure')
if is_secure:
url = self.secure_base_url + method
else:
url = self.base_url + method
params['username'] = self.username
params['api_key'] = self.api_key
if params.get('sender'):
params['from'] = params['sender']
return self.urlopen(url, urlencode(params)).read()
def lists(self, as_xml=False):
"""Get a list of audience lists.
Arguments:
as_xml: If true, the result will be the raw XML response. If False
the result will be a python dictionary of lists.
Default is True. (Optional)
Returns:
The raw XML response or a dictionary of list names and objects.
{'list name': <list object>, 'list2 name': <list object>}
"""
response = self._get('audience_lists/lists.xml')
if as_xml:
return response
else:
return parse_lists(response)
def add_list(self, name):
"""Add a new audience list.
Arguments:
name: The name of the audience list to add.
Returns:
Nothing. The API doesn't provide a response.
"""
self._post('audience_lists', name=name)
def delete_list(self, name):
"""Delete an audience list.
Arguments:
name: The name of the audience list to delete.
Returns:
Nothing. The API doesn't provide a response.
"""
self._post('audience_lists/%s' % quote(name), _method='delete')
def add_contacts(self, contacts_data, fields=DEFAULT_CONTACT_FIELDS):
"""Add audience members to your database.
Arguments:
contacts_data: A list of tuples containting contact data.
fields: A tuple containing the fields that will be represented.
Returns:
Nothing. The API doesn't provide a response.
"""
contacts = []
contacts.append((fields))
contacts.extend(contacts_data)
csvdata = StringIO()
writer = csv.writer(csvdata)
[writer.writerow(row) for row in contacts]
self._post('audience_members', csv_file=csvdata.getvalue())
def subscribe(self, email, audience_list):
"""Add an audience member to an audience list.
Arguments:
email: The email address to add to a list.
audience_list: The audience list to add the email address to.
Return:
Nothing. The API doesn't provide a response.
"""
url = 'audience_lists/%s/add' % quote(audience_list)
self._post(url, email=email)
def unsubscribe(self, email, audience_list):
"""Remove an audience member from an audience list.
Arguments:
email: The email address to add to a list.
audience_list: The audience list to add the email address to.
Returns:
Nothing. The API doesn't provide a response.
"""
url = 'audience_lists/%s/remove' % quote(audience_list)
self._post(url, email=email)
def subscriptions(self, email, as_xml=False):
"""Get an audience member's current subscriptions.
Arguments:
email: The email address to look up.
as_xml: If true, the result will be the raw XML response. If False
the result will be a python dictionary of lists.
Default is True. (Optional)
Returns:
The raw XML response or a dictionary of list names and objects of which
the person is a member.
{'list name': <list object>, 'list2 name': <list object>}
"""
response = self._get('audience_members/%s/lists.xml' % quote(email))
if as_xml:
return response
else:
return parse_lists(response)
def send_message(self, name, email, promotion, subject, sender, body={}):
"""Sends a message to a user.
Arguments:
name: Name of the person you are sending to.
email: Email address of the person you are sending to.
promotion: Name of the Mad Mimi promotion to send.
subject: Subject of the email.
sender: Email address the email should appear to be from.
body: Dict holding variables for the promotion template.
{'variable': 'Replcement value'}
Returns:
The transaction id of the message if successful.
The error if unsuccessful.
"""
# The YAML dump will fail if it encounters non-strings
for item, value in body.iteritems():
body[item] = str(value)
recipients = "%s <%s>" % (name, email)
body = dump(body)
return self._post('mailer', promotion_name=promotion,
recipients=recipients, subject=subject, sender=sender,
body=body, is_secure=True)
def send_message_to_list(self, list_name, promotion, body={}):
"""Send a promotion to a subscriber list.
Arguments:
list_name: Name of the subscriber list to send the promotion to.
promotion: Name of the Mad Mimi promotion to send.
body: Dict holding variables for the promotion template.
{'variable': 'Replcement value'}
Returns:
The transaction id of the message if successful.
The error if unsuccessful.
"""
# The YAML dump will fail if it encounters non-strings
for item, value in body.iteritems():
body[item] = str(value)
body = dump(body)
return self._post('mailer/to_list', promotion_name=promotion,
list_name=list_name, body=body, is_secure=True)
def message_status(self, transaction_id):
"""Get the status of a message.
Arguments:
transaction_id: The transaction id of the message you want to
get the status for.
Returns:
One of the following strings:
ignorant
sending
failed
sent
received
clicked_through
bounced
retried
retry_failed
abused
"""
url = 'mailers/status/%s' % transaction_id
return self._get(url, is_secure=True)
def supressed_since(self, date):
"""Get a list of email addresses that have opted out since date.
Arguments:
date: Python datetime to retrieve opt outs since.
"""
url = 'audience_members/suppressed_since/%s.txt' % date.strftime('%s')
return self._get(url)
def promotion_stats(self):
"""Get an XML document containing stats for all your promotions."""
return self._get('promotions.xml')