# -*- coding: utf-8 -*-
import json
from base64 import b64encode, b64decode
from datetime import datetime
from decimal import Decimal
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
import six
from django.core import mail
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils.timezone import get_fixed_timezone, override as override_current_timezone
from anymail.exceptions import (AnymailAPIError, AnymailConfigurationError, AnymailSerializationError,
AnymailUnsupportedFeature)
from anymail.message import attach_inline_image_file
from .mock_requests_backend import RequestsBackendMockAPITestCase, SessionSharingTestCasesMixin
from .utils import sample_image_content, sample_image_path, SAMPLE_IMAGE_FILENAME, AnymailTestMixin
# noinspection PyUnresolvedReferences
longtype = int if six.PY3 else long # NOQA: F821
@override_settings(EMAIL_BACKEND='anymail.backends.sendinblue.EmailBackend',
ANYMAIL={'SENDINBLUE_API_KEY': 'test_api_key'})
class SendinBlueBackendMockAPITestCase(RequestsBackendMockAPITestCase):
# SendinBlue v3 success responses are empty
DEFAULT_RAW_RESPONSE = b'{"messageId":"<201801020304.1234567890@smtp-relay.mailin.fr>"}'
DEFAULT_STATUS_CODE = 201 # SendinBlue v3 uses '201 Created' for success (in most cases)
def setUp(self):
super(SendinBlueBackendMockAPITestCase, self).setUp()
# Simple message useful for many tests
self.message = mail.EmailMultiAlternatives('Subject', 'Text Body', 'from@example.com', ['to@example.com'])
class SendinBlueBackendStandardEmailTests(SendinBlueBackendMockAPITestCase):
"""Test backend support for Django standard email features"""
def test_send_mail(self):
"""Test basic API for simple send"""
mail.send_mail('Subject here', 'Here is the message.',
'from@sender.example.com', ['to@example.com'], fail_silently=False)
self.assert_esp_called('https://api.sendinblue.com/v3/smtp/email')
http_headers = self.get_api_call_headers()
self.assertEqual(http_headers["api-key"], "test_api_key")
self.assertEqual(http_headers["Content-Type"], "application/json")
data = self.get_api_call_json()
self.assertEqual(data['subject'], "Subject here")
self.assertEqual(data['textContent'], "Here is the message.")
self.assertEqual(data['sender'], {'email': "from@sender.example.com"})
def test_name_addr(self):
"""Make sure RFC2822 name-addr format (with display-name) is allowed
(Test both sender and recipient addresses)
"""
msg = mail.EmailMessage(
'Subject', 'Message', 'From Name This is an important message. This is an important message.
\u2019
') def test_embedded_images(self): # SendinBlue doesn't support inline image # inline image are just added as a content attachment image_filename = SAMPLE_IMAGE_FILENAME image_path = sample_image_path(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("And maybe second html, too
", "text/html") with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_non_html_alternative(self): self.message.body = "Text body" self.message.attach_alternative("{'maybe': 'allowed'}", "application/json") with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_api_failure(self): self.set_mock_response(status_code=400) with self.assertRaisesMessage(AnymailAPIError, "SendinBlue API response 400"): mail.send_mail('Subject', 'Body', 'from@example.com', ['to@example.com']) # Make sure fail_silently is respected self.set_mock_response(status_code=400) 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"""{ "code": "invalid_parameter", "message": "valid sender email required" }""" self.set_mock_response(status_code=400, raw=error_response) with self.assertRaises(AnymailAPIError) as cm: self.message.send() err = cm.exception self.assertIn("code", str(err)) self.assertIn("message", str(err)) # No content in the error response: self.set_mock_response(status_code=502, raw=None) with self.assertRaises(AnymailAPIError): self.message.send() class SendinBlueBackendAnymailFeatureTests(SendinBlueBackendMockAPITestCase): """Test backend support for Anymail added features""" def test_metadata(self): self.message.metadata = {'user_id': "12345", 'items': 6, 'float': 98.6, 'long': longtype(123)} self.message.send() data = self.get_api_call_json() metadata = json.loads(data['headers']['X-Mailin-custom']) self.assertEqual(metadata['user_id'], "12345") self.assertEqual(metadata['items'], 6) self.assertEqual(metadata['float'], 98.6) self.assertEqual(metadata['long'], longtype(123)) def test_send_at(self): utc_plus_6 = get_fixed_timezone(6 * 60) utc_minus_8 = get_fixed_timezone(-8 * 60) with override_current_timezone(utc_plus_6): # Timezone-aware datetime converted to UTC: self.message.send_at = datetime(2016, 3, 4, 5, 6, 7, tzinfo=utc_minus_8) with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_tag(self): self.message.tags = ["receipt"] self.message.send() data = self.get_api_call_json() self.assertCountEqual(data['headers']["X-Mailin-tag"], "receipt") def test_multiple_tags(self): self.message.tags = ["receipt", "repeat-user"] with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_tracking(self): # Test one way... self.message.track_clicks = False self.message.track_opens = True with self.assertRaises(AnymailUnsupportedFeature): self.message.send() # ...and the opposite way self.message.track_clicks = True self.message.track_opens = False with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_template_id(self): # SendinBlue use incremental ID to identify templates self.message.template_id = "12" self.message.merge_global_data = { 'buttonUrl': 'https://mydomain.com', } # SendinBlue doesn't support (if we use a template): # - subject # - body # - display name of emails self.message.subject = '' self.message.body = '' self.message.to = ['alice@example.com', 'bob@example.com'] self.message.cc = ['cc@example.com'] self.message.bcc = ['bcc@example.com'] self.message.reply_to = ['reply@example.com'] self.message.send() self.assert_esp_called('/v3/smtp/templates/12/send') data = self.get_api_call_json() self.assertEqual(data['emailTo'], ["alice@example.com", "bob@example.com"]) self.assertEqual(data['emailCc'], ["cc@example.com"]) self.assertEqual(data['emailBcc'], ["bcc@example.com"]) self.assertEqual(data['replyTo'], 'reply@example.com') self.assertEqual(data['attributes']['buttonUrl'], "https://mydomain.com") def test_template_id_with_empty_body(self): message = mail.EmailMessage(from_email='from@example.com', to=['to@example.com']) message.template_id = "9" message.send() data = self.get_api_call_json() self.assertNotIn('htmlcontent', data) self.assertNotIn('textContent', data) # neither text nor html body self.assertNotIn('subject', data) def test_merge_data(self): self.message.merge_data = { 'alice@example.com': {':name': "Alice", ':group': "Developers"}, 'bob@example.com': {':name': "Bob"}, # and leave :group undefined } with self.assertRaises(AnymailUnsupportedFeature): 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('attachment', data) self.assertNotIn('tag', data) self.assertNotIn('headers', data) self.assertNotIn('replyTo', data) self.assertNotIn('atributes', data) def test_esp_extra(self): self.message.tags = ["tag"] # SendinBlue doesn't offer any esp-extra but we will test # with some extra of SendGrid to see if it's work in the future self.message.esp_extra = { 'ip_pool_name': "transactional", 'asm': { # subscription management 'group_id': 1, }, 'tracking_settings': { 'subscription_tracking': { 'enable': True, 'substitution_tag': '[unsubscribe_url]', }, }, } self.message.send() data = self.get_api_call_json() # merged from esp_extra: self.assertEqual(data['ip_pool_name'], "transactional") self.assertEqual(data['asm'], {'group_id': 1}) self.assertEqual(data['tracking_settings']['subscription_tracking'], {'enable': True, 'substitution_tag': "[unsubscribe_url]"}) # make sure we didn't overwrite Anymail message options: self.assertEqual(data['headers']["X-Mailin-tag"], "tag") # noinspection PyUnresolvedReferences def test_send_attaches_anymail_status(self): """ The anymail_status should be attached to the message when it is sent """ # the DEFAULT_RAW_RESPONSE above is the *only* success response SendinBlue returns, # so no need to override it here msg = mail.EmailMessage('Subject', 'Message', 'from@example.com', ['to1@example.com'],) sent = msg.send() self.assertEqual(sent, 1) self.assertEqual(msg.anymail_status.status, {'queued'}) self.assertEqual(msg.anymail_status.recipients['to1@example.com'].status, 'queued') self.assertEqual(msg.anymail_status.esp_response.content, self.DEFAULT_RAW_RESPONSE) self.assertEqual( msg.anymail_status.message_id, json.loads(msg.anymail_status.esp_response.content.decode('utf-8'))['messageId'] ) self.assertEqual( msg.anymail_status.recipients['to1@example.com'].message_id, json.loads(msg.anymail_status.esp_response.content.decode('utf-8'))['messageId'] ) # 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.assertEqual(self.message.anymail_status.recipients, {}) self.assertIsNone(self.message.anymail_status.esp_response) def test_json_serialization_errors(self): """Try to provide more information about non-json-serializable data""" self.message.esp_extra = {'total': Decimal('19.99')} with self.assertRaises(AnymailSerializationError) as cm: self.message.send() err = cm.exception self.assertIsInstance(err, TypeError) # compatibility with json.dumps self.assertIn("Don't know how to send this data to SendinBlue", str(err)) # our added context self.assertRegex(str(err), r"Decimal.*is not JSON serializable") # original message class SendinBlueBackendRecipientsRefusedTests(SendinBlueBackendMockAPITestCase): """Should raise AnymailRecipientsRefused when *all* recipients are rejected or invalid""" # SendinBlue doesn't check email bounce or complaint lists at time of send -- # it always just queues the message. You'll need to listen for the "rejected" # and "failed" events to detect refused recipients. pass # not applicable to this backend class SendinBlueBackendSessionSharingTestCase(SessionSharingTestCasesMixin, SendinBlueBackendMockAPITestCase): """Requests session sharing tests""" pass # tests are defined in the mixin @override_settings(EMAIL_BACKEND="anymail.backends.sendinblue.EmailBackend") class SendinBlueBackendImproperlyConfiguredTests(SimpleTestCase, AnymailTestMixin): """Test ESP backend without required settings in place""" def test_missing_auth(self): with self.assertRaisesRegex(AnymailConfigurationError, r'\bSENDINBLUE_API_KEY\b'): mail.send_mail('Subject', 'Message', 'from@example.com', ['to@example.com'])