This is an important message.
' + email = mail.EmailMultiAlternatives('Subject', text_content, + 'from@example.com', ['to@example.com']) + email.attach_alternative(html_content, "text/html") + email.send() + data = self.get_api_call_json() + self.assertEqual(data['TextBody'], text_content) + self.assertEqual(data['HtmlBody'], html_content) + # Don't accidentally send the html part as an attachment: + self.assertNotIn('Attachments', data) + + def test_html_only_message(self): + html_content = 'This is an important message.
' + email = mail.EmailMessage('Subject', html_content, 'from@example.com', ['to@example.com']) + email.content_subtype = "html" # Main content is now text/html + email.send() + data = self.get_api_call_json() + self.assertNotIn('TextBody', data) + self.assertEqual(data['HtmlBody'], html_content) + + def test_extra_headers(self): + self.message.extra_headers = {'X-Custom': 'string', 'X-Num': 123} + self.message.send() + data = self.get_api_call_json() + self.assertCountEqual(data['Headers'], [ + {'Name': 'X-Custom', 'Value': 'string'}, + {'Name': 'X-Num', 'Value': 123} + ]) + + def test_extra_headers_serialization_error(self): + self.message.extra_headers = {'X-Custom': Decimal(12.5)} + with self.assertRaisesMessage(AnymailSerializationError, "Decimal('12.5')"): + self.message.send() + + def test_reply_to(self): + # reply_to is new in Django 1.8 -- before that, you can simply include it in headers + try: + # noinspection PyArgumentList + email = mail.EmailMessage('Subject', 'Body goes here', 'from@example.com', ['to1@example.com'], + reply_to=['reply@example.com', 'Other\u2019
', mimetype='text/html') + self.message.send() + data = self.get_api_call_json() + self.assertEqual(data['Attachments'], [{ + 'Name': 'Une pièce jointe.html', + 'ContentType': 'text/html', + 'Content': b64encode('\u2019
'.encode('utf-8')).decode('ascii') + }]) + + def test_embedded_images(self): + image_filename = SAMPLE_IMAGE_FILENAME + image_path = sample_image_path(image_filename) + image_data = sample_image_content(image_filename) + + cid = attach_inline_image_file(self.message, image_path) # Read from a png file + html_content = 'This has an image.
First html is OK
", "text/html") + self.message.attach_alternative("But not second html
", "text/html") + with self.assertRaises(AnymailUnsupportedFeature): + self.message.send() + + def test_html_alternative(self): + # Only html alternatives allowed + self.message.attach_alternative("{'not': 'allowed'}", "application/json") + with self.assertRaises(AnymailUnsupportedFeature): + self.message.send() + + def test_alternatives_fail_silently(self): + # Make sure fail_silently is respected + self.message.attach_alternative("{'not': 'allowed'}", "application/json") + sent = self.message.send(fail_silently=True) + self.assert_esp_not_called("API should not be called when send fails silently") + self.assertEqual(sent, 0) + + def test_suppress_empty_address_lists(self): + """Empty to, cc, bcc, and reply_to shouldn't generate empty fields""" + self.message.send() + data = self.get_api_call_json() + self.assertNotIn('Cc', data) + self.assertNotIn('Bcc', data) + self.assertNotIn('ReplyTo', data) + + # Test empty `to` -- but send requires at least one recipient somewhere (like cc) + self.message.to = [] + self.message.cc = ['cc@example.com'] + self.message.send() + data = self.get_api_call_json() + self.assertNotIn('To', data) + + def test_api_failure(self): + self.set_mock_response(status_code=500) + with self.assertRaises(AnymailAPIError): + sent = mail.send_mail('Subject', 'Body', 'from@example.com', ['to@example.com']) + self.assertEqual(sent, 0) + + # Make sure fail_silently is respected + self.set_mock_response(status_code=500) + sent = mail.send_mail('Subject', 'Body', 'from@example.com', ['to@example.com'], fail_silently=True) + self.assertEqual(sent, 0) + + def test_api_error_includes_details(self): + """AnymailAPIError should include ESP's error message""" + # JSON error response: + error_response = b"""{ + "ErrorCode": 451, + "Message": "Helpful explanation from Postmark." + }""" + self.set_mock_response(status_code=200, raw=error_response) + with self.assertRaisesMessage(AnymailAPIError, "Helpful explanation from Postmark"): + self.message.send() + + # Non-JSON error response: + self.set_mock_response(status_code=500, raw=b"Ack! Bad proxy!") + with self.assertRaisesMessage(AnymailAPIError, "Ack! Bad proxy!"): + self.message.send() + + # No content in the error response: + self.set_mock_response(status_code=502, raw=None) + with self.assertRaises(AnymailAPIError): + self.message.send() + + +class PostmarkBackendAnymailFeatureTests(PostmarkBackendMockAPITestCase): + """Test backend support for Anymail added features""" + + def test_metadata(self): + self.message.metadata = {'user_id': "12345", 'items': 6} + with self.assertRaisesMessage(AnymailUnsupportedFeature, 'metadata'): + self.message.send() + + def test_send_at(self): + self.message.send_at = 1651820889 # 2022-05-06 07:08:09 UTC + with self.assertRaisesMessage(AnymailUnsupportedFeature, 'send_at'): + self.message.send() + + def test_tags(self): + self.message.tags = ["receipt"] + self.message.send() + data = self.get_api_call_json() + self.assertEqual(data['Tag'], "receipt") + + self.message.tags = ["receipt", "repeat-user"] + with self.assertRaisesMessage(AnymailUnsupportedFeature, 'multiple tags'): + self.message.send() + + def test_track_opens(self): + self.message.track_opens = True + self.message.send() + data = self.get_api_call_json() + self.assertEqual(data['TrackOpens'], True) + + def test_track_clicks(self): + self.message.track_clicks = True + with self.assertRaisesMessage(AnymailUnsupportedFeature, 'track_clicks'): + self.message.send() + + def test_default_omits_options(self): + """Make sure by default we don't send any ESP-specific options. + + Options not specified by the caller should be omitted entirely from + the API call (*not* sent as False or empty). This ensures + that your ESP account settings apply by default. + """ + self.message.send() + data = self.get_api_call_json() + self.assertNotIn('Tag', data) + self.assertNotIn('TrackOpens', data) + + def test_esp_extra(self): + self.message.esp_extra = { + 'FuturePostmarkOption': 'some-value', + } + self.message.send() + data = self.get_api_call_json() + self.assertEqual(data['FuturePostmarkOption'], 'some-value') + + def test_message_server_token(self): + # Can override server-token on a per-message basis: + self.message.esp_extra = { + 'server_token': 'token_for_this_message_only', + } + self.message.send() + headers = self.get_api_call_headers() + self.assertEqual(headers["X-Postmark-Server-Token"], "token_for_this_message_only") + data = self.get_api_call_json() + self.assertNotIn('server_token', data) # not in the json + + # noinspection PyUnresolvedReferences + def test_send_attaches_anymail_status(self): + """ The anymail_status should be attached to the message when it is sent """ + response_content = b"""{ + "MessageID":"abcdef01-2345-6789-0123-456789abcdef", + "ErrorCode":0, + "Message":"OK" + }""" + self.set_mock_response(raw=response_content) + msg = mail.EmailMessage('Subject', 'Message', 'from@example.com', ['to1@example.com'],) + sent = msg.send() + self.assertEqual(sent, 1) + self.assertEqual(msg.anymail_status.status, {'sent'}) + self.assertEqual(msg.anymail_status.message_id, 'abcdef01-2345-6789-0123-456789abcdef') + self.assertEqual(msg.anymail_status.recipients['to1@example.com'].status, 'sent') + self.assertEqual(msg.anymail_status.recipients['to1@example.com'].message_id, + 'abcdef01-2345-6789-0123-456789abcdef') + self.assertEqual(msg.anymail_status.esp_response.content, response_content) + + # noinspection PyUnresolvedReferences + def test_send_failed_anymail_status(self): + """ If the send fails, anymail_status should contain initial values""" + self.set_mock_response(status_code=500) + sent = self.message.send(fail_silently=True) + self.assertEqual(sent, 0) + self.assertIsNone(self.message.anymail_status.status) + self.assertIsNone(self.message.anymail_status.message_id) + self.assertEqual(self.message.anymail_status.recipients, {}) + self.assertIsNone(self.message.anymail_status.esp_response) + + # noinspection PyUnresolvedReferences + def test_send_unparsable_response(self): + """If the send succeeds, but a non-JSON API response, should raise an API exception""" + mock_response = self.set_mock_response(status_code=200, + raw=b"yikes, this isn't a real response") + with self.assertRaises(AnymailAPIError): + self.message.send() + self.assertIsNone(self.message.anymail_status.status) + self.assertIsNone(self.message.anymail_status.message_id) + self.assertEqual(self.message.anymail_status.recipients, {}) + self.assertEqual(self.message.anymail_status.esp_response, mock_response) + + def test_json_serialization_errors(self): + """Try to provide more information about non-json-serializable data""" + self.message.tags = [Decimal('19.99')] # yeah, don't do this + with self.assertRaises(AnymailSerializationError) as cm: + self.message.send() + print(self.get_api_call_json()) + err = cm.exception + self.assertIsInstance(err, TypeError) # compatibility with json.dumps + self.assertIn("Don't know how to send this data to Postmark", str(err)) # our added context + self.assertIn("Decimal('19.99') is not JSON serializable", str(err)) # original message + + +class PostmarkBackendRecipientsRefusedTests(PostmarkBackendMockAPITestCase): + """Should raise AnymailRecipientsRefused when *all* recipients are rejected or invalid""" + + def test_recipients_inactive(self): + self.set_mock_response( + status_code=422, + raw=b'{"ErrorCode":406,' + b'"Message":"You tried to send to a recipient that has been marked as inactive.\\n' + b'Found inactive addresses: hardbounce@example.com, spam@example.com.\\n' + b'Inactive recipients are ones that have generated a hard bounce or a spam complaint."}' + ) + msg = mail.EmailMessage('Subject', 'Body', 'from@example.com', + ['hardbounce@example.com', 'Hates SpamHTML content
', "text/html") + + def test_simple_send(self): + # Example of getting the SendGrid send status and message id from the message + sent_count = self.message.send() + self.assertEqual(sent_count, 1) + + anymail_status = self.message.anymail_status + sent_status = anymail_status.recipients['to@example.com'].status + message_id = anymail_status.recipients['to@example.com'].message_id + + self.assertEqual(sent_status, 'sent') + self.assertGreater(len(message_id), 0) # non-empty string + self.assertEqual(anymail_status.status, {sent_status}) # set of all recipient statuses + self.assertEqual(anymail_status.message_id, message_id) + + def test_all_options(self): + message = AnymailMessage( + subject="Anymail all-options integration test", + body="This is the text body", + from_email="Test FromHTML: with link"
+ "and image: " % cid,
+ "text/html")
+
+ message.send()
+ self.assertEqual(message.anymail_status.status, {'sent'})
+
+ def test_invalid_from(self):
+ self.message.from_email = 'webmaster@localhost' # Django's default From
+ with self.assertRaises(AnymailAPIError) as cm:
+ self.message.send()
+ err = cm.exception
+ self.assertEqual(err.status_code, 422)
+ self.assertIn("Invalid 'From' address", str(err))
+
+ @override_settings(ANYMAIL_POSTMARK_SERVER_TOKEN="Hey, that's not a server token!")
+ def test_invalid_server_token(self):
+ with self.assertRaises(AnymailAPIError) as cm:
+ self.message.send()
+ err = cm.exception
+ self.assertEqual(err.status_code, 401)
+ # Make sure the exception message includes Postmark's response:
+ self.assertIn("Bad or missing Server API token", str(err))
diff --git a/docs/esps/postmark.rst b/docs/esps/postmark.rst
index 815b417..90c1e9a 100644
--- a/docs/esps/postmark.rst
+++ b/docs/esps/postmark.rst
@@ -1,17 +1,115 @@
-.. _postmark:
+.. _postmark-backend:
Postmark
---------
+========
-.. note::
+Anymail integrates with the `Postmark`_ transactional email service,
+using their `HTTP email API`_.
- Postmark support coming soon
+.. _Postmark: https://postmarkapp.com/
+.. _HTTP email API: http://developer.postmarkapp.com/developer-api-email.html
Settings
-========
+--------
- EMAIL_BACKEND = "anymail.backends.postmark.PostmarkBackend"
+.. rubric:: EMAIL_BACKEND
-(Watch your capitalization: Postmark spells their name with a
+To use Anymail's Postmark backend, set:
+
+ .. code-block:: python
+
+ EMAIL_BACKEND = "anymail.backends.postmark.PostmarkBackend"
+
+in your settings.py. (Watch your capitalization: Postmark spells their name with a
lowercase "m", so Anymail does too.)
+
+
+.. setting:: ANYMAIL_POSTMARK_SERVER_TOKEN
+
+.. rubric:: POSTMARK_SERVER_TOKEN
+
+Required. A Postmark server token.
+
+ .. code-block:: python
+
+ ANYMAIL = {
+ ...
+ "POSTMARK_SERVER_TOKEN": "