|
| 1 | +from django.conf import settings |
| 2 | +from django.core.mail.backends.base import BaseEmailBackend |
| 3 | + |
| 4 | +from sparkpost import SparkPost |
| 5 | + |
| 6 | +from .exceptions import UnsupportedContent |
| 7 | +from .exceptions import UnsupportedParam |
| 8 | + |
| 9 | + |
| 10 | +class SparkPostEmailBackend(BaseEmailBackend): |
| 11 | + """ |
| 12 | + SparkPost wrapper for Django email backend |
| 13 | + """ |
| 14 | + |
| 15 | + def __init__(self, fail_silently=False, **kwargs): |
| 16 | + super(SparkPostEmailBackend, self)\ |
| 17 | + .__init__(fail_silently=fail_silently, **kwargs) |
| 18 | + |
| 19 | + sp_api_key = getattr(settings, 'SPARKPOST_API_KEY', None) |
| 20 | + |
| 21 | + self.client = SparkPost(sp_api_key) |
| 22 | + |
| 23 | + def send_messages(self, email_messages): |
| 24 | + """ |
| 25 | + Send emails, returns integer representing number of successful emails |
| 26 | + """ |
| 27 | + success = 0 |
| 28 | + for message in email_messages: |
| 29 | + try: |
| 30 | + response = self._send(message) |
| 31 | + success += response['total_accepted_recipients'] |
| 32 | + except Exception: |
| 33 | + if not self.fail_silently: |
| 34 | + raise |
| 35 | + return success |
| 36 | + |
| 37 | + def _send(self, message): |
| 38 | + self.check_unsupported(message) |
| 39 | + self.check_attachments(message) |
| 40 | + |
| 41 | + params = dict( |
| 42 | + recipients=message.to, |
| 43 | + text=message.body, |
| 44 | + from_email=message.from_email, |
| 45 | + subject=message.subject |
| 46 | + ) |
| 47 | + |
| 48 | + if hasattr(message, 'alternatives') and len(message.alternatives) > 0: |
| 49 | + for alternative in message.alternatives: |
| 50 | + |
| 51 | + if alternative[1] == 'text/html': |
| 52 | + params['html'] = alternative[0] |
| 53 | + else: |
| 54 | + raise UnsupportedContent( |
| 55 | + 'Content type %s is not supported' % alternative[1] |
| 56 | + ) |
| 57 | + |
| 58 | + return self.client.transmissions.send(**params) |
| 59 | + |
| 60 | + @staticmethod |
| 61 | + def check_attachments(message): |
| 62 | + if len(message.attachments): |
| 63 | + raise UnsupportedContent( |
| 64 | + 'The SparkPost Django email backend does not ' |
| 65 | + 'currently support attachment.' |
| 66 | + ) |
| 67 | + |
| 68 | + @staticmethod |
| 69 | + def check_unsupported(message): |
| 70 | + unsupported_params = ['cc', 'bcc', 'reply_to'] |
| 71 | + for param in unsupported_params: |
| 72 | + if len(getattr(message, param, [])): |
| 73 | + raise UnsupportedParam( |
| 74 | + 'The SparkPost Django email backend does not currently ' |
| 75 | + 'support %s.' % param |
| 76 | + ) |
0 commit comments