-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmandrill.py
3166 lines (2619 loc) · 200 KB
/
mandrill.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests, os.path, logging, sys, time
try:
import ujson as json
except ImportError:
try:
import simplejson as json
except ImportError:
import json
class Error(Exception):
pass
class ValidationError(Error):
pass
class InvalidKeyError(Error):
pass
class PaymentRequiredError(Error):
pass
class UnknownSubaccountError(Error):
pass
class UnknownTemplateError(Error):
pass
class ServiceUnavailableError(Error):
pass
class UnknownMessageError(Error):
pass
class InvalidTagNameError(Error):
pass
class InvalidRejectError(Error):
pass
class UnknownSenderError(Error):
pass
class UnknownUrlError(Error):
pass
class UnknownTrackingDomainError(Error):
pass
class InvalidTemplateError(Error):
pass
class UnknownWebhookError(Error):
pass
class UnknownInboundDomainError(Error):
pass
class UnknownInboundRouteError(Error):
pass
class UnknownExportError(Error):
pass
class IPProvisionLimitError(Error):
pass
class UnknownPoolError(Error):
pass
class NoSendingHistoryError(Error):
pass
class PoorReputationError(Error):
pass
class UnknownIPError(Error):
pass
class InvalidEmptyDefaultPoolError(Error):
pass
class InvalidDeleteDefaultPoolError(Error):
pass
class InvalidDeleteNonEmptyPoolError(Error):
pass
class InvalidCustomDNSError(Error):
pass
class InvalidCustomDNSPendingError(Error):
pass
class MetadataFieldLimitError(Error):
pass
class UnknownMetadataFieldError(Error):
pass
ROOT = 'https://mandrillapp.com/api/1.0/'
ERROR_MAP = {
'ValidationError': ValidationError,
'Invalid_Key': InvalidKeyError,
'PaymentRequired': PaymentRequiredError,
'Unknown_Subaccount': UnknownSubaccountError,
'Unknown_Template': UnknownTemplateError,
'ServiceUnavailable': ServiceUnavailableError,
'Unknown_Message': UnknownMessageError,
'Invalid_Tag_Name': InvalidTagNameError,
'Invalid_Reject': InvalidRejectError,
'Unknown_Sender': UnknownSenderError,
'Unknown_Url': UnknownUrlError,
'Unknown_TrackingDomain': UnknownTrackingDomainError,
'Invalid_Template': InvalidTemplateError,
'Unknown_Webhook': UnknownWebhookError,
'Unknown_InboundDomain': UnknownInboundDomainError,
'Unknown_InboundRoute': UnknownInboundRouteError,
'Unknown_Export': UnknownExportError,
'IP_ProvisionLimit': IPProvisionLimitError,
'Unknown_Pool': UnknownPoolError,
'NoSendingHistory': NoSendingHistoryError,
'PoorReputation': PoorReputationError,
'Unknown_IP': UnknownIPError,
'Invalid_EmptyDefaultPool': InvalidEmptyDefaultPoolError,
'Invalid_DeleteDefaultPool': InvalidDeleteDefaultPoolError,
'Invalid_DeleteNonEmptyPool': InvalidDeleteNonEmptyPoolError,
'Invalid_CustomDNS': InvalidCustomDNSError,
'Invalid_CustomDNSPending': InvalidCustomDNSPendingError,
'Metadata_FieldLimit': MetadataFieldLimitError,
'Unknown_MetadataField': UnknownMetadataFieldError
}
logger = logging.getLogger('mandrill')
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stderr))
class Mandrill(object):
def __init__(self, apikey=None, debug=False):
'''Initialize the API client
Args:
apikey (str|None): provide your Mandrill API key. If this is left as None, we will attempt to get the API key from the following locations::
- MANDRILL_APIKEY in the environment vars
- ~/.mandrill.key for the user executing the script
- /etc/mandrill.key
debug (bool): set to True to log all the request and response information to the "mandrill" logger at the INFO level. When set to false, it will log at the DEBUG level. By default it will write log entries to STDERR
'''
self.session = requests.session()
if debug:
self.level = logging.INFO
else:
self.level = logging.DEBUG
self.last_request = None
if apikey is None:
if 'MANDRILL_APIKEY' in os.environ:
apikey = os.environ['MANDRILL_APIKEY']
else:
apikey = self.read_configs()
if apikey is None: raise Error('You must provide a Mandrill API key')
self.apikey = apikey
self.templates = Templates(self)
self.exports = Exports(self)
self.users = Users(self)
self.rejects = Rejects(self)
self.inbound = Inbound(self)
self.tags = Tags(self)
self.messages = Messages(self)
self.whitelists = Whitelists(self)
self.ips = Ips(self)
self.internal = Internal(self)
self.subaccounts = Subaccounts(self)
self.urls = Urls(self)
self.webhooks = Webhooks(self)
self.senders = Senders(self)
self.metadata = Metadata(self)
def call(self, url, params=None):
'''Actually make the API call with the given params - this should only be called by the namespace methods - use the helpers in regular usage like m.tags.list()'''
if params is None: params = {}
params['key'] = self.apikey
params = json.dumps(params)
self.log('POST to %s%s.json: %s' % (ROOT, url, params))
start = time.time()
r = self.session.post('%s%s.json' % (ROOT, url), data=params, headers={'content-type': 'application/json', 'user-agent': 'Mandrill-Python/1.0.58'})
try:
remote_addr = r.raw._original_response.fp._sock.getpeername() # grab the remote_addr before grabbing the text since the socket will go away
except:
remote_addr = (None, None) #we use two private fields when getting the remote_addr, so be a little robust against errors
response_body = r.text
complete_time = time.time() - start
self.log('Received %s in %.2fms: %s' % (r.status_code, complete_time * 1000, r.text))
self.last_request = {'url': url, 'request_body': params, 'response_body': r.text, 'remote_addr': remote_addr, 'response': r, 'time': complete_time}
result = json.loads(response_body)
if r.status_code != requests.codes.ok:
raise self.cast_error(result)
return result
def cast_error(self, result):
'''Take a result representing an error and cast it to a specific exception if possible (use a generic mandrill.Error exception for unknown cases)'''
if not 'status' in result or result['status'] != 'error' or not 'name' in result:
raise Error('We received an unexpected error: %r' % result)
if result['name'] in ERROR_MAP:
return ERROR_MAP[result['name']](result['message'])
return Error(result['message'])
def read_configs(self):
'''Try to read the API key from a series of files if it's not provided in code'''
paths = [os.path.expanduser('~/.mandrill.key'), '/etc/mandrill.key']
for path in paths:
try:
f = open(path, 'r')
apikey = f.read().strip()
f.close()
if apikey != '':
return apikey
except:
pass
return None
def log(self, *args, **kwargs):
'''Proxy access to the mandrill logger, changing the level based on the debug setting'''
logger.log(self.level, *args, **kwargs)
def __repr__(self):
return '<Mandrill %s>' % self.apikey
class Templates(object):
def __init__(self, master):
self.master = master
def add(self, name, from_email=None, from_name=None, subject=None, code=None, text=None, publish=True, labels=[]):
"""Add a new template
Args:
name (string): the name for the new template - must be unique
from_email (string): a default sending address for emails sent using this template
from_name (string): a default from name to be used
subject (string): a default subject line to be used
code (string): the HTML code for the template with mc:edit attributes for the editable elements
text (string): a default text part to be used when sending with this template
publish (boolean): set to false to add a draft template without publishing
labels (array): an optional array of up to 10 labels to use for filtering templates::
labels[] (string): a single label
Returns:
struct. the information saved about the new template::
slug (string): the immutable unique code name of the template
name (string): the name of the template
labels (array): the list of labels applied to the template::
labels[] (string): a single label
code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements - draft version
subject (string): the subject line of the template, if provided - draft version
from_email (string): the default sender address for the template, if provided - draft version
from_name (string): the default sender from name for the template, if provided - draft version
text (string): the default text part of messages sent with the template, if provided - draft version
publish_name (string): the same as the template name - kept as a separate field for backwards compatibility
publish_code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements that are available as published, if it has been published
publish_subject (string): the subject line of the template, if provided
publish_from_email (string): the default sender address for the template, if provided
publish_from_name (string): the default sender from name for the template, if provided
publish_text (string): the default text part of messages sent with the template, if provided
published_at (string): the date and time the template was last published as a UTC string in YYYY-MM-DD HH:MM:SS format, or null if it has not been published
created_at (string): the date and time the template was first created as a UTC string in YYYY-MM-DD HH:MM:SS format
updated_at (string): the date and time the template was last modified as a UTC string in YYYY-MM-DD HH:MM:SS format
Raises:
InvalidTemplateError: The given template name already exists or contains invalid characters
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'name': name, 'from_email': from_email, 'from_name': from_name, 'subject': subject, 'code': code, 'text': text, 'publish': publish, 'labels': labels}
return self.master.call('templates/add', _params)
def info(self, name):
"""Get the information for an existing template
Args:
name (string): the immutable name of an existing template
Returns:
struct. the requested template information::
slug (string): the immutable unique code name of the template
name (string): the name of the template
labels (array): the list of labels applied to the template::
labels[] (string): a single label
code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements - draft version
subject (string): the subject line of the template, if provided - draft version
from_email (string): the default sender address for the template, if provided - draft version
from_name (string): the default sender from name for the template, if provided - draft version
text (string): the default text part of messages sent with the template, if provided - draft version
publish_name (string): the same as the template name - kept as a separate field for backwards compatibility
publish_code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements that are available as published, if it has been published
publish_subject (string): the subject line of the template, if provided
publish_from_email (string): the default sender address for the template, if provided
publish_from_name (string): the default sender from name for the template, if provided
publish_text (string): the default text part of messages sent with the template, if provided
published_at (string): the date and time the template was last published as a UTC string in YYYY-MM-DD HH:MM:SS format, or null if it has not been published
created_at (string): the date and time the template was first created as a UTC string in YYYY-MM-DD HH:MM:SS format
updated_at (string): the date and time the template was last modified as a UTC string in YYYY-MM-DD HH:MM:SS format
Raises:
UnknownTemplateError: The requested template does not exist
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'name': name}
return self.master.call('templates/info', _params)
def update(self, name, from_email=None, from_name=None, subject=None, code=None, text=None, publish=True, labels=None):
"""Update the code for an existing template. If null is provided for any fields, the values will remain unchanged.
Args:
name (string): the immutable name of an existing template
from_email (string): the new default sending address
from_name (string): the new default from name
subject (string): the new default subject line
code (string): the new code for the template
text (string): the new default text part to be used
publish (boolean): set to false to update the draft version of the template without publishing
labels (array): an optional array of up to 10 labels to use for filtering templates::
labels[] (string): a single label
Returns:
struct. the template that was updated::
slug (string): the immutable unique code name of the template
name (string): the name of the template
labels (array): the list of labels applied to the template::
labels[] (string): a single label
code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements - draft version
subject (string): the subject line of the template, if provided - draft version
from_email (string): the default sender address for the template, if provided - draft version
from_name (string): the default sender from name for the template, if provided - draft version
text (string): the default text part of messages sent with the template, if provided - draft version
publish_name (string): the same as the template name - kept as a separate field for backwards compatibility
publish_code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements that are available as published, if it has been published
publish_subject (string): the subject line of the template, if provided
publish_from_email (string): the default sender address for the template, if provided
publish_from_name (string): the default sender from name for the template, if provided
publish_text (string): the default text part of messages sent with the template, if provided
published_at (string): the date and time the template was last published as a UTC string in YYYY-MM-DD HH:MM:SS format, or null if it has not been published
created_at (string): the date and time the template was first created as a UTC string in YYYY-MM-DD HH:MM:SS format
updated_at (string): the date and time the template was last modified as a UTC string in YYYY-MM-DD HH:MM:SS format
Raises:
UnknownTemplateError: The requested template does not exist
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'name': name, 'from_email': from_email, 'from_name': from_name, 'subject': subject, 'code': code, 'text': text, 'publish': publish, 'labels': labels}
return self.master.call('templates/update', _params)
def publish(self, name):
"""Publish the content for the template. Any new messages sent using this template will start using the content that was previously in draft.
Args:
name (string): the immutable name of an existing template
Returns:
struct. the template that was published::
slug (string): the immutable unique code name of the template
name (string): the name of the template
labels (array): the list of labels applied to the template::
labels[] (string): a single label
code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements - draft version
subject (string): the subject line of the template, if provided - draft version
from_email (string): the default sender address for the template, if provided - draft version
from_name (string): the default sender from name for the template, if provided - draft version
text (string): the default text part of messages sent with the template, if provided - draft version
publish_name (string): the same as the template name - kept as a separate field for backwards compatibility
publish_code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements that are available as published, if it has been published
publish_subject (string): the subject line of the template, if provided
publish_from_email (string): the default sender address for the template, if provided
publish_from_name (string): the default sender from name for the template, if provided
publish_text (string): the default text part of messages sent with the template, if provided
published_at (string): the date and time the template was last published as a UTC string in YYYY-MM-DD HH:MM:SS format, or null if it has not been published
created_at (string): the date and time the template was first created as a UTC string in YYYY-MM-DD HH:MM:SS format
updated_at (string): the date and time the template was last modified as a UTC string in YYYY-MM-DD HH:MM:SS format
Raises:
UnknownTemplateError: The requested template does not exist
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'name': name}
return self.master.call('templates/publish', _params)
def delete(self, name):
"""Delete a template
Args:
name (string): the immutable name of an existing template
Returns:
struct. the template that was deleted::
slug (string): the immutable unique code name of the template
name (string): the name of the template
labels (array): the list of labels applied to the template::
labels[] (string): a single label
code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements - draft version
subject (string): the subject line of the template, if provided - draft version
from_email (string): the default sender address for the template, if provided - draft version
from_name (string): the default sender from name for the template, if provided - draft version
text (string): the default text part of messages sent with the template, if provided - draft version
publish_name (string): the same as the template name - kept as a separate field for backwards compatibility
publish_code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements that are available as published, if it has been published
publish_subject (string): the subject line of the template, if provided
publish_from_email (string): the default sender address for the template, if provided
publish_from_name (string): the default sender from name for the template, if provided
publish_text (string): the default text part of messages sent with the template, if provided
published_at (string): the date and time the template was last published as a UTC string in YYYY-MM-DD HH:MM:SS format, or null if it has not been published
created_at (string): the date and time the template was first created as a UTC string in YYYY-MM-DD HH:MM:SS format
updated_at (string): the date and time the template was last modified as a UTC string in YYYY-MM-DD HH:MM:SS format
Raises:
UnknownTemplateError: The requested template does not exist
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'name': name}
return self.master.call('templates/delete', _params)
def list(self, label=None):
"""Return a list of all the templates available to this user
Args:
label (string): an optional label to filter the templates
Returns:
array. an array of structs with information about each template::
[] (struct): the information on each template in the account::
[].slug (string): the immutable unique code name of the template
[].name (string): the name of the template
[].labels (array): the list of labels applied to the template::
[].labels[] (string): a single label
[].code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements - draft version
[].subject (string): the subject line of the template, if provided - draft version
[].from_email (string): the default sender address for the template, if provided - draft version
[].from_name (string): the default sender from name for the template, if provided - draft version
[].text (string): the default text part of messages sent with the template, if provided - draft version
[].publish_name (string): the same as the template name - kept as a separate field for backwards compatibility
[].publish_code (string): the full HTML code of the template, with mc:edit attributes marking the editable elements that are available as published, if it has been published
[].publish_subject (string): the subject line of the template, if provided
[].publish_from_email (string): the default sender address for the template, if provided
[].publish_from_name (string): the default sender from name for the template, if provided
[].publish_text (string): the default text part of messages sent with the template, if provided
[].published_at (string): the date and time the template was last published as a UTC string in YYYY-MM-DD HH:MM:SS format, or null if it has not been published
[].created_at (string): the date and time the template was first created as a UTC string in YYYY-MM-DD HH:MM:SS format
[].updated_at (string): the date and time the template was last modified as a UTC string in YYYY-MM-DD HH:MM:SS format
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'label': label}
return self.master.call('templates/list', _params)
def time_series(self, name):
"""Return the recent history (hourly stats for the last 30 days) for a template
Args:
name (string): the name of an existing template
Returns:
array. the array of history information::
[] (struct): the stats for a single hour::
[].time (string): the hour as a UTC date string in YYYY-MM-DD HH:MM:SS format
[].sent (integer): the number of emails that were sent during the hour
[].hard_bounces (integer): the number of emails that hard bounced during the hour
[].soft_bounces (integer): the number of emails that soft bounced during the hour
[].rejects (integer): the number of emails that were rejected during the hour
[].complaints (integer): the number of spam complaints received during the hour
[].opens (integer): the number of emails opened during the hour
[].unique_opens (integer): the number of unique opens generated by messages sent during the hour
[].clicks (integer): the number of tracked URLs clicked during the hour
[].unique_clicks (integer): the number of unique clicks generated by messages sent during the hour
Raises:
UnknownTemplateError: The requested template does not exist
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'name': name}
return self.master.call('templates/time-series', _params)
def render(self, template_name, template_content, merge_vars=None):
"""Inject content and optionally merge fields into a template, returning the HTML that results
Args:
template_name (string): the immutable name of a template that exists in the user's account
template_content (array): an array of template content to render. Each item in the array should be a struct with two keys - name: the name of the content block to set the content for, and content: the actual content to put into the block::
template_content[] (struct): the injection of a single piece of content into a single editable region::
template_content[].name (string): the name of the mc:edit editable region to inject into
template_content[].content (string): the content to inject
merge_vars (array): optional merge variables to use for injecting merge field content. If this is not provided, no merge fields will be replaced.::
merge_vars[] (struct): a single merge variable::
merge_vars[].name (string): the merge variable's name. Merge variable names are case-insensitive and may not start with _
merge_vars[].content (string): the merge variable's content
Returns:
struct. the result of rendering the given template with the content and merge field values injected::
html (string): the rendered HTML as a string
Raises:
UnknownTemplateError: The requested template does not exist
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'template_name': template_name, 'template_content': template_content, 'merge_vars': merge_vars}
return self.master.call('templates/render', _params)
class Exports(object):
def __init__(self, master):
self.master = master
def info(self, id):
"""Returns information about an export job. If the export job's state is 'complete',
the returned data will include a URL you can use to fetch the results. Every export
job produces a zip archive, but the format of the archive is distinct for each job
type. The api calls that initiate exports include more details about the output format
for that job type.
Args:
id (string): an export job identifier
Returns:
struct. the information about the export::
id (string): the unique identifier for this Export. Use this identifier when checking the export job's status
created_at (string): the date and time that the export job was created as a UTC string in YYYY-MM-DD HH:MM:SS format
type (string): the type of the export job - activity, reject, or whitelist
finished_at (string): the date and time that the export job was finished as a UTC string in YYYY-MM-DD HH:MM:SS format
state (string): the export job's state - waiting, working, complete, error, or expired.
result_url (string): the url for the export job's results, if the job is completed.
Raises:
UnknownExportError: The requested export job does not exist
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'id': id}
return self.master.call('exports/info', _params)
def list(self, ):
"""Returns a list of your exports.
Returns:
array. the account's exports::
[] (struct): the individual export info::
[].id (string): the unique identifier for this Export. Use this identifier when checking the export job's status
[].created_at (string): the date and time that the export job was created as a UTC string in YYYY-MM-DD HH:MM:SS format
[].type (string): the type of the export job - activity, reject, or whitelist
[].finished_at (string): the date and time that the export job was finished as a UTC string in YYYY-MM-DD HH:MM:SS format
[].state (string): the export job's state - waiting, working, complete, error, or expired.
[].result_url (string): the url for the export job's results, if the job is completed.
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {}
return self.master.call('exports/list', _params)
def rejects(self, notify_email=None):
"""Begins an export of your rejection blacklist. The blacklist will be exported to a zip archive
containing a single file named rejects.csv that includes the following fields: email,
reason, detail, created_at, expires_at, last_event_at, expires_at.
Args:
notify_email (string): an optional email address to notify when the export job has finished.
Returns:
struct. information about the rejects export job that was started::
id (string): the unique identifier for this Export. Use this identifier when checking the export job's status
created_at (string): the date and time that the export job was created as a UTC string in YYYY-MM-DD HH:MM:SS format
type (string): the type of the export job
finished_at (string): the date and time that the export job was finished as a UTC string in YYYY-MM-DD HH:MM:SS format, or null for jobs that have not run
state (string): the export job's state
result_url (string): the url for the export job's results, if the job is complete
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'notify_email': notify_email}
return self.master.call('exports/rejects', _params)
def whitelist(self, notify_email=None):
"""Begins an export of your rejection whitelist. The whitelist will be exported to a zip archive
containing a single file named whitelist.csv that includes the following fields:
email, detail, created_at.
Args:
notify_email (string): an optional email address to notify when the export job has finished.
Returns:
struct. information about the whitelist export job that was started::
id (string): the unique identifier for this Export. Use this identifier when checking the export job's status
created_at (string): the date and time that the export job was created as a UTC string in YYYY-MM-DD HH:MM:SS format
type (string): the type of the export job
finished_at (string): the date and time that the export job was finished as a UTC string in YYYY-MM-DD HH:MM:SS format, or null for jobs that have not run
state (string): the export job's state
result_url (string): the url for the export job's results, if the job is complete
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'notify_email': notify_email}
return self.master.call('exports/whitelist', _params)
def activity(self, notify_email=None, date_from=None, date_to=None, tags=None, senders=None, states=None, api_keys=None):
"""Begins an export of your activity history. The activity will be exported to a zip archive
containing a single file named activity.csv in the same format as you would be able to export
from your account's activity view. It includes the following fields: Date, Email Address,
Sender, Subject, Status, Tags, Opens, Clicks, Bounce Detail. If you have configured any custom
metadata fields, they will be included in the exported data.
Args:
notify_email (string): an optional email address to notify when the export job has finished
date_from (string): start date as a UTC string in YYYY-MM-DD HH:MM:SS format
date_to (string): end date as a UTC string in YYYY-MM-DD HH:MM:SS format
tags (array): an array of tag names to narrow the export to; will match messages that contain ANY of the tags::
tags[] (string): a tag name
senders (array): an array of senders to narrow the export to::
senders[] (string): a sender address
states (array): an array of states to narrow the export to; messages with ANY of the states will be included::
states[] (string): a message state
api_keys (array): an array of api keys to narrow the export to; messsagse sent with ANY of the keys will be included::
api_keys[] (string): an API key associated with your account
Returns:
struct. information about the activity export job that was started::
id (string): the unique identifier for this Export. Use this identifier when checking the export job's status
created_at (string): the date and time that the export job was created as a UTC string in YYYY-MM-DD HH:MM:SS format
type (string): the type of the export job
finished_at (string): the date and time that the export job was finished as a UTC string in YYYY-MM-DD HH:MM:SS format, or null for jobs that have not run
state (string): the export job's state
result_url (string): the url for the export job's results, if the job is complete
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'notify_email': notify_email, 'date_from': date_from, 'date_to': date_to, 'tags': tags, 'senders': senders, 'states': states, 'api_keys': api_keys}
return self.master.call('exports/activity', _params)
class Users(object):
def __init__(self, master):
self.master = master
def info(self, ):
"""Return the information about the API-connected user
Returns:
struct. the user information including username, key, reputation, quota, and historical sending stats::
username (string): the username of the user (used for SMTP authentication)
created_at (string): the date and time that the user's Mandrill account was created as a UTC string in YYYY-MM-DD HH:MM:SS format
public_id (string): a unique, permanent identifier for this user
reputation (integer): the reputation of the user on a scale from 0 to 100, with 75 generally being a "good" reputation
hourly_quota (integer): the maximum number of emails Mandrill will deliver for this user each hour. Any emails beyond that will be accepted and queued for later delivery. Users with higher reputations will have higher hourly quotas
backlog (integer): the number of emails that are queued for delivery due to exceeding your monthly or hourly quotas
stats (struct): an aggregate summary of the account's sending stats::
stats.today (struct): stats for this user so far today::
stats.today.sent (integer): the number of emails sent for this user so far today
stats.today.hard_bounces (integer): the number of emails hard bounced for this user so far today
stats.today.soft_bounces (integer): the number of emails soft bounced for this user so far today
stats.today.rejects (integer): the number of emails rejected for sending this user so far today
stats.today.complaints (integer): the number of spam complaints for this user so far today
stats.today.unsubs (integer): the number of unsubscribes for this user so far today
stats.today.opens (integer): the number of times emails have been opened for this user so far today
stats.today.unique_opens (integer): the number of unique opens for emails sent for this user so far today
stats.today.clicks (integer): the number of URLs that have been clicked for this user so far today
stats.today.unique_clicks (integer): the number of unique clicks for emails sent for this user so far today
stats.last_7_days (struct): stats for this user in the last 7 days::
stats.last_7_days.sent (integer): the number of emails sent for this user in the last 7 days
stats.last_7_days.hard_bounces (integer): the number of emails hard bounced for this user in the last 7 days
stats.last_7_days.soft_bounces (integer): the number of emails soft bounced for this user in the last 7 days
stats.last_7_days.rejects (integer): the number of emails rejected for sending this user in the last 7 days
stats.last_7_days.complaints (integer): the number of spam complaints for this user in the last 7 days
stats.last_7_days.unsubs (integer): the number of unsubscribes for this user in the last 7 days
stats.last_7_days.opens (integer): the number of times emails have been opened for this user in the last 7 days
stats.last_7_days.unique_opens (integer): the number of unique opens for emails sent for this user in the last 7 days
stats.last_7_days.clicks (integer): the number of URLs that have been clicked for this user in the last 7 days
stats.last_7_days.unique_clicks (integer): the number of unique clicks for emails sent for this user in the last 7 days
stats.last_30_days (struct): stats for this user in the last 30 days::
stats.last_30_days.sent (integer): the number of emails sent for this user in the last 30 days
stats.last_30_days.hard_bounces (integer): the number of emails hard bounced for this user in the last 30 days
stats.last_30_days.soft_bounces (integer): the number of emails soft bounced for this user in the last 30 days
stats.last_30_days.rejects (integer): the number of emails rejected for sending this user in the last 30 days
stats.last_30_days.complaints (integer): the number of spam complaints for this user in the last 30 days
stats.last_30_days.unsubs (integer): the number of unsubscribes for this user in the last 30 days
stats.last_30_days.opens (integer): the number of times emails have been opened for this user in the last 30 days
stats.last_30_days.unique_opens (integer): the number of unique opens for emails sent for this user in the last 30 days
stats.last_30_days.clicks (integer): the number of URLs that have been clicked for this user in the last 30 days
stats.last_30_days.unique_clicks (integer): the number of unique clicks for emails sent for this user in the last 30 days
stats.last_60_days (struct): stats for this user in the last 60 days::
stats.last_60_days.sent (integer): the number of emails sent for this user in the last 60 days
stats.last_60_days.hard_bounces (integer): the number of emails hard bounced for this user in the last 60 days
stats.last_60_days.soft_bounces (integer): the number of emails soft bounced for this user in the last 60 days
stats.last_60_days.rejects (integer): the number of emails rejected for sending this user in the last 60 days
stats.last_60_days.complaints (integer): the number of spam complaints for this user in the last 60 days
stats.last_60_days.unsubs (integer): the number of unsubscribes for this user in the last 60 days
stats.last_60_days.opens (integer): the number of times emails have been opened for this user in the last 60 days
stats.last_60_days.unique_opens (integer): the number of unique opens for emails sent for this user in the last 60 days
stats.last_60_days.clicks (integer): the number of URLs that have been clicked for this user in the last 60 days
stats.last_60_days.unique_clicks (integer): the number of unique clicks for emails sent for this user in the last 60 days
stats.last_90_days (struct): stats for this user in the last 90 days::
stats.last_90_days.sent (integer): the number of emails sent for this user in the last 90 days
stats.last_90_days.hard_bounces (integer): the number of emails hard bounced for this user in the last 90 days
stats.last_90_days.soft_bounces (integer): the number of emails soft bounced for this user in the last 90 days
stats.last_90_days.rejects (integer): the number of emails rejected for sending this user in the last 90 days
stats.last_90_days.complaints (integer): the number of spam complaints for this user in the last 90 days
stats.last_90_days.unsubs (integer): the number of unsubscribes for this user in the last 90 days
stats.last_90_days.opens (integer): the number of times emails have been opened for this user in the last 90 days
stats.last_90_days.unique_opens (integer): the number of unique opens for emails sent for this user in the last 90 days
stats.last_90_days.clicks (integer): the number of URLs that have been clicked for this user in the last 90 days
stats.last_90_days.unique_clicks (integer): the number of unique clicks for emails sent for this user in the last 90 days
stats.all_time (struct): stats for the lifetime of the user's account::
stats.all_time.sent (integer): the number of emails sent in the lifetime of the user's account
stats.all_time.hard_bounces (integer): the number of emails hard bounced in the lifetime of the user's account
stats.all_time.soft_bounces (integer): the number of emails soft bounced in the lifetime of the user's account
stats.all_time.rejects (integer): the number of emails rejected for sending this user so far today
stats.all_time.complaints (integer): the number of spam complaints in the lifetime of the user's account
stats.all_time.unsubs (integer): the number of unsubscribes in the lifetime of the user's account
stats.all_time.opens (integer): the number of times emails have been opened in the lifetime of the user's account
stats.all_time.unique_opens (integer): the number of unique opens for emails sent in the lifetime of the user's account
stats.all_time.clicks (integer): the number of URLs that have been clicked in the lifetime of the user's account
stats.all_time.unique_clicks (integer): the number of unique clicks for emails sent in the lifetime of the user's account
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {}
return self.master.call('users/info', _params)
def ping(self, ):
"""Validate an API key and respond to a ping
Returns:
string. the string "PONG!"
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {}
return self.master.call('users/ping', _params)
def ping2(self, ):
"""Validate an API key and respond to a ping (anal JSON parser version)
Returns:
struct. a struct with one key "PING" with a static value "PONG!"
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {}
return self.master.call('users/ping2', _params)
def senders(self, ):
"""Return the senders that have tried to use this account, both verified and unverified
Returns:
array. an array of sender data, one for each sending addresses used by the account::
[] (struct): the information on each sending address in the account::
[].address (string): the sender's email address
[].created_at (string): the date and time that the sender was first seen by Mandrill as a UTC date string in YYYY-MM-DD HH:MM:SS format
[].sent (integer): the total number of messages sent by this sender
[].hard_bounces (integer): the total number of hard bounces by messages by this sender
[].soft_bounces (integer): the total number of soft bounces by messages by this sender
[].rejects (integer): the total number of rejected messages by this sender
[].complaints (integer): the total number of spam complaints received for messages by this sender
[].unsubs (integer): the total number of unsubscribe requests received for messages by this sender
[].opens (integer): the total number of times messages by this sender have been opened
[].clicks (integer): the total number of times tracked URLs in messages by this sender have been clicked
[].unique_opens (integer): the number of unique opens for emails sent for this sender
[].unique_clicks (integer): the number of unique clicks for emails sent for this sender
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {}
return self.master.call('users/senders', _params)
class Rejects(object):
def __init__(self, master):
self.master = master
def add(self, email, comment=None, subaccount=None):
"""Adds an email to your email rejection blacklist. Addresses that you
add manually will never expire and there is no reputation penalty
for removing them from your blacklist. Attempting to blacklist an
address that has been whitelisted will have no effect.
Args:
email (string): an email address to block
comment (string): an optional comment describing the rejection
subaccount (string): an optional unique identifier for the subaccount to limit the blacklist entry
Returns:
struct. a status object containing the address and the result of the operation::
email (string): the email address you provided
added (boolean): whether the operation succeeded
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
UnknownSubaccountError: The provided subaccount id does not exist.
Error: A general Mandrill error has occurred
"""
_params = {'email': email, 'comment': comment, 'subaccount': subaccount}
return self.master.call('rejects/add', _params)
def list(self, email=None, include_expired=False, subaccount=None):
"""Retrieves your email rejection blacklist. You can provide an email
address to limit the results. Returns up to 1000 results. By default,
entries that have expired are excluded from the results; set
include_expired to true to include them.
Args:
email (string): an optional email address to search by
include_expired (boolean): whether to include rejections that have already expired.
subaccount (string): an optional unique identifier for the subaccount to limit the blacklist
Returns:
array. Up to 1000 rejection entries::
[] (struct): the information for each rejection blacklist entry::
[].email (string): the email that is blocked
[].reason (string): the type of event (hard-bounce, soft-bounce, spam, unsub, custom) that caused this rejection
[].detail (string): extended details about the event, such as the SMTP diagnostic for bounces or the comment for manually-created rejections
[].created_at (string): when the email was added to the blacklist
[].last_event_at (string): the timestamp of the most recent event that either created or renewed this rejection
[].expires_at (string): when the blacklist entry will expire (this may be in the past)
[].expired (boolean): whether the blacklist entry has expired
[].sender (struct): the sender that this blacklist entry applies to, or null if none.::
[].sender.address (string): the sender's email address
[].sender.created_at (string): the date and time that the sender was first seen by Mandrill as a UTC date string in YYYY-MM-DD HH:MM:SS format
[].sender.sent (integer): the total number of messages sent by this sender
[].sender.hard_bounces (integer): the total number of hard bounces by messages by this sender
[].sender.soft_bounces (integer): the total number of soft bounces by messages by this sender
[].sender.rejects (integer): the total number of rejected messages by this sender
[].sender.complaints (integer): the total number of spam complaints received for messages by this sender
[].sender.unsubs (integer): the total number of unsubscribe requests received for messages by this sender
[].sender.opens (integer): the total number of times messages by this sender have been opened
[].sender.clicks (integer): the total number of times tracked URLs in messages by this sender have been clicked
[].sender.unique_opens (integer): the number of unique opens for emails sent for this sender
[].sender.unique_clicks (integer): the number of unique clicks for emails sent for this sender
[].subaccount (string): the subaccount that this blacklist entry applies to, or null if none.
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
UnknownSubaccountError: The provided subaccount id does not exist.
ServiceUnavailableError: The subsystem providing this API call is down for maintenance
Error: A general Mandrill error has occurred
"""
_params = {'email': email, 'include_expired': include_expired, 'subaccount': subaccount}
return self.master.call('rejects/list', _params)
def delete(self, email, subaccount=None):
"""Deletes an email rejection. There is no limit to how many rejections
you can remove from your blacklist, but keep in mind that each deletion
has an affect on your reputation.
Args:
email (string): an email address
subaccount (string): an optional unique identifier for the subaccount to limit the blacklist deletion
Returns:
struct. a status object containing the address and whether the deletion succeeded.::
email (string): the email address that was removed from the blacklist
deleted (boolean): whether the address was deleted successfully.
subaccount (string): the subaccount blacklist that the address was removed from, if any
Raises:
InvalidRejectError: The requested email is not in the rejection list
InvalidKeyError: The provided API key is not a valid Mandrill API key
UnknownSubaccountError: The provided subaccount id does not exist.
Error: A general Mandrill error has occurred
"""
_params = {'email': email, 'subaccount': subaccount}
return self.master.call('rejects/delete', _params)
class Inbound(object):
def __init__(self, master):
self.master = master
def domains(self, ):
"""List the domains that have been configured for inbound delivery
Returns:
array. the inbound domains associated with the account::
[] (struct): the individual domain info::
[].domain (string): the domain name that is accepting mail
[].created_at (string): the date and time that the inbound domain was added as a UTC string in YYYY-MM-DD HH:MM:SS format
[].valid_mx (boolean): true if this inbound domain has successfully set up an MX record to deliver mail to the Mandrill servers
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {}
return self.master.call('inbound/domains', _params)
def add_domain(self, domain):
"""Add an inbound domain to your account
Args:
domain (string): a domain name
Returns:
struct. information about the domain::
domain (string): the domain name that is accepting mail
created_at (string): the date and time that the inbound domain was added as a UTC string in YYYY-MM-DD HH:MM:SS format
valid_mx (boolean): true if this inbound domain has successfully set up an MX record to deliver mail to the Mandrill servers
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {'domain': domain}
return self.master.call('inbound/add-domain', _params)
def check_domain(self, domain):
"""Check the MX settings for an inbound domain. The domain must have already been added with the add-domain call
Args:
domain (string): an existing inbound domain
Returns:
struct. information about the inbound domain::
domain (string): the domain name that is accepting mail
created_at (string): the date and time that the inbound domain was added as a UTC string in YYYY-MM-DD HH:MM:SS format
valid_mx (boolean): true if this inbound domain has successfully set up an MX record to deliver mail to the Mandrill servers
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
UnknownInboundDomainError: The requested inbound domain does not exist
Error: A general Mandrill error has occurred
"""
_params = {'domain': domain}
return self.master.call('inbound/check-domain', _params)
def delete_domain(self, domain):
"""Delete an inbound domain from the account. All mail will stop routing for this domain immediately.
Args:
domain (string): an existing inbound domain
Returns:
struct. information about the deleted domain::
domain (string): the domain name that is accepting mail
created_at (string): the date and time that the inbound domain was added as a UTC string in YYYY-MM-DD HH:MM:SS format
valid_mx (boolean): true if this inbound domain has successfully set up an MX record to deliver mail to the Mandrill servers
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
UnknownInboundDomainError: The requested inbound domain does not exist
Error: A general Mandrill error has occurred
"""
_params = {'domain': domain}
return self.master.call('inbound/delete-domain', _params)
def routes(self, domain):
"""List the mailbox routes defined for an inbound domain
Args:
domain (string): the domain to check
Returns:
array. the routes associated with the domain::
[] (struct): the individual mailbox route::
[].id (string): the unique identifier of the route
[].pattern (string): the search pattern that the mailbox name should match
[].url (string): the webhook URL where inbound messages will be published
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
UnknownInboundDomainError: The requested inbound domain does not exist
Error: A general Mandrill error has occurred
"""
_params = {'domain': domain}
return self.master.call('inbound/routes', _params)
def add_route(self, domain, pattern, url):
"""Add a new mailbox route to an inbound domain
Args:
domain (string): an existing inbound domain
pattern (string): the search pattern that the mailbox name should match
url (string): the webhook URL where the inbound messages will be published