|
| 1 | +from django.core.mail import make_msgid |
| 2 | + |
| 3 | +from ..exceptions import AnymailImproperlyInstalled, AnymailRequestsAPIError |
| 4 | +from ..message import AnymailRecipientStatus |
| 5 | +from ..utils import get_anymail_setting, timestamp |
| 6 | + |
| 7 | +from .base_requests import AnymailRequestsBackend, RequestsPayload |
| 8 | + |
| 9 | +try: |
| 10 | + # noinspection PyUnresolvedReferences |
| 11 | + from requests.structures import CaseInsensitiveDict |
| 12 | +except ImportError: |
| 13 | + raise AnymailImproperlyInstalled('requests', backend="sendgrid") |
| 14 | + |
| 15 | + |
| 16 | +class SendGridBackend(AnymailRequestsBackend): |
| 17 | + """ |
| 18 | + SendGrid API Email Backend |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, **kwargs): |
| 22 | + """Init options from Django settings""" |
| 23 | + self.api_key = get_anymail_setting('SENDGRID_API_KEY', allow_bare=True) |
| 24 | + # This is SendGrid's Web API v2 (because the Web API v3 doesn't support sending) |
| 25 | + api_url = get_anymail_setting("SENDGRID_API_URL", "https://api.sendgrid.com/api/") |
| 26 | + if not api_url.endswith("/"): |
| 27 | + api_url += "/" |
| 28 | + super(SendGridBackend, self).__init__(api_url, **kwargs) |
| 29 | + |
| 30 | + def build_message_payload(self, message, defaults): |
| 31 | + return SendGridPayload(message, defaults, self) |
| 32 | + |
| 33 | + def parse_recipient_status(self, response, payload, message): |
| 34 | + parsed_response = self.deserialize_json_response(response, payload, message) |
| 35 | + try: |
| 36 | + sendgrid_message = parsed_response["message"] |
| 37 | + except (KeyError, TypeError): |
| 38 | + raise AnymailRequestsAPIError("Invalid SendGrid API response format", |
| 39 | + email_message=message, payload=payload, response=response) |
| 40 | + if sendgrid_message != "success": |
| 41 | + errors = parsed_response.get("errors", []) |
| 42 | + raise AnymailRequestsAPIError("SendGrid send failed: '%s'" % "; ".join(errors), |
| 43 | + email_message=message, payload=payload, response=response) |
| 44 | + # Simulate a per-recipient status of "queued": |
| 45 | + status = AnymailRecipientStatus(message_id=payload.message_id, status="queued") |
| 46 | + return {recipient.email: status for recipient in payload.all_recipients} |
| 47 | + |
| 48 | + |
| 49 | +class SendGridPayload(RequestsPayload): |
| 50 | + |
| 51 | + def __init__(self, message, defaults, backend, *args, **kwargs): |
| 52 | + self.all_recipients = [] # used for backend.parse_recipient_status |
| 53 | + self.message_id = None # Message-ID -- assigned in serialize_data unless provided in headers |
| 54 | + self.smtpapi = {} # SendGrid x-smtpapi field |
| 55 | + |
| 56 | + auth_headers = {'Authorization': 'Bearer ' + backend.api_key} |
| 57 | + super(SendGridPayload, self).__init__(message, defaults, backend, |
| 58 | + headers=auth_headers, *args, **kwargs) |
| 59 | + |
| 60 | + def get_api_endpoint(self): |
| 61 | + return "mail.send.json" |
| 62 | + |
| 63 | + def serialize_data(self): |
| 64 | + """Performs any necessary serialization on self.data, and returns the result.""" |
| 65 | + |
| 66 | + # Serialize x-smtpapi to json: |
| 67 | + if len(self.smtpapi) > 0: |
| 68 | + # If esp_extra was also used to set x-smtpapi, need to merge it |
| 69 | + if "x-smtpapi" in self.data: |
| 70 | + esp_extra_smtpapi = self.data["x-smtpapi"] |
| 71 | + self.smtpapi.update(esp_extra_smtpapi) # need to make this deep merge (for filters)! |
| 72 | + self.data["x-smtpapi"] = self.serialize_json(self.smtpapi) |
| 73 | + elif "x-smtpapi" in self.data: |
| 74 | + self.data["x-smtpapi"] = self.serialize_json(self.data["x-smtpapi"]) |
| 75 | + |
| 76 | + # Add our own message_id, and serialize extra headers to json: |
| 77 | + headers = self.data["headers"] |
| 78 | + try: |
| 79 | + self.message_id = headers["Message-ID"] |
| 80 | + except KeyError: |
| 81 | + self.message_id = headers["Message-ID"] = self.make_message_id() |
| 82 | + self.data["headers"] = self.serialize_json(dict(headers.items())) |
| 83 | + |
| 84 | + return self.data |
| 85 | + |
| 86 | + def make_message_id(self): |
| 87 | + """Returns a Message-ID that could be used for this payload |
| 88 | +
|
| 89 | + Tries to use the from_email's domain as the Message-ID's domain |
| 90 | + """ |
| 91 | + try: |
| 92 | + _, domain = self.data["from"].split("@") |
| 93 | + except (AttributeError, KeyError, TypeError, ValueError): |
| 94 | + domain = None |
| 95 | + return make_msgid(domain=domain) |
| 96 | + |
| 97 | + # |
| 98 | + # Payload construction |
| 99 | + # |
| 100 | + |
| 101 | + def init_payload(self): |
| 102 | + self.data = {} # {field: [multiple, values]} |
| 103 | + self.files = {} |
| 104 | + self.data['headers'] = CaseInsensitiveDict() # headers keys are case-insensitive |
| 105 | + |
| 106 | + def set_from_email(self, email): |
| 107 | + self.data["from"] = email.email |
| 108 | + if email.name: |
| 109 | + self.data["fromname"] = email.name |
| 110 | + |
| 111 | + def set_recipients(self, recipient_type, emails): |
| 112 | + assert recipient_type in ["to", "cc", "bcc"] |
| 113 | + if emails: |
| 114 | + self.data[recipient_type] = [email.email for email in emails] |
| 115 | + empty_name = " " # SendGrid API balks on complete empty name fields |
| 116 | + self.data[recipient_type + "name"] = [email.name or empty_name for email in emails] |
| 117 | + self.all_recipients += emails # used for backend.parse_recipient_status |
| 118 | + |
| 119 | + def set_subject(self, subject): |
| 120 | + self.data["subject"] = subject |
| 121 | + |
| 122 | + def set_reply_to(self, emails): |
| 123 | + # Note: SendGrid mangles the 'replyto' API param: it drops |
| 124 | + # all but the last email in a multi-address replyto, and |
| 125 | + # drops all the display names. [tested 2016-03-10] |
| 126 | + # |
| 127 | + # To avoid those quirks, we provide a fully-formed Reply-To |
| 128 | + # in the custom headers, which makes it through intact. |
| 129 | + if emails: |
| 130 | + reply_to = ", ".join([email.address for email in emails]) |
| 131 | + self.data["headers"]["Reply-To"] = reply_to |
| 132 | + |
| 133 | + def set_extra_headers(self, headers): |
| 134 | + # SendGrid requires header values to be strings -- not integers. |
| 135 | + # We'll stringify ints and floats; anything else is the caller's responsibility. |
| 136 | + # (This field gets converted to json in self.serialize_data) |
| 137 | + self.data["headers"].update({ |
| 138 | + k: str(v) if isinstance(v, (int, float)) else v |
| 139 | + for k, v in headers.items() |
| 140 | + }) |
| 141 | + |
| 142 | + def set_text_body(self, body): |
| 143 | + self.data["text"] = body |
| 144 | + |
| 145 | + def set_html_body(self, body): |
| 146 | + if "html" in self.data: |
| 147 | + # second html body could show up through multiple alternatives, or html body + alternative |
| 148 | + self.unsupported_feature("multiple html parts") |
| 149 | + self.data["html"] = body |
| 150 | + |
| 151 | + def add_attachment(self, attachment): |
| 152 | + filename = attachment.name or "" |
| 153 | + if attachment.inline: |
| 154 | + filename = filename or attachment.cid # must have non-empty name for the cid matching |
| 155 | + content_field = "content[%s]" % filename |
| 156 | + self.data[content_field] = attachment.cid |
| 157 | + |
| 158 | + files_field = "files[%s]" % filename |
| 159 | + if files_field in self.files: |
| 160 | + # It's possible SendGrid could actually handle this case (needs testing), |
| 161 | + # but requests doesn't seem to accept a list of tuples for a files field. |
| 162 | + # (See the MailgunBackend version for a different approach that might work.) |
| 163 | + self.unsupported_feature( |
| 164 | + "multiple attachments with the same filename ('%s')" % filename if filename |
| 165 | + else "multiple unnamed attachments") |
| 166 | + |
| 167 | + self.files[files_field] = (filename, attachment.content, attachment.mimetype) |
| 168 | + |
| 169 | + def set_metadata(self, metadata): |
| 170 | + self.smtpapi['unique_args'] = metadata |
| 171 | + |
| 172 | + def set_send_at(self, send_at): |
| 173 | + # Backend has converted pretty much everything to |
| 174 | + # a datetime by here; SendGrid expects unix timestamp |
| 175 | + self.smtpapi["send_at"] = int(timestamp(send_at)) # strip microseconds |
| 176 | + |
| 177 | + def set_tags(self, tags): |
| 178 | + self.smtpapi["category"] = tags |
| 179 | + |
| 180 | + def add_filter(self, filter_name, setting, val): |
| 181 | + self.smtpapi.setdefault('filters', {})\ |
| 182 | + .setdefault(filter_name, {})\ |
| 183 | + .setdefault('settings', {})[setting] = val |
| 184 | + |
| 185 | + def set_track_clicks(self, track_clicks): |
| 186 | + self.add_filter('clicktrack', 'enable', int(track_clicks)) |
| 187 | + |
| 188 | + def set_track_opens(self, track_opens): |
| 189 | + # SendGrid's opentrack filter also supports a "replace" |
| 190 | + # parameter, which Anymail doesn't offer directly. |
| 191 | + # (You could add it through esp_extra.) |
| 192 | + self.add_filter('opentrack', 'enable', int(track_opens)) |
| 193 | + |
| 194 | + def set_esp_extra(self, extra): |
| 195 | + self.data.update(extra) |
0 commit comments