-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathpystmark.py
More file actions
1617 lines (1348 loc) · 58.2 KB
/
pystmark.py
File metadata and controls
1617 lines (1348 loc) · 58.2 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
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
"""
pystmark
--------
Postmark API library built on :mod:`requests`
:copyright: 2013, see AUTHORS for more details
:license: MIT, see LICENSE for more details
:TODO:
Support for bounce and inbound hooks? These should be mostly handled
in a framework specific manner but there might be some common utilities
to provide.
Optionally verify attachment size <=10MB
Wrapper class for Message attachments and headers?
"""
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
from base64 import b64encode
import requests
import mimetypes
import os.path
import sys
from _pystmark_meta import __title__, __version__, __license__
(__title__, __version__, __license__) # silence pyflakes
if sys.version_info[0] >= 3: # pragma: no cover
from urllib.parse import urljoin
basestring = str
def iteritems(obj):
return obj.items()
else: # pragma: no cover
from urlparse import urljoin
def iteritems(obj):
return obj.iteritems()
try: # pragma: no cover
import simplejson as json
except ImportError: # pragma: no cover
import json
# Constant defined in the Postmark docs:
# http://developer.postmarkapp.com/developer-build.html
POSTMARK_API_URL = 'http://api.postmarkapp.com/'
POSTMARK_API_URL_SECURE = 'https://api.postmarkapp.com/'
POSTMARK_API_TEST_KEY = 'POSTMARK_API_TEST'
MAX_RECIPIENTS_PER_MESSAGE = 20
MAX_BATCH_MESSAGES = 500
bounce_types = {
'HardBounce': 1,
'Transient': 2,
'Unsubscribe': 16,
'Subscribe': 32,
'AutoResponder': 64,
'AddressChange': 128,
'DnsError': 256,
'SpamNotification': 512,
'OpenRelayTest': 1024,
'Unknown': 2048,
'SoftBounce': 4096,
'VirusNotification': 8192,
'ChallengeVerification': 16384,
'BadEmailAddress': 100000,
'SpamComplaint': 100001,
'ManuallyDeactivated': 100002,
'Unconfirmed': 100003,
'Blocked': 100006,
'SMTPApiError': 100007,
'InboundError': 100008
}
""" Simple API """
def send(message, api_key=None, secure=None, test=None, **request_args):
"""Send a message.
:param message: Message to send.
:type message: `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`SendResponse`
"""
return _default_pyst_sender.send(message=message, api_key=api_key,
secure=secure, test=test, **request_args)
def send_with_template(message,
api_key=None,
secure=None,
test=None,
**request_args):
"""Send a message.
:param message: Message to send.
:type message: `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`SendResponse`
"""
return _default_pyst_template_sender.send(message=message,
api_key=api_key,
secure=secure,
test=test,
**request_args)
def send_batch(messages, api_key=None, secure=None, test=None, **request_args):
"""Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BatchSendResponse`
"""
return _default_pyst_batch_sender.send(messages=messages, api_key=api_key,
secure=secure, test=test,
**request_args)
def send_batch_with_templates(messages,
api_key=None,
secure=None,
test=None,
**request_args):
"""Send a batch of messages with templates.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BatchSendResponse`
"""
return _default_pyst_batch_template_sender.send(messages=messages,
api_key=api_key,
secure=secure,
test=test,
**request_args)
def get_outbound_message_details(message_id, api_key=None, secure=None,
test=None, **request_args):
'''Get outbound message details.
:param message_id: The messages's id.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`OutboundMessageDetailsResponse`
'''
return _default_outbound_message_details.get(message_id, api_key=api_key,
secure=secure, test=test,
**request_args)
def get_delivery_stats(api_key=None, secure=None, test=None, **request_args):
"""Get delivery stats for your Postmark account.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`DeliveryStatsResponse`
"""
return _default_delivery_stats.get(api_key=api_key, secure=secure,
test=test, **request_args)
def get_bounces(api_key=None, secure=None, test=None, **request_args):
"""Get a paginated list of bounces.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BouncesResponse`
"""
return _default_bounces.get(api_key=api_key, secure=secure,
test=test, **request_args)
def get_bounce(bounce_id, api_key=None, secure=None, test=None,
**request_args):
"""Get a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BounceResponse`
"""
return _default_bounce.get(bounce_id, api_key=api_key, secure=secure,
test=test, **request_args)
def get_bounce_dump(bounce_id, api_key=None, secure=None, test=None,
**request_args):
"""Get the raw email dump for a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BounceDumpResponse`
"""
return _default_bounce_dump.get(bounce_id, api_key=api_key, secure=secure,
test=test, **request_args)
def get_bounce_tags(api_key=None, secure=None, test=None, **request_args):
"""Get a list of tags for bounces associated with your Postmark server.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BounceTagsResponse`
"""
return _default_bounce_tags.get(api_key=api_key, secure=secure, test=test,
**request_args)
def activate_bounce(bounce_id, api_key=None, secure=None, test=None,
**request_args):
"""Activate a deactivated bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BounceActivateResponse`
"""
return _default_bounce_activate.activate(bounce_id, api_key=api_key,
secure=secure, test=test,
**request_args)
""" Messages """
class Message(object):
""" A container for message(s) to send to the Postmark API.
You can populate this message with defaults for initializing an
:class:`Interface`. The message will be combined with the final message
and verified before transmission.
:param sender: Email address of the sender.
:param to: Destination email address.
:param cc: A list of cc'd email addresses.
:param bcc: A list of bcc'd email address.
:param subject: The message subject.
:param tag: Tag your emails with this.
:param html: HTML body content.
:param text: Text body content.
:param reply_to: Email address to reply to.
:param headers: Additional headers to include with the email. If you do
not have the headers formatted for the Postmark API, use
:meth:`Message.add_header`.
:type headers: A list of `dict`, each with the keys 'Name' and
'Value'.
:param attachments: Attachments to include with the email. If you do not
have the attachments formatted for the Postmark API, use
:meth:`Message.attach_file` or :meth:`Message.attach_binary`.
:type attachments: A list of `dict`, each with the keys 'Name',
'Content' and 'ContentType'.
:param verify: Verify the message when initialized.
Defaults to `False`.
:param track_opens: Set to true to enable tracking email opens.
"""
_fields = {
'to': 'To',
'sender': 'From',
'cc': 'Cc',
'bcc': 'Bcc',
'subject': 'Subject',
'tag': 'Tag',
'template_id': 'TemplateId',
'template_alias': 'TemplateAlias',
'template_model': 'TemplateModel',
'html': 'HtmlBody',
'text': 'TextBody',
'reply_to': 'ReplyTo',
'headers': 'Headers',
'attachments': 'Attachments',
'track_opens': 'TrackOpens',
'message_stream': 'MessageStream'
}
_banned_extensions = ['vbs', 'exe', 'bin', 'bat', 'chm', 'com', 'cpl',
'crt', 'hlp', 'hta', 'inf', 'ins', 'isp', 'jse',
'lnk', 'mdb', 'pcd', 'pif', 'reg', 'scr', 'sct',
'shs', 'vbe', 'vba', 'wsf', 'wsh', 'wsl', 'msc',
'msi', 'msp', 'mst']
_to = None
_cc = None
_bcc = None
_default_content_type = 'application/octet-stream'
def __init__(self, sender=None, to=None, cc=None, bcc=None, subject=None,
template_id=None, template_alias=None, template_model=None,
tag=None, html=None, text=None, reply_to=None, headers=None,
attachments=None, verify=False, track_opens=None,
message_stream=None):
self.sender = sender
self.to = to
self.cc = cc
self.bcc = bcc
self.subject = subject
self.tag = tag
self.template_id = template_id
self.template_alias = template_alias
self.template_model = template_model
self.html = html
self.text = text
self.reply_to = reply_to
self.headers = headers
self.attachments = attachments
self.track_opens = track_opens
self.message_stream = message_stream
if verify:
self.verify()
def data(self):
"""Returns data formatted for a POST request to the Postmark send API.
:rtype: `dict`
"""
d = {}
for val, key in self._fields.items():
val = getattr(self, val)
if val is not None:
d[key] = val
return d
def json(self):
"""Return json-encoded string of message data.
:rtype: `str`
"""
return json.dumps(self.data(), ensure_ascii=True)
@classmethod
def load_message(self, message, **kwargs):
"""Create a :class:`Message` from a message data `dict`.
:param message: A `dict` of message data.
:param kwargs: Additional keyword arguments to construct
:class:`Message` with.
:rtype: :class:`Message`
"""
kwargs.update(message)
message = kwargs
try:
message = Message(**message)
except TypeError as e:
message = self._convert_postmark_to_native(kwargs)
if message:
message = Message(**message)
else:
raise e
return message
def load_from(self, other, **kwargs):
"""Create a :class:`Message` by merging `other` with `self`.
Values from `other` will be copied to `self` if the value was not
set on `self` and is set on `other`.
:param other: The :class:`Message` to copy defaults from.
:type other: :class:`Message`
:param kwargs: Additional keyword arguments to construct
:class:`Message` with.
:rtype: :class:`Message`
"""
data = self.data()
other_data = other.data()
for k, v in iteritems(other_data):
if data.get(k) is None:
data[k] = v
return self.load_message(data, **kwargs)
def add_header(self, name, value):
"""Attach an email header to send with the message.
:param name: The name of the header value.
:param value: The header value.
"""
if self.headers is None:
self.headers = []
self.headers.append(dict(Name=name, Value=value))
def attach_binary(self, data, filename, content_type=None,
content_id=None):
"""Attach a file to the message given raw binary data.
:param data: Raw data to attach to the message.
:param filename: Name of the file for the data.
:param content_type: mimetype of the data. It will be guessed from the
filename if not provided.
:param content_id: ContentID URL of the attachment. A RFC 2392-
compliant URL for the attachment that allows it to be referenced
from inside the body of the message. Must start with 'cid:'
"""
if self.attachments is None:
self.attachments = []
if content_type is None:
content_type = self._detect_content_type(filename)
attachment = {
'Name': filename,
'Content': b64encode(data).decode('utf-8'),
'ContentType': content_type
}
if content_id is not None:
if not content_id.startswith('cid:'):
raise MessageError('content_id parameter must be an '
'RFC-2392 URL starting with "cid:"')
attachment['ContentID'] = content_id
self.attachments.append(attachment)
def attach_file(self, filename, content_type=None,
content_id=None):
"""Attach a file to the message given a filename.
:param filename: Name of the file to attach.
:param content_type: mimetype of the data. It will be guessed from the
filename if not provided.
:param content_id: ContentID URL of the attachment. A RFC 2392-
compliant URL for the attachment that allows it to be referenced
from inside the body of the message. Must start with 'cid:'
"""
# Open the file, grab the filename, detect content type
name = os.path.basename(filename)
if not name:
err = 'Filename not found in path: {0}'
raise MessageError(err.format(filename))
with open(filename, 'rb') as f:
data = f.read()
self.attach_binary(data, name, content_type=content_type,
content_id=content_id)
def verify(self):
"""Verifies the message data based on rules and restrictions defined
in the Postmark API docs. There can be no more than 20 recipients
in total. NOTE: This does not check that your attachments total less
than 10MB, you must do that yourself.
"""
if self.to is None:
raise MessageError('"to" is required')
if self.html is None and self.text is None:
err = 'At least one of "html" or "text" must be provided'
raise MessageError(err)
self._verify_headers()
self._verify_attachments()
if (MAX_RECIPIENTS_PER_MESSAGE and
len(self.recipients) > MAX_RECIPIENTS_PER_MESSAGE):
err = 'No more than {0} recipients accepted.'
raise MessageError(err.format(MAX_RECIPIENTS_PER_MESSAGE))
@property
def recipients(self):
"""A list of all recipients for this message.
"""
cc = self._cc or []
bcc = self._bcc or []
return self._to + cc + bcc
@property
def to(self):
"""A comma delimited string of receivers for the message 'To'
field.
"""
if self._to is not None:
return ','.join(self._to)
@to.setter
def to(self, to):
"""
:param to: Email addresses for the 'To' API field.
:type to: :keyword:`list` or `str`
"""
if isinstance(to, basestring):
to = to.split(',')
self._to = to
@property
def cc(self):
"""A comma delimited string of receivers for the message 'Cc'
field.
"""
if self._cc is not None:
return ','.join(self._cc)
@cc.setter
def cc(self, cc):
"""
:param cc: Email addresses for the 'Cc' API field.
:type cc: :keyword:`list` or `str`
"""
if isinstance(cc, basestring):
cc = cc.split(',')
self._cc = cc
@property
def bcc(self):
"""A comma delimited string of receivers for the message 'Bcc'
field.
"""
if self._bcc is not None:
return ','.join(self._bcc)
@bcc.setter
def bcc(self, bcc):
"""
:param bcc: Email addresses for the 'Bcc' API field.
:type bcc: :keyword:`list` or `str`
"""
if isinstance(bcc, basestring):
bcc = bcc.split(',')
self._bcc = bcc
@classmethod
def _convert_postmark_to_native(cls, message):
"""Converts Postmark message API field names to their corresponding
:class:`Message` attribute names.
:param message: Postmark message data, with API fields using Postmark
API names.
:type message: `dict`
"""
d = {}
for dest, src in cls._fields.items():
if src in message:
d[dest] = message[src]
return d
def _detect_content_type(self, filename):
"""Determine the mimetype for a file.
:param filename: Filename of file to detect.
"""
name, ext = os.path.splitext(filename)
if not ext:
raise MessageError('File requires an extension.')
ext = ext.lower()
if ext.lstrip('.') in self._banned_extensions:
err = 'Extension "{0}" is not allowed.'
raise MessageError(err.format(ext))
if not mimetypes.inited:
mimetypes.init()
return mimetypes.types_map.get(ext, self._default_content_type)
def _verify_headers(self):
"""Verify that header values match the format expected by the Postmark
API.
"""
if self.headers is None:
return
self._verify_dict_list(self.headers, ('Name', 'Value'), 'Header')
def _verify_attachments(self):
"""Verify that attachment values match the format expected by the
Postmark API.
"""
if self.attachments is None:
return
keys = ('Name', 'Content', 'ContentType')
self._verify_dict_list(self.attachments, keys, 'Attachment')
def _verify_dict_list(self, values, keys, name):
"""Validate a list of `dict`, ensuring it has specific keys
and no others.
:param values: A list of `dict` to validate.
:param keys: A list of keys to validate each `dict` against.
:param name: Name describing the values, to show in error messages.
"""
keys = set(keys)
name = name.title()
for value in values:
if not isinstance(value, Mapping):
raise MessageError('Invalid {0} value'.format(name))
for key in keys:
if key not in value:
err = '{0} must contain "{1}"'
raise MessageError(err.format(name, key))
if set(value) - keys:
err = '{0} must contain only {1}'
words = ['"{0}"'.format(r) for r in sorted(keys)]
words = ' and '.join(words)
raise MessageError(err.format(name, words))
def __eq__(self, other):
"""If comparing to a `dict`, convert to a :class:`Message`
then compare data fields.
"""
if isinstance(other, Mapping):
other = self.__class__.load_message(other)
return self.data() == other.data()
def __ne__(self, other):
return not self.__eq__(other)
class BouncedMessage(object):
"""Bounced message data wrapper.
:param bounce_data: Raw bounced message data retrieved from
:class:`Bounce` or :class:`Bounces`.
:param sender: The :class:`Interface` that made the request for the
bounce data. Defaults to `None`.
"""
def __init__(self, bounce_data, sender=None):
self._data = bounce_data
self._sender = sender
self.id = bounce_data['ID']
self.type = bounce_data['Type']
self.message_id = bounce_data['MessageID']
self.type_code = bounce_data['TypeCode']
self.details = bounce_data['Details']
self.email = bounce_data['Email']
self.bounced_at = bounce_data['BouncedAt']
self.dump_available = bounce_data['DumpAvailable']
self.inactive = bounce_data['Inactive']
self.can_activate = bounce_data['CanActivate']
self.content = bounce_data.get('Content')
self.subject = bounce_data['Subject']
def dump(self, sender=None, **kwargs):
"""Retrieve raw email dump for this bounce.
:param sender: A :class:`BounceDump` object to get dump with.
Defaults to `None`.
:param kwargs: Keyword arguments passed to
:func:`requests.request`.
"""
if sender is None:
if self._sender is None:
sender = _default_bounce_dump
else:
sender = BounceDump(api_key=self._sender.api_key,
test=self._sender.test,
secure=self._sender.secure)
return sender.get(self.id, **kwargs)
class MessageConfirmation(object):
"""Wrapper around data returned from Postmark after sending
:param data: Data returned from Postmark upon sending a message
"""
def __init__(self, data):
self._data = data
self.error_code = data.get('ErrorCode', 0)
self.message = data.get('Message', 'OK')
self.id = data.get('MessageID', '')
self.submitted_at = data.get('SubmittedAt', '')
# TODO -- find out if 'To' is returned comma delimited list of
# emails when sent that way
self.to = data.get('To', '')
class BounceTypeData(object):
"""Bounce type data wrapper.
:param bounce_type_data: Raw bounce type data retrieved from
:class:`DeliveryStats`.
"""
def __init__(self, bounce_type_data):
self.count = bounce_type_data.get('Count', 0)
self.name = bounce_type_data['Name']
self.type = bounce_type_data.get('Type', 'All')
""" Response Wrappers """
class Response(object):
"""Base class for API response wrappers. The wrapped
:class:`requests.Response` object interface is exposed by this class,
unless the attribute is defined in `self._attrs`.
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
_attrs = []
def __init__(self, response, sender=None):
attrs = self._attrs
attrs += ['sender', '_data']
self._attrs = list(set(attrs))
self.sender = sender
try:
self._data = response.json()
except ValueError:
self._data = None
self._requests_response = response
def __getattribute__(self, k):
"""Gets attribute from `self` if attribute key is in `self._attrs`,
else get it from the wrapped :class:`requests.Response`.
"""
if k == '_attrs' or k in object.__getattribute__(self, '_attrs'):
return object.__getattribute__(self, k)
r = object.__getattribute__(self, '_requests_response')
if k == '_requests_response':
return r
return r.__getattribute__(k)
def __setattr__(self, k, v):
"""Sets attribute on `self` if attribute key is in `self._attrs`,
else sets it on the wrapped :class:`requests.Response`.
"""
if k in ['_attrs', '_requests_response'] or k in self._attrs:
object.__setattr__(self, k, v)
else:
self._requests_response.__setattr__(k, v)
def raise_for_status(self):
"""Raise Postmark-specific HTTP errors. If there isn't one, the
standard HTTP error is raised.
HTTP 401 raises :class:`UnauthorizedError`
HTTP 422 raises :class:`UnprocessableEntityError`
HTTP 500 raises :class:`InternalServerError`
"""
if self.status_code == 401:
raise UnauthorizedError(self._requests_response)
elif self.status_code == 422:
raise UnprocessableEntityError(self._requests_response)
elif self.status_code == 500:
raise InternalServerError(self._requests_response)
return self._requests_response.raise_for_status()
class SendResponse(Response):
"""Wrapper around :func:`Sender.send` and :func:`BatchSender.send`
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
_attrs = ['message', 'raise_for_status']
def __init__(self, response, sender=None):
super(SendResponse, self).__init__(response, sender=sender)
data = self._data or {}
self.message = MessageConfirmation(data)
class BatchSendResponse(Response):
"""Wrapper around :func:`Sender.send` and :func:`BatchSender.send`
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
_attrs = ['messages', 'raise_for_status']
def __init__(self, response, sender=None):
super(BatchSendResponse, self).__init__(response, sender=sender)
data = self._data or []
self.messages = [MessageConfirmation(msg) for msg in data]
class BatchTemplateSendResponse(Response):
"""Wrapper around :func:`Sender.send` and :func:`BatchTemplateSender.send`
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
_attrs = ['messages', 'raise_for_status']
def __init__(self, response, sender=None):
super(BatchTemplateSendResponse, self).__init__(
response, sender=sender)
data = self._data or []
self.messages = [MessageConfirmation(msg) for msg in data]
class BouncesResponse(Response):
"""Wrapper for responses from :func:`Bounces.get`.
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
_attrs = ['bounces', 'total']
def __init__(self, response, sender=None):
super(BouncesResponse, self).__init__(response, sender=sender)
data = self._data or {}
self.total = data.get('TotalCount', 0)
bounces = data.get('Bounces', [])
self.bounces = [BouncedMessage(bounce, sender=sender)
for bounce in bounces]
class BounceResponse(Response):
"""Wrapper for responses from :func:`Bounce.get`.
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
_attrs = ['bounce']
def __init__(self, response, sender=None):
super(BounceResponse, self).__init__(response, sender=sender)
if self._data is None:
self.bounce = None
else:
self.bounce = BouncedMessage(self._data, sender=sender)
class BounceDumpResponse(Response):
"""Wrapper for responses from :func:`BounceDump.get`.
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
def __init__(self, response, sender=None):
super(BounceDumpResponse, self).__init__(response, sender=sender)
data = self._data or {}
self.dump = data.get('Body')
class BounceTagsResponse(Response):
"""Wrapper for responses from :func:`BounceTags.get`.
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
def __init__(self, response, sender=None):
super(BounceTagsResponse, self).__init__(response, sender=sender)
self.tags = self._data or []
class OutboundMessageDetailsResponse(Response):
'''Wrapper for responses from :func:`OutboundMessageDetails.get`.
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
'''
def __init__(self, response, sender=None):
super(OutboundMessageDetailsResponse, self
).__init__(response, sender=sender)
self.raise_for_status()
self.message_details = self._data or {}
class DeliveryStatsResponse(Response):
"""Wrapper for responses from :func:`BounceActivate.activate`.
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
def __init__(self, response, sender=None):
super(DeliveryStatsResponse, self).__init__(response, sender=sender)
data = self._data or {}
self.inactive = data.get('InactiveMails', 0)
self.total = 0
bounces = data.get('Bounces', [])
self.bounces = {}
for bounce in bounces:
bounce = BounceTypeData(bounce)
self.bounces[bounce.type] = bounce
if bounce.type == 'All':
self.total = bounce.count
class BounceActivateResponse(Response):
"""Wrapper for responses from the bounce activate endpoint.
:param response: Response returned from :func:`requests.request`.
:type response: :class:`requests.Response`
:param sender: The API interface wrapper that generated the request.
Defaults to `None`.
:type sender: :class:`Interface`
"""
def __init__(self, response, sender=None):
super(BounceActivateResponse, self).__init__(response, sender=sender)
data = self._data or {}
self.message = data.get('Message', '')
bounce = data.get('Bounce')
if bounce is None:
self.bounce = None
else:
self.bounce = BouncedMessage(data['Bounce'], sender=sender)
""" Interfaces """
class Interface(object):
"""Base class interface for Postmark API endpoint wrappers
:param api_key: Your Postmark API key. Defaults to `None`.
:param secure: Use the https scheme for API requests.
Defaults to `True`.
:param test: Use the Postmark test API. Defaults to `False`.
"""
method = None
endpoint = None
response_class = Response
_headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
_api_key_header_name = 'X-Postmark-Server-Token'
def __init__(self, api_key=None, secure=True, test=False):
self.api_key = api_key
self.secure = secure
self.test = test
def _request(self, url, **kwargs):
"""Inner :func:`requests.request` wrapper.