File: email_backend.py

package info (click to toggle)
python-sparkpost 1.3.10-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 512 kB
  • sloc: python: 2,528; makefile: 31; sh: 10
file content (40 lines) | stat: -rw-r--r-- 1,302 bytes parent folder | download | duplicates (2)
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
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend

from sparkpost import SparkPost, US_API

from .message import SparkPostMessage


class SparkPostEmailBackend(BaseEmailBackend):
    """
    SparkPost wrapper for Django email backend
    """

    def __init__(self, fail_silently=False, **kwargs):
        super(SparkPostEmailBackend, self)\
            .__init__(fail_silently=fail_silently, **kwargs)

        sp_api_key = getattr(settings, 'SPARKPOST_API_KEY', None)
        sp_base_uri = getattr(settings, 'SPARKPOST_BASE_URI', US_API)

        self.client = SparkPost(sp_api_key, sp_base_uri)

    def send_messages(self, email_messages):
        """
        Send emails, returns integer representing number of successful emails
        """
        success = 0
        for message in email_messages:
            try:
                response = self._send(SparkPostMessage(message))
                success += response['total_accepted_recipients']
            except Exception:
                if not self.fail_silently:
                    raise
        return success

    def _send(self, message):
        params = getattr(settings, 'SPARKPOST_OPTIONS', {}).copy()
        params.update(message)
        return self.client.transmissions.send(**params)