|
| 1 | +from __future__ import absolute_import # we want the sparkpost package, not our own module |
| 2 | + |
| 3 | +from .base import AnymailBaseBackend, BasePayload |
| 4 | +from ..exceptions import AnymailAPIError, AnymailImproperlyInstalled, AnymailConfigurationError |
| 5 | +from ..message import AnymailRecipientStatus |
| 6 | +from ..utils import get_anymail_setting |
| 7 | + |
| 8 | +try: |
| 9 | + from sparkpost import SparkPost, SparkPostException |
| 10 | +except ImportError: |
| 11 | + raise AnymailImproperlyInstalled(missing_package='sparkpost', backend='sparkpost') |
| 12 | + |
| 13 | + |
| 14 | +class SparkPostBackend(AnymailBaseBackend): |
| 15 | + """ |
| 16 | + SparkPost Email Backend (using python-sparkpost client) |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, **kwargs): |
| 20 | + """Init options from Django settings""" |
| 21 | + super(SparkPostBackend, self).__init__(**kwargs) |
| 22 | + # SPARKPOST_API_KEY is optional - library reads from env by default |
| 23 | + self.api_key = get_anymail_setting('api_key', esp_name=self.esp_name, |
| 24 | + kwargs=kwargs, allow_bare=True, default=None) |
| 25 | + try: |
| 26 | + self.sp = SparkPost(self.api_key) # SparkPost API instance |
| 27 | + except SparkPostException as err: |
| 28 | + # This is almost certainly a missing API key |
| 29 | + raise AnymailConfigurationError( |
| 30 | + "Error initializing SparkPost: %s\n" |
| 31 | + "You may need to set ANYMAIL = {'SPARKPOST_API_KEY': ...} " |
| 32 | + "or ANYMAIL_SPARKPOST_API_KEY in your Django settings, " |
| 33 | + "or SPARKPOST_API_KEY in your environment." % str(err) |
| 34 | + ) |
| 35 | + |
| 36 | + # Note: SparkPost python API doesn't expose requests session sharing |
| 37 | + # (so there's no need to implement open/close connection management here) |
| 38 | + |
| 39 | + def build_message_payload(self, message, defaults): |
| 40 | + return SparkPostPayload(message, defaults, self) |
| 41 | + |
| 42 | + def post_to_esp(self, payload, message): |
| 43 | + params = payload.get_api_params() |
| 44 | + try: |
| 45 | + response = self.sp.transmissions.send(**params) |
| 46 | + except SparkPostException as err: |
| 47 | + raise AnymailAPIError( |
| 48 | + str(err), backend=self, email_message=message, payload=payload, |
| 49 | + response=getattr(err, 'response', None), # SparkPostAPIException requests.Response |
| 50 | + status_code=getattr(err, 'status', None), # SparkPostAPIException HTTP status_code |
| 51 | + ) |
| 52 | + return response |
| 53 | + |
| 54 | + def parse_recipient_status(self, response, payload, message): |
| 55 | + try: |
| 56 | + accepted = response['total_accepted_recipients'] |
| 57 | + rejected = response['total_rejected_recipients'] |
| 58 | + transmission_id = response['id'] |
| 59 | + except (KeyError, TypeError) as err: |
| 60 | + raise AnymailAPIError( |
| 61 | + "%s in SparkPost.transmissions.send result %r" % (str(err), response), |
| 62 | + backend=self, email_message=message, payload=payload, |
| 63 | + ) |
| 64 | + |
| 65 | + # SparkPost doesn't (yet*) tell us *which* recipients were accepted or rejected. |
| 66 | + # (* looks like undocumented 'rcpt_to_errors' might provide this info.) |
| 67 | + # If all are one or the other, we can report a specific status; |
| 68 | + # else just report 'unknown' for all recipients. |
| 69 | + recipient_count = len(payload.all_recipients) |
| 70 | + if accepted == recipient_count and rejected == 0: |
| 71 | + status = 'queued' |
| 72 | + elif rejected == recipient_count and accepted == 0: |
| 73 | + status = 'rejected' |
| 74 | + else: # mixed results, or wrong total |
| 75 | + status = 'unknown' |
| 76 | + recipient_status = AnymailRecipientStatus(message_id=transmission_id, status=status) |
| 77 | + return {recipient.email: recipient_status for recipient in payload.all_recipients} |
| 78 | + |
| 79 | + |
| 80 | +class SparkPostPayload(BasePayload): |
| 81 | + def init_payload(self): |
| 82 | + self.params = {} |
| 83 | + self.all_recipients = [] |
| 84 | + self.to_emails = [] |
| 85 | + self.merge_data = {} |
| 86 | + |
| 87 | + def get_api_params(self): |
| 88 | + # Compose recipients param from to_emails and merge_data (if any) |
| 89 | + recipients = [] |
| 90 | + for email in self.to_emails: |
| 91 | + rcpt = {'address': {'email': email.email}} |
| 92 | + if email.name: |
| 93 | + rcpt['address']['name'] = email.name |
| 94 | + try: |
| 95 | + rcpt['substitution_data'] = self.merge_data[email.email] |
| 96 | + except KeyError: |
| 97 | + pass # no merge_data or none for this recipient |
| 98 | + recipients.append(rcpt) |
| 99 | + if recipients: |
| 100 | + self.params['recipients'] = recipients |
| 101 | + |
| 102 | + return self.params |
| 103 | + |
| 104 | + def set_from_email(self, email): |
| 105 | + self.params['from_email'] = email.address |
| 106 | + |
| 107 | + def set_to(self, emails): |
| 108 | + if emails: |
| 109 | + self.to_emails = emails # bound to params['recipients'] in get_api_params |
| 110 | + self.all_recipients += emails |
| 111 | + |
| 112 | + def set_cc(self, emails): |
| 113 | + if emails: |
| 114 | + self.params['cc'] = [email.address for email in emails] |
| 115 | + self.all_recipients += emails |
| 116 | + |
| 117 | + def set_bcc(self, emails): |
| 118 | + if emails: |
| 119 | + self.params['bcc'] = [email.address for email in emails] |
| 120 | + self.all_recipients += emails |
| 121 | + |
| 122 | + def set_subject(self, subject): |
| 123 | + self.params['subject'] = subject |
| 124 | + |
| 125 | + def set_reply_to(self, emails): |
| 126 | + if emails: |
| 127 | + # reply_to is only documented as a single email, but this seems to work: |
| 128 | + self.params['reply_to'] = ', '.join([email.address for email in emails]) |
| 129 | + |
| 130 | + def set_extra_headers(self, headers): |
| 131 | + if headers: |
| 132 | + self.params['custom_headers'] = headers |
| 133 | + |
| 134 | + def set_text_body(self, body): |
| 135 | + self.params['text'] = body |
| 136 | + |
| 137 | + def set_html_body(self, body): |
| 138 | + if 'html' in self.params: |
| 139 | + # second html body could show up through multiple alternatives, or html body + alternative |
| 140 | + self.unsupported_feature("multiple html parts") |
| 141 | + self.params['html'] = body |
| 142 | + |
| 143 | + def add_attachment(self, attachment): |
| 144 | + if attachment.inline: |
| 145 | + param = 'inline_images' |
| 146 | + name = attachment.cid |
| 147 | + else: |
| 148 | + param = 'attachments' |
| 149 | + name = attachment.name or '' |
| 150 | + |
| 151 | + self.params.setdefault(param, []).append({ |
| 152 | + 'type': attachment.mimetype, |
| 153 | + 'name': name, |
| 154 | + 'data': attachment.b64content}) |
| 155 | + |
| 156 | + # Anymail-specific payload construction |
| 157 | + def set_metadata(self, metadata): |
| 158 | + self.params['metadata'] = metadata |
| 159 | + |
| 160 | + def set_send_at(self, send_at): |
| 161 | + try: |
| 162 | + self.params['start_time'] = send_at.replace(microsecond=0).isoformat() |
| 163 | + except (AttributeError, TypeError): |
| 164 | + self.params['start_time'] = send_at # assume user already formatted |
| 165 | + |
| 166 | + def set_tags(self, tags): |
| 167 | + if len(tags) > 0: |
| 168 | + self.params['campaign'] = tags[0] |
| 169 | + if len(tags) > 1: |
| 170 | + self.unsupported_feature('multiple tags (%r)' % tags) |
| 171 | + |
| 172 | + def set_track_clicks(self, track_clicks): |
| 173 | + self.params['track_clicks'] = track_clicks |
| 174 | + |
| 175 | + def set_track_opens(self, track_opens): |
| 176 | + self.params['track_opens'] = track_opens |
| 177 | + |
| 178 | + def set_template_id(self, template_id): |
| 179 | + # 'template' transmissions.send param becomes 'template_id' in API json 'content' |
| 180 | + self.params['template'] = template_id |
| 181 | + |
| 182 | + def set_merge_data(self, merge_data): |
| 183 | + self.merge_data = merge_data # merged into params['recipients'] in get_api_params |
| 184 | + |
| 185 | + def set_merge_global_data(self, merge_global_data): |
| 186 | + self.params['substitution_data'] = merge_global_data |
| 187 | + |
| 188 | + # ESP-specific payload construction |
| 189 | + def set_esp_extra(self, extra): |
| 190 | + self.params.update(extra) |
0 commit comments